diff --git a/dev_docs/contributing/how_we_use_github.mdx b/dev_docs/contributing/how_we_use_github.mdx new file mode 100644 index 000000000000..f18bcbcf556f --- /dev/null +++ b/dev_docs/contributing/how_we_use_github.mdx @@ -0,0 +1,155 @@ +--- +id: kibGitHub +slug: /kibana-dev-docs/github +title: How we use Github +summary: Forking, branching, committing and using labels in the Kibana GitHub repo +date: 2021-09-16 +tags: ['contributor', 'dev', 'github', 'getting started', 'onboarding', 'kibana'] +--- + +## Forking + +We follow the [GitHub forking model](https://help.github.com/articles/fork-a-repo/) for collaborating on Kibana code. This model assumes that you have a remote called upstream which points to the official Kibana repo, which we’ll refer to in later code snippets. + +## Branching + +At Elastic, all products in the stack, including Kibana, are released at the same time with the same version number. Most of these projects have the following branching strategy: + +- master is the next major version. +- `.x` is the next minor version. +- `.` is the next release of a minor version, including patch releases. + +As an example, let’s assume that the 7.x branch is currently a not-yet-released 7.6.0. Once 7.6.0 has reached feature freeze, it will be branched to 7.6 and 7.x will be updated to reflect 7.7.0. The release of 7.6.0 and subsequent patch releases will be cut from the 7.6 branch. At any time, you can verify the current version of a branch by inspecting the version attribute in the package.json file within the Kibana source. + +Pull requests are made into the master branch and then backported when it is safe and appropriate. + +- Breaking changes do not get backported and only go into master. +- All non-breaking changes can be backported to the `.x` branch. +- Features should not be backported to a `.` branch. +- Bug fixes can be backported to a `.` branch if the changes are safe and appropriate. Safety is a judgment call you make based on factors like the bug’s severity, test coverage, confidence in the changes, etc. Your reasoning should be included in the pull request description. +- Documentation changes can be backported to any branch at any time. + +## Commits and Merging + +- Feel free to make as many commits as you want, while working on a branch. +- When submitting a PR for review, please perform an interactive rebase to present a logical history that’s easy for the reviewers to follow. +- Please use your commit messages to include helpful information on your changes, e.g. changes to APIs, UX changes, bugs fixed, and an explanation of why you made the changes that you did. +- Resolve merge conflicts by rebasing the target branch over your feature branch, and force-pushing (see below for instructions). +- When merging, we’ll squash your commits into a single commit. + +### Rebasing and fixing merge conflicts + +Rebasing can be tricky, and fixing merge conflicts can be even trickier because it involves force pushing. This is all compounded by the fact that attempting to push a rebased branch remotely will be rejected by git, and you’ll be prompted to do a pull, which is not at all what you should do (this will really mess up your branch’s history). + +Here’s how you should rebase master onto your branch, and how to fix merge conflicts when they arise. + +First, make sure master is up-to-date. + +```bash +git checkout master +git fetch upstream +git rebase upstream/master +``` + +Then, check out your branch and rebase master on top of it, which will apply all of the new commits on master to your branch, and then apply all of your branch’s new commits after that. + +```bash +git checkout name-of-your-branch +git rebase master +``` + +You want to make sure there are no merge conflicts. If there are merge conflicts, git will pause the rebase and allow you to fix the conflicts before continuing. + +You can use git status to see which files contain conflicts. They’ll be the ones that aren’t staged for commit. Open those files, and look for where git has marked the conflicts. Resolve the conflicts so that the changes you want to make to the code have been incorporated in a way that doesn’t destroy work that’s been done in master. Refer to master’s commit history on GitHub if you need to gain a better understanding of how code is conflicting and how best to resolve it. + +Once you’ve resolved all of the merge conflicts, use git add -A to stage them to be committed, and then use git rebase --continue to tell git to continue the rebase. + +When the rebase has completed, you will need to force push your branch because the history is now completely different than what’s on the remote. This is potentially dangerous because it will completely overwrite what you have on the remote, so you need to be sure that you haven’t lost any work when resolving merge conflicts. (If there weren’t any merge conflicts, then you can force push without having to worry about this.) + +```bash +git push origin name-of-your-branch --force +``` + +This will overwrite the remote branch with what you have locally. You’re done! + +**Note that you should not run git pull**, for example in response to a push rejection like this: + +```bash +! [rejected] name-of-your-branch -> name-of-your-branch (non-fast-forward) +error: failed to push some refs to 'https://github.com/YourGitHubHandle/kibana.git' +hint: Updates were rejected because the tip of your current branch is behind +hint: its remote counterpart. Integrate the remote changes (e.g. +hint: 'git pull ...') before pushing again. +hint: See the 'Note about fast-forwards' in 'git push --help' for details. +``` + +Assuming you’ve successfully rebased and you’re happy with the code, you should force push instead. + +## Creating a pull request + +See [Submitting a pull request](https://www.elastic.co/guide/en/kibana/master/development-pull-request.html) for the next steps on getting your code changes merged into Kibana. + +## Labels + +The following information notes how we use GitHub labels in Kibana. Note that only internal Elasticians are able to create and assign labels to issues, but for searching purposes, the information is likely useful for external developers as well. + +Many of our labels follow the pattern of `{key}:{value}`. + + +Use PascalCase when creating new labels. + +Teams can create labels at their own discretion, but we have over 600 labels at the time of this writing. +Consider using an existing convention before creating a new one. If you think a new label or convention +would be useful to all teams, talk to your team or tech lead about getting it added here. + + + +### Team labels + +Examples: `Team:Security`, `Team:Operations`. + +These labels map the issue to the team that owns the particular area. Part of the responsibilities of +(todo) is to ensure every issue has at least a team or a project +label. + + + View our org chart [here](https://wiki.elastic.co/display/DEV/Kibana+Team+Organization) to view + all our teams and appropriate contacts. + + +### Feature labels + +Examples: `Feature:Lens`, `Feature:TSVB`, `Feature:Vega`. + +Feature labels break down architectural domains that are owned by a given team. + +### Project labels + +Examples: `Project:RuntimeFields`, `Project:MakeItSlow`. + +Sometimes issues span multiple teams, that is often when Project labels are more appropriate. To avoid too much noise, +these should be used for high visibility projects. Try not to use project labels for small, single team projects, where a team +and feature label would be applicable. Use your best judgement when determining whether to add a new project label. + +### Needed For labels (`NeededFor:{Team}`) + +Examples: `NeededFor:APM`, `NeededFor:AppServices`. + +We use these labels to help us organize internal dependencies. An issue with the labels +`NeededFor:APM` and `Team:AppServices` means APM has a dependency on the App services team. The owning team +can filter on these labels during roadmap prioritization, and the dependent team can use these labels to +search and view the status of its dependencies. To avoid noise, use these labels for high priority requests that +need to be taken into account in roadmap planning. A low priority item that can be prioritized along with +other community requests does not need this label, as part of its usefulness is helping teams wade through the noise +of external feature requests. + +### Version labels + +Examples: `v7.9.2`, `v8.0` + +We use version labels on PRs to indicate which versions a PR will be merged into. For issues, +teams use these labels inconsistently. On a bug, it might mean the version the bug was found in, or +it might mean the version the team is tentatively planning to merge a fix. + +Consult the owning team if you have a question about how a version label is meant +to be used on an issue. diff --git a/docs/development/core/server/kibana-plugin-core-server.deprecationsservicesetup.md b/docs/development/core/server/kibana-plugin-core-server.deprecationsservicesetup.md index 2bc7f6cba594..7b2cbdecd146 100644 --- a/docs/development/core/server/kibana-plugin-core-server.deprecationsservicesetup.md +++ b/docs/development/core/server/kibana-plugin-core-server.deprecationsservicesetup.md @@ -27,7 +27,6 @@ async function getDeprecations({ esClient, savedObjectsClient }: GetDeprecations const deprecations: DeprecationsDetails[] = []; const count = await getFooCount(savedObjectsClient); if (count > 0) { - // Example of a manual correctiveAction deprecations.push({ title: i18n.translate('xpack.foo.deprecations.title', { defaultMessage: `Foo's are deprecated` diff --git a/docs/development/core/server/kibana-plugin-core-server.opsmetrics.md b/docs/development/core/server/kibana-plugin-core-server.opsmetrics.md index 1572c1ae3131..4774215cef07 100644 --- a/docs/development/core/server/kibana-plugin-core-server.opsmetrics.md +++ b/docs/development/core/server/kibana-plugin-core-server.opsmetrics.md @@ -19,7 +19,7 @@ export interface OpsMetrics | [collected\_at](./kibana-plugin-core-server.opsmetrics.collected_at.md) | Date | Time metrics were recorded at. | | [concurrent\_connections](./kibana-plugin-core-server.opsmetrics.concurrent_connections.md) | OpsServerMetrics['concurrent_connections'] | number of current concurrent connections to the server | | [os](./kibana-plugin-core-server.opsmetrics.os.md) | OpsOsMetrics | OS related metrics | -| [process](./kibana-plugin-core-server.opsmetrics.process.md) | OpsProcessMetrics | Process related metrics. Deprecated in favor of processes field. | +| [process](./kibana-plugin-core-server.opsmetrics.process.md) | OpsProcessMetrics | Process related metrics. | | [processes](./kibana-plugin-core-server.opsmetrics.processes.md) | OpsProcessMetrics[] | Process related metrics. Reports an array of objects for each kibana pid. | | [requests](./kibana-plugin-core-server.opsmetrics.requests.md) | OpsServerMetrics['requests'] | server requests stats | | [response\_times](./kibana-plugin-core-server.opsmetrics.response_times.md) | OpsServerMetrics['response_times'] | server response time stats | diff --git a/docs/development/core/server/kibana-plugin-core-server.opsmetrics.process.md b/docs/development/core/server/kibana-plugin-core-server.opsmetrics.process.md index 9da2c0644dc8..6e686f189aee 100644 --- a/docs/development/core/server/kibana-plugin-core-server.opsmetrics.process.md +++ b/docs/development/core/server/kibana-plugin-core-server.opsmetrics.process.md @@ -6,9 +6,10 @@ > Warning: This API is now obsolete. > +> use the processes field instead. > -Process related metrics. Deprecated in favor of processes field. +Process related metrics. Signature: diff --git a/examples/bfetch_explorer/public/mount.tsx b/examples/bfetch_explorer/public/mount.tsx index 58ab3a609ad5..8c15405f2f6b 100644 --- a/examples/bfetch_explorer/public/mount.tsx +++ b/examples/bfetch_explorer/public/mount.tsx @@ -20,17 +20,16 @@ export interface BfetchDeps { explorer: ExplorerService; } -export const mount = ( - coreSetup: CoreSetup, - explorer: ExplorerService -) => async ({ appBasePath, element }: AppMountParameters) => { - const [core, plugins] = await coreSetup.getStartServices(); - const deps: BfetchDeps = { appBasePath, core, plugins, explorer }; - const reactElement = ( - - - - ); - render(reactElement, element); - return () => unmountComponentAtNode(element); -}; +export const mount = + (coreSetup: CoreSetup, explorer: ExplorerService) => + async ({ appBasePath, element }: AppMountParameters) => { + const [core, plugins] = await coreSetup.getStartServices(); + const deps: BfetchDeps = { appBasePath, core, plugins, explorer }; + const reactElement = ( + + + + ); + render(reactElement, element); + return () => unmountComponentAtNode(element); + }; diff --git a/examples/dashboard_embeddable_examples/public/plugin.tsx b/examples/dashboard_embeddable_examples/public/plugin.tsx index 57678f5a2a51..5fd3e01f2ca7 100644 --- a/examples/dashboard_embeddable_examples/public/plugin.tsx +++ b/examples/dashboard_embeddable_examples/public/plugin.tsx @@ -33,7 +33,8 @@ export class DashboardEmbeddableExamples implements Plugin - implements ReferenceOrValueEmbeddable { + implements ReferenceOrValueEmbeddable +{ public readonly type = BOOK_EMBEDDABLE; private subscription: Subscription; private node?: HTMLElement; diff --git a/examples/embeddable_examples/public/book/book_embeddable_factory.tsx b/examples/embeddable_examples/public/book/book_embeddable_factory.tsx index a16c50db8b10..727e0fd18a52 100644 --- a/examples/embeddable_examples/public/book/book_embeddable_factory.tsx +++ b/examples/embeddable_examples/public/book/book_embeddable_factory.tsx @@ -52,7 +52,8 @@ export class BookEmbeddableFactoryDefinition BookEmbeddableOutput, BookEmbeddable, BookSavedObjectAttributes - > { + > +{ public readonly type = BOOK_EMBEDDABLE; public savedObjectMetaData = { name: 'Book', @@ -116,10 +117,8 @@ export class BookEmbeddableFactoryDefinition private async unwrapMethod(savedObjectId: string): Promise { const { savedObjectsClient } = await this.getStartServices(); - const savedObject: SimpleSavedObject = await savedObjectsClient.get( - this.type, - savedObjectId - ); + const savedObject: SimpleSavedObject = + await savedObjectsClient.get(this.type, savedObjectId); return { ...savedObject.attributes }; } diff --git a/examples/embeddable_examples/public/list_container/list_container_factory.ts b/examples/embeddable_examples/public/list_container/list_container_factory.ts index d5b4e6712c6d..7dc85fa476df 100644 --- a/examples/embeddable_examples/public/list_container/list_container_factory.ts +++ b/examples/embeddable_examples/public/list_container/list_container_factory.ts @@ -22,7 +22,8 @@ interface StartServices { export type ListContainerFactory = EmbeddableFactory; export class ListContainerFactoryDefinition - implements EmbeddableFactoryDefinition { + implements EmbeddableFactoryDefinition +{ public readonly type = LIST_CONTAINER; public readonly isContainerType = true; diff --git a/examples/embeddable_examples/public/migrations/migrations_embeddable_factory.ts b/examples/embeddable_examples/public/migrations/migrations_embeddable_factory.ts index 508ed780038c..c1ceaaca3e46 100644 --- a/examples/embeddable_examples/public/migrations/migrations_embeddable_factory.ts +++ b/examples/embeddable_examples/public/migrations/migrations_embeddable_factory.ts @@ -26,7 +26,8 @@ export type SimpleEmbeddableInput = EmbeddableInput & { export type SimpleEmbeddableFactory = EmbeddableFactory; export class SimpleEmbeddableFactoryDefinition - implements EmbeddableFactoryDefinition { + implements EmbeddableFactoryDefinition +{ public readonly type = SIMPLE_EMBEDDABLE; // we need to provide migration function every time we change the interface of our state diff --git a/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_embeddable_factory.ts b/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_embeddable_factory.ts index 473e9dee8736..7364f336b722 100644 --- a/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_embeddable_factory.ts +++ b/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_embeddable_factory.ts @@ -27,7 +27,8 @@ export type MultiTaskTodoEmbeddableFactory = EmbeddableFactory< export class MultiTaskTodoEmbeddableFactoryDefinition implements - EmbeddableFactoryDefinition { + EmbeddableFactoryDefinition +{ public readonly type = MULTI_TASK_TODO_EMBEDDABLE; public async isEditable() { diff --git a/examples/embeddable_examples/public/plugin.ts b/examples/embeddable_examples/public/plugin.ts index 248072064e14..e59e7367e8af 100644 --- a/examples/embeddable_examples/public/plugin.ts +++ b/examples/embeddable_examples/public/plugin.ts @@ -88,65 +88,74 @@ export class EmbeddableExamplesPlugin EmbeddableExamplesStart, EmbeddableExamplesSetupDependencies, EmbeddableExamplesStartDependencies - > { + > +{ private exampleEmbeddableFactories: Partial = {}; public setup( core: CoreSetup, deps: EmbeddableExamplesSetupDependencies ) { - this.exampleEmbeddableFactories.getHelloWorldEmbeddableFactory = deps.embeddable.registerEmbeddableFactory( - HELLO_WORLD_EMBEDDABLE, - new HelloWorldEmbeddableFactoryDefinition() - ); - - this.exampleEmbeddableFactories.getMigrationsEmbeddableFactory = deps.embeddable.registerEmbeddableFactory( - SIMPLE_EMBEDDABLE, - new SimpleEmbeddableFactoryDefinition() - ); - - this.exampleEmbeddableFactories.getMultiTaskTodoEmbeddableFactory = deps.embeddable.registerEmbeddableFactory( - MULTI_TASK_TODO_EMBEDDABLE, - new MultiTaskTodoEmbeddableFactoryDefinition() - ); - - this.exampleEmbeddableFactories.getSearchableListContainerEmbeddableFactory = deps.embeddable.registerEmbeddableFactory( - SEARCHABLE_LIST_CONTAINER, - new SearchableListContainerFactoryDefinition(async () => ({ - embeddableServices: (await core.getStartServices())[1].embeddable, - })) - ); - - this.exampleEmbeddableFactories.getListContainerEmbeddableFactory = deps.embeddable.registerEmbeddableFactory( - LIST_CONTAINER, - new ListContainerFactoryDefinition(async () => ({ - embeddableServices: (await core.getStartServices())[1].embeddable, - })) - ); - - this.exampleEmbeddableFactories.getTodoEmbeddableFactory = deps.embeddable.registerEmbeddableFactory( - TODO_EMBEDDABLE, - new TodoEmbeddableFactoryDefinition(async () => ({ - openModal: (await core.getStartServices())[0].overlays.openModal, - })) - ); - - this.exampleEmbeddableFactories.getTodoRefEmbeddableFactory = deps.embeddable.registerEmbeddableFactory( - TODO_REF_EMBEDDABLE, - new TodoRefEmbeddableFactoryDefinition(async () => ({ - savedObjectsClient: (await core.getStartServices())[0].savedObjects.client, - getEmbeddableFactory: (await core.getStartServices())[1].embeddable.getEmbeddableFactory, - })) - ); - this.exampleEmbeddableFactories.getBookEmbeddableFactory = deps.embeddable.registerEmbeddableFactory( - BOOK_EMBEDDABLE, - new BookEmbeddableFactoryDefinition(async () => ({ - getAttributeService: (await core.getStartServices())[1].embeddable.getAttributeService, - openModal: (await core.getStartServices())[0].overlays.openModal, - savedObjectsClient: (await core.getStartServices())[0].savedObjects.client, - overlays: (await core.getStartServices())[0].overlays, - })) - ); + this.exampleEmbeddableFactories.getHelloWorldEmbeddableFactory = + deps.embeddable.registerEmbeddableFactory( + HELLO_WORLD_EMBEDDABLE, + new HelloWorldEmbeddableFactoryDefinition() + ); + + this.exampleEmbeddableFactories.getMigrationsEmbeddableFactory = + deps.embeddable.registerEmbeddableFactory( + SIMPLE_EMBEDDABLE, + new SimpleEmbeddableFactoryDefinition() + ); + + this.exampleEmbeddableFactories.getMultiTaskTodoEmbeddableFactory = + deps.embeddable.registerEmbeddableFactory( + MULTI_TASK_TODO_EMBEDDABLE, + new MultiTaskTodoEmbeddableFactoryDefinition() + ); + + this.exampleEmbeddableFactories.getSearchableListContainerEmbeddableFactory = + deps.embeddable.registerEmbeddableFactory( + SEARCHABLE_LIST_CONTAINER, + new SearchableListContainerFactoryDefinition(async () => ({ + embeddableServices: (await core.getStartServices())[1].embeddable, + })) + ); + + this.exampleEmbeddableFactories.getListContainerEmbeddableFactory = + deps.embeddable.registerEmbeddableFactory( + LIST_CONTAINER, + new ListContainerFactoryDefinition(async () => ({ + embeddableServices: (await core.getStartServices())[1].embeddable, + })) + ); + + this.exampleEmbeddableFactories.getTodoEmbeddableFactory = + deps.embeddable.registerEmbeddableFactory( + TODO_EMBEDDABLE, + new TodoEmbeddableFactoryDefinition(async () => ({ + openModal: (await core.getStartServices())[0].overlays.openModal, + })) + ); + + this.exampleEmbeddableFactories.getTodoRefEmbeddableFactory = + deps.embeddable.registerEmbeddableFactory( + TODO_REF_EMBEDDABLE, + new TodoRefEmbeddableFactoryDefinition(async () => ({ + savedObjectsClient: (await core.getStartServices())[0].savedObjects.client, + getEmbeddableFactory: (await core.getStartServices())[1].embeddable.getEmbeddableFactory, + })) + ); + this.exampleEmbeddableFactories.getBookEmbeddableFactory = + deps.embeddable.registerEmbeddableFactory( + BOOK_EMBEDDABLE, + new BookEmbeddableFactoryDefinition(async () => ({ + getAttributeService: (await core.getStartServices())[1].embeddable.getAttributeService, + openModal: (await core.getStartServices())[0].overlays.openModal, + savedObjectsClient: (await core.getStartServices())[0].savedObjects.client, + overlays: (await core.getStartServices())[0].overlays, + })) + ); const editBookAction = createEditBookAction(async () => ({ getAttributeService: (await core.getStartServices())[1].embeddable.getAttributeService, diff --git a/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_factory.ts b/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_factory.ts index 0c7c42ef4d97..5b09719f70b3 100644 --- a/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_factory.ts +++ b/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_factory.ts @@ -28,7 +28,8 @@ export type SearchableListContainerFactory = EmbeddableFactory< ContainerOutput >; export class SearchableListContainerFactoryDefinition - implements EmbeddableFactoryDefinition { + implements EmbeddableFactoryDefinition +{ public readonly type = SEARCHABLE_LIST_CONTAINER; public readonly isContainerType = true; diff --git a/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx b/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx index 2a55316e504d..2c8b3083fd99 100644 --- a/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx +++ b/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx @@ -44,7 +44,8 @@ interface StartServices { export type TodoEmbeddableFactory = EmbeddableFactory; export class TodoEmbeddableFactoryDefinition - implements EmbeddableFactoryDefinition { + implements EmbeddableFactoryDefinition +{ public readonly type = TODO_EMBEDDABLE; constructor(private getStartServices: () => Promise) {} diff --git a/examples/embeddable_examples/public/todo/todo_ref_embeddable_factory.tsx b/examples/embeddable_examples/public/todo/todo_ref_embeddable_factory.tsx index 73f34796cd91..467318658da1 100644 --- a/examples/embeddable_examples/public/todo/todo_ref_embeddable_factory.tsx +++ b/examples/embeddable_examples/public/todo/todo_ref_embeddable_factory.tsx @@ -42,7 +42,8 @@ export class TodoRefEmbeddableFactoryDefinition TodoRefOutput, TodoRefEmbeddable, TodoSavedObjectAttributes - > { + > +{ public readonly type = TODO_REF_EMBEDDABLE; public readonly savedObjectMetaData = { name: 'Todo', diff --git a/examples/embeddable_examples/server/plugin.ts b/examples/embeddable_examples/server/plugin.ts index a3c3d4b5284f..469c463381d1 100644 --- a/examples/embeddable_examples/server/plugin.ts +++ b/examples/embeddable_examples/server/plugin.ts @@ -17,7 +17,8 @@ export interface EmbeddableExamplesSetupDependencies { } export class EmbeddableExamplesPlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, { embeddable }: EmbeddableExamplesSetupDependencies) { core.savedObjects.registerType(todoSavedObject); core.savedObjects.registerType(bookSavedObject); diff --git a/examples/index_pattern_field_editor_example/public/plugin.tsx b/examples/index_pattern_field_editor_example/public/plugin.tsx index ccbb93e3acf9..8ed158e9923e 100644 --- a/examples/index_pattern_field_editor_example/public/plugin.tsx +++ b/examples/index_pattern_field_editor_example/public/plugin.tsx @@ -40,8 +40,7 @@ export class IndexPatternFieldEditorPlugin implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, plugins: SetupDeps) { const locator = plugins.share.url.locators.create(new HelloLocatorDefinition()); diff --git a/examples/locator_explorer/public/plugin.tsx b/examples/locator_explorer/public/plugin.tsx index 3e8382f2a606..45b1d2d7939e 100644 --- a/examples/locator_explorer/public/plugin.tsx +++ b/examples/locator_explorer/public/plugin.tsx @@ -47,8 +47,7 @@ export class LocatorExplorerPlugin implements Plugin { links: [ { label: 'IRouter', - href: - 'https://github.com/elastic/kibana/blob/master/docs/development/core/server/kibana-plugin-core-server.irouter.md', + href: 'https://github.com/elastic/kibana/blob/master/docs/development/core/server/kibana-plugin-core-server.irouter.md', iconType: 'logoGithub', target: '_blank', size: 's', }, { label: 'HttpHandler (core.http.fetch)', - href: - 'https://github.com/elastic/kibana/blob/master/docs/development/core/public/kibana-plugin-core-public.httphandler.md', + href: 'https://github.com/elastic/kibana/blob/master/docs/development/core/public/kibana-plugin-core-public.httphandler.md', iconType: 'logoGithub', target: '_blank', size: 's', diff --git a/examples/search_examples/public/plugin.ts b/examples/search_examples/public/plugin.ts index 87992e5493f0..b00362aef1f5 100644 --- a/examples/search_examples/public/plugin.ts +++ b/examples/search_examples/public/plugin.ts @@ -30,7 +30,8 @@ export class SearchExamplesPlugin SearchExamplesPluginStart, AppPluginSetupDependencies, AppPluginStartDependencies - > { + > +{ public setup( core: CoreSetup, { developerExamples, share }: AppPluginSetupDependencies diff --git a/examples/search_examples/public/search_sessions/app.tsx b/examples/search_examples/public/search_sessions/app.tsx index 173cf91cd9c7..63ab706c945d 100644 --- a/examples/search_examples/public/search_sessions/app.tsx +++ b/examples/search_examples/public/search_sessions/app.tsx @@ -542,14 +542,8 @@ function SearchInspector({ function useAppState({ data }: { data: DataPublicPluginStart }) { const stateContainer = useMemo(() => { - const { - filters, - time, - searchSessionId, - numericFieldName, - indexPatternId, - query, - } = getInitialStateFromUrl(); + const { filters, time, searchSessionId, numericFieldName, indexPatternId, query } = + getInitialStateFromUrl(); if (filters) { data.query.filterManager.setFilters(filters); diff --git a/examples/search_examples/server/fibonacci_strategy.ts b/examples/search_examples/server/fibonacci_strategy.ts index a37438aba705..93cb18d3e9e8 100644 --- a/examples/search_examples/server/fibonacci_strategy.ts +++ b/examples/search_examples/server/fibonacci_strategy.ts @@ -15,7 +15,7 @@ export const fibonacciStrategyProvider = (): ISearchStrategy< FibonacciResponse > => { const responseMap = new Map(); - return ({ + return { search: (request: FibonacciRequest) => { const id = request.id ?? uuid(); const [sequence, total, started] = responseMap.get(id) ?? [ @@ -48,5 +48,5 @@ export const fibonacciStrategyProvider = (): ISearchStrategy< cancel: async (id: string) => { responseMap.delete(id); }, - } as unknown) as ISearchStrategy; + } as unknown as ISearchStrategy; }; diff --git a/examples/search_examples/server/plugin.ts b/examples/search_examples/server/plugin.ts index 984d3201220e..992c260e25e9 100644 --- a/examples/search_examples/server/plugin.ts +++ b/examples/search_examples/server/plugin.ts @@ -33,7 +33,8 @@ export class SearchExamplesPlugin SearchExamplesPluginStart, SearchExamplesPluginSetupDeps, SearchExamplesPluginStartDeps - > { + > +{ private readonly logger: Logger; constructor(initializerContext: PluginInitializerContext) { diff --git a/examples/state_containers_examples/public/plugin.ts b/examples/state_containers_examples/public/plugin.ts index df4d34ef1e1a..ac65d42ae405 100644 --- a/examples/state_containers_examples/public/plugin.ts +++ b/examples/state_containers_examples/public/plugin.ts @@ -88,16 +88,14 @@ export class StateContainersExamplesPlugin implements Plugin { links: [ { label: 'State containers README', - href: - 'https://github.com/elastic/kibana/tree/master/src/plugins/kibana_utils/docs/state_containers', + href: 'https://github.com/elastic/kibana/tree/master/src/plugins/kibana_utils/docs/state_containers', iconType: 'logoGithub', size: 's', target: '_blank', }, { label: 'State sync utils README', - href: - 'https://github.com/elastic/kibana/tree/master/src/plugins/kibana_utils/docs/state_sync', + href: 'https://github.com/elastic/kibana/tree/master/src/plugins/kibana_utils/docs/state_sync', iconType: 'logoGithub', size: 's', target: '_blank', diff --git a/examples/ui_action_examples/public/plugin.ts b/examples/ui_action_examples/public/plugin.ts index a3c2f3ea9f2c..4845ebf68302 100644 --- a/examples/ui_action_examples/public/plugin.ts +++ b/examples/ui_action_examples/public/plugin.ts @@ -21,7 +21,8 @@ export interface UiActionExamplesStartDependencies { export class UiActionExamplesPlugin implements - Plugin { + Plugin +{ public setup( core: CoreSetup, { uiActions }: UiActionExamplesSetupDependencies diff --git a/package.json b/package.json index 67fb73e21f73..77c6dbd6d703 100644 --- a/package.json +++ b/package.json @@ -220,7 +220,7 @@ "deep-freeze-strict": "^1.1.1", "deepmerge": "^4.2.2", "del": "^5.1.0", - "elastic-apm-node": "^3.20.0", + "elastic-apm-node": "^3.21.1", "execa": "^4.0.2", "exit-hook": "^2.2.0", "expiry-js": "0.1.7", @@ -280,8 +280,8 @@ "lodash": "^4.17.21", "lru-cache": "^4.1.5", "lz-string": "^1.4.4", - "maplibre-gl": "1.15.2", "mapbox-gl-draw-rectangle-mode": "1.0.4", + "maplibre-gl": "1.15.2", "markdown-it": "^10.0.0", "md5": "^2.1.0", "mdast-util-to-hast": "10.0.1", @@ -586,7 +586,7 @@ "@types/pdfmake": "^0.1.15", "@types/pegjs": "^0.10.1", "@types/pngjs": "^3.4.0", - "@types/prettier": "^2.1.5", + "@types/prettier": "^2.3.2", "@types/pretty-ms": "^5.0.0", "@types/prop-types": "^15.7.3", "@types/rbush": "^3.0.0", @@ -641,8 +641,8 @@ "@types/yauzl": "^2.9.1", "@types/zen-observable": "^0.8.0", "@typescript-eslint/eslint-plugin": "^4.14.1", - "@typescript-eslint/typescript-estree": "^4.14.1", "@typescript-eslint/parser": "^4.14.1", + "@typescript-eslint/typescript-estree": "^4.14.1", "@yarnpkg/lockfile": "^1.1.0", "abab": "^2.0.4", "aggregate-error": "^3.1.0", @@ -707,7 +707,7 @@ "eslint-plugin-no-unsanitized": "^3.0.2", "eslint-plugin-node": "^11.0.0", "eslint-plugin-prefer-object-spread": "^1.2.1", - "eslint-plugin-prettier": "^3.1.4", + "eslint-plugin-prettier": "^3.4.1", "eslint-plugin-react": "^7.20.3", "eslint-plugin-react-hooks": "^4.2.0", "eslint-plugin-react-perf": "^3.2.3", @@ -784,7 +784,7 @@ "postcss": "^7.0.32", "postcss-loader": "^3.0.0", "postcss-prefix-selector": "^1.7.2", - "prettier": "^2.2.0", + "prettier": "^2.4.0", "pretty-ms": "5.0.0", "q": "^1.5.1", "react-test-renderer": "^16.12.0", diff --git a/packages/kbn-analytics/src/application_usage_tracker.ts b/packages/kbn-analytics/src/application_usage_tracker.ts index b1cc47334541..751fb9203fe6 100644 --- a/packages/kbn-analytics/src/application_usage_tracker.ts +++ b/packages/kbn-analytics/src/application_usage_tracker.ts @@ -132,9 +132,9 @@ export class ApplicationUsageTracker { } public pauseTrackingAll() { - this.currentApplicationKeys = Object.values( - this.trackedApplicationViews - ).map(({ appId, viewId }) => this.createKey(appId, viewId)); + this.currentApplicationKeys = Object.values(this.trackedApplicationViews).map( + ({ appId, viewId }) => this.createKey(appId, viewId) + ); this.flushTrackedViews(); } diff --git a/packages/kbn-apm-config-loader/BUILD.bazel b/packages/kbn-apm-config-loader/BUILD.bazel index 81189171412b..8fb513a746ec 100644 --- a/packages/kbn-apm-config-loader/BUILD.bazel +++ b/packages/kbn-apm-config-loader/BUILD.bazel @@ -36,6 +36,7 @@ RUNTIME_DEPS = [ TYPES_DEPS = [ "//packages/elastic-safer-lodash-set", "//packages/kbn-utils", + "@npm//elastic-apm-node", "@npm//@types/jest", "@npm//@types/js-yaml", "@npm//@types/lodash", diff --git a/packages/kbn-apm-config-loader/src/config.test.ts b/packages/kbn-apm-config-loader/src/config.test.ts index e3cfbf43f841..4e4dbf81740b 100644 --- a/packages/kbn-apm-config-loader/src/config.test.ts +++ b/packages/kbn-apm-config-loader/src/config.test.ts @@ -5,7 +5,7 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - +import type { Labels } from 'elastic-apm-node'; import { packageMock, mockedRootDir, @@ -46,7 +46,8 @@ describe('ApmConfiguration', () => { it('sets the git revision from `git rev-parse` command in non distribution mode', () => { gitRevExecMock.mockReturnValue('some-git-rev'); const config = new ApmConfiguration(mockedRootDir, {}, false); - expect(config.getConfig('serviceName').globalLabels?.git_rev).toBe('some-git-rev'); + const labels = config.getConfig('serviceName').globalLabels as Labels; + expect(labels.git_rev).toBe('some-git-rev'); }); it('sets the git revision from `pkg.build.sha` in distribution mode', () => { @@ -58,13 +59,15 @@ describe('ApmConfiguration', () => { }, }; const config = new ApmConfiguration(mockedRootDir, {}, true); - expect(config.getConfig('serviceName').globalLabels?.git_rev).toBe('distribution-sha'); + const labels = config.getConfig('serviceName').globalLabels as Labels; + expect(labels.git_rev).toBe('distribution-sha'); }); it('reads the kibana uuid from the uuid file', () => { readUuidFileMock.mockReturnValue('instance-uuid'); const config = new ApmConfiguration(mockedRootDir, {}, false); - expect(config.getConfig('serviceName').globalLabels?.kibana_uuid).toBe('instance-uuid'); + const labels = config.getConfig('serviceName').globalLabels as Labels; + expect(labels.kibana_uuid).toBe('instance-uuid'); }); it('uses the uuid from the kibana config if present', () => { @@ -75,7 +78,8 @@ describe('ApmConfiguration', () => { }, }; const config = new ApmConfiguration(mockedRootDir, kibanaConfig, false); - expect(config.getConfig('serviceName').globalLabels?.kibana_uuid).toBe('uuid-from-config'); + const labels = config.getConfig('serviceName').globalLabels as Labels; + expect(labels.kibana_uuid).toBe('uuid-from-config'); }); it('overrides metricsInterval, breakdownMetrics, captureHeaders, and captureBody when `isDistributable` is true', () => { diff --git a/packages/kbn-apm-config-loader/src/config.ts b/packages/kbn-apm-config-loader/src/config.ts index 1436d396aae5..ad2fd63f0fec 100644 --- a/packages/kbn-apm-config-loader/src/config.ts +++ b/packages/kbn-apm-config-loader/src/config.ts @@ -12,17 +12,17 @@ import { execSync } from 'child_process'; // deep import to avoid loading the whole package import { getDataPath } from '@kbn/utils'; import { readFileSync } from 'fs'; -import { ApmAgentConfig } from './types'; +import type { AgentConfigOptions } from 'elastic-apm-node'; // https://www.elastic.co/guide/en/apm/agent/nodejs/current/configuration.html -const DEFAULT_CONFIG: ApmAgentConfig = { +const DEFAULT_CONFIG: AgentConfigOptions = { active: false, environment: 'development', logUncaughtExceptions: true, globalLabels: {}, }; -const CENTRALIZED_SERVICE_BASE_CONFIG: ApmAgentConfig = { +const CENTRALIZED_SERVICE_BASE_CONFIG: AgentConfigOptions = { serverUrl: 'https://38b80fbd79fb4c91bae06b4642d4d093.apm.us-east-1.aws.cloud.es.io', // The secretToken below is intended to be hardcoded in this file even though @@ -39,7 +39,7 @@ const CENTRALIZED_SERVICE_BASE_CONFIG: ApmAgentConfig = { breakdownMetrics: true, }; -const CENTRALIZED_SERVICE_DIST_CONFIG: ApmAgentConfig = { +const CENTRALIZED_SERVICE_DIST_CONFIG: AgentConfigOptions = { metricsInterval: '120s', captureBody: 'off', captureHeaders: false, @@ -47,7 +47,7 @@ const CENTRALIZED_SERVICE_DIST_CONFIG: ApmAgentConfig = { }; export class ApmConfiguration { - private baseConfig?: ApmAgentConfig; + private baseConfig?: AgentConfigOptions; private kibanaVersion: string; private pkgBuild: Record; @@ -62,7 +62,7 @@ export class ApmConfiguration { this.pkgBuild = build; } - public getConfig(serviceName: string): ApmAgentConfig { + public getConfig(serviceName: string): AgentConfigOptions { return { ...this.getBaseConfig(), serviceName, @@ -107,8 +107,8 @@ export class ApmConfiguration { /** * Override some config values when specific environment variables are used */ - private getConfigFromEnv(): ApmAgentConfig { - const config: ApmAgentConfig = {}; + private getConfigFromEnv(): AgentConfigOptions { + const config: AgentConfigOptions = {}; if (process.env.ELASTIC_APM_ACTIVE === 'true') { config.active = true; @@ -142,7 +142,7 @@ export class ApmConfiguration { * Get the elastic.apm configuration from the --config file, supersedes the * default config. */ - private getConfigFromKibanaConfig(): ApmAgentConfig { + private getConfigFromKibanaConfig(): AgentConfigOptions { return this.rawKibanaConfig?.elastic?.apm ?? {}; } @@ -150,7 +150,7 @@ export class ApmConfiguration { * Get the configuration from the apm.dev.js file, supersedes config * from the --config file, disabled when running the distributable */ - private getDevConfig(): ApmAgentConfig { + private getDevConfig(): AgentConfigOptions { if (this.isDistributable) { return {}; } @@ -167,7 +167,7 @@ export class ApmConfiguration { * Determine the Kibana UUID, initialized the value of `globalLabels.kibana_uuid` * when the UUID can be determined. */ - private getUuidConfig(): ApmAgentConfig { + private getUuidConfig(): AgentConfigOptions { // try to access the `server.uuid` value from the config file first. // if not manually defined, we will then read the value from the `{DATA_FOLDER}/uuid` file. // note that as the file is created by the platform AFTER apm init, the file @@ -207,7 +207,7 @@ export class ApmConfiguration { * When running Kibana with ELASTIC_APM_ENVIRONMENT=ci we attempt to grab * some environment variables we populate in CI related to the build under test */ - private getCiConfig(): ApmAgentConfig { + private getCiConfig(): AgentConfigOptions { if (process.env.ELASTIC_APM_ENVIRONMENT !== 'ci') { return {}; } diff --git a/packages/kbn-apm-config-loader/src/config_loader.ts b/packages/kbn-apm-config-loader/src/config_loader.ts index 75f69481da76..be0af8deceb8 100644 --- a/packages/kbn-apm-config-loader/src/config_loader.ts +++ b/packages/kbn-apm-config-loader/src/config_loader.ts @@ -5,10 +5,9 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - +import type { AgentConfigOptions } from 'elastic-apm-node'; import { getConfigurationFilePaths, getConfigFromFiles, applyConfigOverrides } from './utils'; import { ApmConfiguration } from './config'; -import { ApmAgentConfig } from './types'; let apmConfig: ApmConfiguration | undefined; @@ -32,7 +31,7 @@ export const loadConfiguration = ( return apmConfig; }; -export const getConfiguration = (serviceName: string): ApmAgentConfig | undefined => { +export const getConfiguration = (serviceName: string): AgentConfigOptions | undefined => { // integration test runner starts a kibana server that import the module without initializing APM. // so we need to check initialization of the config. // note that we can't just load the configuration during this module's import diff --git a/packages/kbn-apm-config-loader/src/index.ts b/packages/kbn-apm-config-loader/src/index.ts index da42bfad1841..b16f6dcfd418 100644 --- a/packages/kbn-apm-config-loader/src/index.ts +++ b/packages/kbn-apm-config-loader/src/index.ts @@ -9,4 +9,3 @@ export { getConfiguration } from './config_loader'; export { initApm } from './init_apm'; export type { ApmConfiguration } from './config'; -export type { ApmAgentConfig } from './types'; diff --git a/packages/kbn-apm-config-loader/src/types.ts b/packages/kbn-apm-config-loader/src/types.ts deleted file mode 100644 index 2e80631638e4..000000000000 --- a/packages/kbn-apm-config-loader/src/types.ts +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -// There is an (incomplete) `AgentConfigOptions` type declared in node_modules/elastic-apm-node/index.d.ts -// but it's not exported, and using ts tricks to retrieve the type via Parameters[0] -// causes errors in the generated .d.ts file because of esModuleInterop and the fact that the apm module -// is just exporting an instance of the `ApmAgent` type. -export interface ApmAgentConfig { - active?: boolean; - environment?: string; - serviceName?: string; - serviceVersion?: string; - serverUrl?: string; - secretToken?: string; - logUncaughtExceptions?: boolean; - globalLabels?: Record; - centralConfig?: boolean; - metricsInterval?: string; - captureSpanStackTraces?: boolean; - transactionSampleRate?: number; - breakdownMetrics?: boolean; - captureHeaders?: boolean; - captureBody?: 'off' | 'all' | 'errors' | 'transactions'; -} diff --git a/packages/kbn-config-schema/src/types/object_type.ts b/packages/kbn-config-schema/src/types/object_type.ts index 284ea6fddb35..784b17a92c39 100644 --- a/packages/kbn-config-schema/src/types/object_type.ts +++ b/packages/kbn-config-schema/src/types/object_type.ts @@ -35,8 +35,9 @@ type RequiredProperties = Pick< // Because of https://github.com/Microsoft/TypeScript/issues/14041 // this might not have perfect _rendering_ output, but it will be typed. export type ObjectResultType

= Readonly< - { [K in keyof OptionalProperties

]?: TypeOf } & - { [K in keyof RequiredProperties

]: TypeOf } + { [K in keyof OptionalProperties

]?: TypeOf } & { + [K in keyof RequiredProperties

]: TypeOf; + } >; type DefinedProperties = Pick< @@ -46,8 +47,9 @@ type DefinedProperties = Pick< }[keyof Base] >; -type ExtendedProps

= Omit & - { [K in keyof DefinedProperties]: NP[K] }; +type ExtendedProps

= Omit & { + [K in keyof DefinedProperties]: NP[K]; +}; type ExtendedObjectType

= ObjectType< ExtendedProps diff --git a/packages/kbn-config/src/deprecation/deprecation_factory.ts b/packages/kbn-config/src/deprecation/deprecation_factory.ts index 6d7669cef04f..119b9b11237d 100644 --- a/packages/kbn-config/src/deprecation/deprecation_factory.ts +++ b/packages/kbn-config/src/deprecation/deprecation_factory.ts @@ -125,31 +125,25 @@ const _unused = ( }; }; -const rename = ( - oldKey: string, - newKey: string, - details?: Partial -): ConfigDeprecation => (config, rootPath, addDeprecation) => - _rename(config, rootPath, addDeprecation, oldKey, newKey, details); +const rename = + (oldKey: string, newKey: string, details?: Partial): ConfigDeprecation => + (config, rootPath, addDeprecation) => + _rename(config, rootPath, addDeprecation, oldKey, newKey, details); -const renameFromRoot = ( - oldKey: string, - newKey: string, - details?: Partial -): ConfigDeprecation => (config, rootPath, addDeprecation) => - _rename(config, '', addDeprecation, oldKey, newKey, details); +const renameFromRoot = + (oldKey: string, newKey: string, details?: Partial): ConfigDeprecation => + (config, rootPath, addDeprecation) => + _rename(config, '', addDeprecation, oldKey, newKey, details); -const unused = ( - unusedKey: string, - details?: Partial -): ConfigDeprecation => (config, rootPath, addDeprecation) => - _unused(config, rootPath, addDeprecation, unusedKey, details); +const unused = + (unusedKey: string, details?: Partial): ConfigDeprecation => + (config, rootPath, addDeprecation) => + _unused(config, rootPath, addDeprecation, unusedKey, details); -const unusedFromRoot = ( - unusedKey: string, - details?: Partial -): ConfigDeprecation => (config, rootPath, addDeprecation) => - _unused(config, '', addDeprecation, unusedKey, details); +const unusedFromRoot = + (unusedKey: string, details?: Partial): ConfigDeprecation => + (config, rootPath, addDeprecation) => + _unused(config, '', addDeprecation, unusedKey, details); const getPath = (rootPath: string, subPath: string) => rootPath !== '' ? `${rootPath}.${subPath}` : subPath; diff --git a/packages/kbn-docs-utils/src/api_docs/build_api_docs_cli.ts b/packages/kbn-docs-utils/src/api_docs/build_api_docs_cli.ts index 5b973977c86d..a45c9035baa3 100644 --- a/packages/kbn-docs-utils/src/api_docs/build_api_docs_cli.ts +++ b/packages/kbn-docs-utils/src/api_docs/build_api_docs_cli.ts @@ -74,15 +74,11 @@ export function runBuildApiDocsCli() { } const collectReferences = flags.references as boolean; - const { - pluginApiMap, - missingApiItems, - unReferencedDeprecations, - referencedDeprecations, - } = getPluginApiMap(project, plugins, log, { - collectReferences, - pluginFilter: pluginFilter as string[], - }); + const { pluginApiMap, missingApiItems, unReferencedDeprecations, referencedDeprecations } = + getPluginApiMap(project, plugins, log, { + collectReferences, + pluginFilter: pluginFilter as string[], + }); const reporter = CiStatsReporter.fromEnv(log); plugins.forEach((plugin) => { diff --git a/packages/kbn-docs-utils/src/api_docs/tests/__fixtures__/src/plugin_a/public/fns.ts b/packages/kbn-docs-utils/src/api_docs/tests/__fixtures__/src/plugin_a/public/fns.ts index c2a932f7d913..8bcf2bb7ab18 100644 --- a/packages/kbn-docs-utils/src/api_docs/tests/__fixtures__/src/plugin_a/public/fns.ts +++ b/packages/kbn-docs-utils/src/api_docs/tests/__fixtures__/src/plugin_a/public/fns.ts @@ -60,11 +60,15 @@ export const arrowFn = ( * @returns I have no idea. * */ -export const crazyFunction = ( - obj: { hi: string }, - { fn1, fn2 }: { fn1: (foo: { param: string }) => number; fn2: () => void }, - { str }: { str: string } -) => () => () => fn1({ param: str }); +export const crazyFunction = + ( + obj: { hi: string }, + { fn1, fn2 }: { fn1: (foo: { param: string }) => number; fn2: () => void }, + { str }: { str: string } + ) => + () => + () => + fn1({ param: str }); export const fnWithNonExportedRef = (a: ImNotExportedFromIndex) => a; diff --git a/packages/kbn-es-query/src/es_query/from_filters.test.ts b/packages/kbn-es-query/src/es_query/from_filters.test.ts index e3a56b5a9d63..0e376fe3f299 100644 --- a/packages/kbn-es-query/src/es_query/from_filters.test.ts +++ b/packages/kbn-es-query/src/es_query/from_filters.test.ts @@ -60,7 +60,7 @@ describe('build query', () => { }); test('should remove falsy filters', () => { - const filters = ([null, undefined] as unknown) as Filter[]; + const filters = [null, undefined] as unknown as Filter[]; const result = buildQueryFromFilters(filters, indexPattern, false); expect(result.must_not).toEqual([]); diff --git a/packages/kbn-es-query/src/es_query/from_lucene.test.ts b/packages/kbn-es-query/src/es_query/from_lucene.test.ts index e4ca435ae886..bed8333c762d 100644 --- a/packages/kbn-es-query/src/es_query/from_lucene.test.ts +++ b/packages/kbn-es-query/src/es_query/from_lucene.test.ts @@ -26,10 +26,10 @@ describe('build query', () => { }); test("should transform an array of lucene queries into ES queries combined in the bool's must clause", () => { - const queries = ([ + const queries = [ { query: 'foo:bar', language: 'lucene' }, { query: 'bar:baz', language: 'lucene' }, - ] as unknown) as Query[]; + ] as unknown as Query[]; const expectedESQueries = queries.map((query) => { return decorateQuery(luceneStringToDsl(query.query), {}); }); @@ -40,7 +40,7 @@ describe('build query', () => { }); test('should also accept queries in ES query DSL format, simply passing them through', () => { - const queries = ([{ query: { match_all: {} }, language: 'lucene' }] as unknown) as Query[]; + const queries = [{ query: { match_all: {} }, language: 'lucene' }] as unknown as Query[]; const result = buildQueryFromLucene(queries, {}); expect(result.must).toEqual([queries[0].query]); @@ -48,10 +48,10 @@ describe('build query', () => { }); test("should accept a date format in the decorated queries and combine that into the bool's must clause", () => { - const queries = ([ + const queries = [ { query: 'foo:bar', language: 'lucene' }, { query: 'bar:baz', language: 'lucene' }, - ] as unknown) as Query[]; + ] as unknown as Query[]; const dateFormatTZ = 'America/Phoenix'; const expectedESQueries = queries.map((query) => { return decorateQuery(luceneStringToDsl(query.query), {}, dateFormatTZ); diff --git a/packages/kbn-es-query/src/es_query/migrate_filter.test.ts b/packages/kbn-es-query/src/es_query/migrate_filter.test.ts index ed01ce22e2ed..77118e2cbdb1 100644 --- a/packages/kbn-es-query/src/es_query/migrate_filter.test.ts +++ b/packages/kbn-es-query/src/es_query/migrate_filter.test.ts @@ -11,7 +11,7 @@ import { migrateFilter, DeprecatedMatchPhraseFilter } from './migrate_filter'; import { PhraseFilter, MatchAllFilter } from '../filters'; describe('migrateFilter', function () { - const oldMatchPhraseFilter = ({ + const oldMatchPhraseFilter = { query: { match: { fieldFoo: { @@ -21,9 +21,9 @@ describe('migrateFilter', function () { }, }, meta: {}, - } as unknown) as DeprecatedMatchPhraseFilter; + } as unknown as DeprecatedMatchPhraseFilter; - const newMatchPhraseFilter = ({ + const newMatchPhraseFilter = { query: { match_phrase: { fieldFoo: { @@ -32,7 +32,7 @@ describe('migrateFilter', function () { }, }, meta: {}, - } as unknown) as PhraseFilter; + } as unknown as PhraseFilter; it('should migrate match filters of type phrase', function () { const migratedFilter = migrateFilter(oldMatchPhraseFilter, undefined); diff --git a/packages/kbn-es-query/src/filters/build_filters/range_filter.test.ts b/packages/kbn-es-query/src/filters/build_filters/range_filter.test.ts index 32909fcc8cf9..8895b766e233 100644 --- a/packages/kbn-es-query/src/filters/build_filters/range_filter.test.ts +++ b/packages/kbn-es-query/src/filters/build_filters/range_filter.test.ts @@ -203,9 +203,9 @@ describe('Range filter builder', () => { }); describe('getRangeFilterField', function () { - const indexPattern: IndexPatternBase = ({ + const indexPattern: IndexPatternBase = { fields, - } as unknown) as IndexPatternBase; + } as unknown as IndexPatternBase; test('should return the name of the field a range query is targeting', () => { const field = indexPattern.fields.find((patternField) => patternField.name === 'bytes'); diff --git a/packages/kbn-es-query/src/kuery/ast/ast.test.ts b/packages/kbn-es-query/src/kuery/ast/ast.test.ts index 459ace026796..edb9150ea00d 100644 --- a/packages/kbn-es-query/src/kuery/ast/ast.test.ts +++ b/packages/kbn-es-query/src/kuery/ast/ast.test.ts @@ -371,7 +371,7 @@ describe('kuery AST API', () => { indexPattern ); - expect(toElasticsearchQuery((null as unknown) as KueryNode, undefined)).toEqual(expected); + expect(toElasticsearchQuery(null as unknown as KueryNode, undefined)).toEqual(expected); const noTypeNode = nodeTypes.function.buildNode('exists', 'foo'); diff --git a/packages/kbn-es-query/src/kuery/ast/ast.ts b/packages/kbn-es-query/src/kuery/ast/ast.ts index 7145eb5043c6..c1b4380ecbfe 100644 --- a/packages/kbn-es-query/src/kuery/ast/ast.ts +++ b/packages/kbn-es-query/src/kuery/ast/ast.ts @@ -75,6 +75,6 @@ export const toElasticsearchQuery = ( } // TODO: the return type of this function might be incorrect and it works only because of this casting - const nodeType = (nodeTypes[node.type] as unknown) as any; + const nodeType = nodeTypes[node.type] as unknown as any; return nodeType.toElasticsearchQuery(node, indexPattern, config, context); }; diff --git a/packages/kbn-es-query/src/kuery/functions/is.ts b/packages/kbn-es-query/src/kuery/functions/is.ts index 4dc0a66d3d9f..596dd91df22b 100644 --- a/packages/kbn-es-query/src/kuery/functions/is.ts +++ b/packages/kbn-es-query/src/kuery/functions/is.ts @@ -76,7 +76,7 @@ export function toElasticsearchQuery( return { multi_match: { type, - query: (value as unknown) as string, + query: value as unknown as string, lenient: true, }, }; @@ -90,7 +90,7 @@ export function toElasticsearchQuery( // keep things familiar for now. if (fields && fields.length === 0) { fields.push({ - name: (ast.toElasticsearchQuery(fullFieldNameArg) as unknown) as string, + name: ast.toElasticsearchQuery(fullFieldNameArg) as unknown as string, scripted: false, type: '', }); diff --git a/packages/kbn-es-query/src/kuery/functions/nested.ts b/packages/kbn-es-query/src/kuery/functions/nested.ts index 3a3be4c10ead..e59f7a6acc07 100644 --- a/packages/kbn-es-query/src/kuery/functions/nested.ts +++ b/packages/kbn-es-query/src/kuery/functions/nested.ts @@ -26,7 +26,7 @@ export function toElasticsearchQuery( context: Record = {} ): estypes.QueryDslQueryContainer { const [path, child] = node.arguments; - const stringPath = (ast.toElasticsearchQuery(path) as unknown) as string; + const stringPath = ast.toElasticsearchQuery(path) as unknown as string; const fullPath = context?.nested?.path ? `${context.nested.path}.${stringPath}` : stringPath; return { diff --git a/packages/kbn-es-query/src/kuery/functions/range.ts b/packages/kbn-es-query/src/kuery/functions/range.ts index 6b5810bb7518..51f686925518 100644 --- a/packages/kbn-es-query/src/kuery/functions/range.ts +++ b/packages/kbn-es-query/src/kuery/functions/range.ts @@ -57,7 +57,7 @@ export function toElasticsearchQuery( // keep things familiar for now. if (fields && fields.length === 0) { fields.push({ - name: (ast.toElasticsearchQuery(fullFieldNameArg) as unknown) as string, + name: ast.toElasticsearchQuery(fullFieldNameArg) as unknown as string, scripted: false, type: '', }); diff --git a/packages/kbn-es-query/src/kuery/functions/utils/get_fields.test.ts b/packages/kbn-es-query/src/kuery/functions/utils/get_fields.test.ts index 4125b0a57256..2a63614fadd0 100644 --- a/packages/kbn-es-query/src/kuery/functions/utils/get_fields.test.ts +++ b/packages/kbn-es-query/src/kuery/functions/utils/get_fields.test.ts @@ -18,9 +18,9 @@ describe('getFields', () => { let indexPattern: IndexPatternBase; beforeEach(() => { - indexPattern = ({ + indexPattern = { fields, - } as unknown) as IndexPatternBase; + } as unknown as IndexPatternBase; }); describe('field names without a wildcard', () => { @@ -41,14 +41,14 @@ describe('getFields', () => { }); test('should not match a wildcard in a literal node', () => { - const indexPatternWithWildField: IndexPatternBase = ({ + const indexPatternWithWildField: IndexPatternBase = { title: 'wildIndex', fields: [ { name: 'foo*', }, ], - } as unknown) as IndexPatternBase; + } as unknown as IndexPatternBase; const fieldNameNode = nodeTypes.literal.buildNode('foo*'); const results = getFields(fieldNameNode, indexPatternWithWildField); diff --git a/packages/kbn-i18n/src/core/pseudo_locale.ts b/packages/kbn-i18n/src/core/pseudo_locale.ts index daa1b76391f7..10fd086169b6 100644 --- a/packages/kbn-i18n/src/core/pseudo_locale.ts +++ b/packages/kbn-i18n/src/core/pseudo_locale.ts @@ -9,7 +9,8 @@ /** * Matches every single [A-Za-z] character, ``, `](markdown-link-address)` and `@I18N@valid_variable_name@I18N@` */ -const CHARS_FOR_PSEUDO_LOCALIZATION_REGEX = /[A-Za-z]|(\]\([\s\S]*?\))|(<([^"<>]|("[^"]*?"))*?>)|(@I18N@\w*?@I18N@)/g; +const CHARS_FOR_PSEUDO_LOCALIZATION_REGEX = + /[A-Za-z]|(\]\([\s\S]*?\))|(<([^"<>]|("[^"]*?"))*?>)|(@I18N@\w*?@I18N@)/g; const PSEUDO_ACCENTS_LOCALE = 'en-xa'; export function isPseudoLocale(locale: string) { diff --git a/packages/kbn-io-ts-utils/src/merge_rt/index.ts b/packages/kbn-io-ts-utils/src/merge_rt/index.ts index c582767fb510..b2c3ea03938d 100644 --- a/packages/kbn-io-ts-utils/src/merge_rt/index.ts +++ b/packages/kbn-io-ts-utils/src/merge_rt/index.ts @@ -14,10 +14,9 @@ type PlainObject = Record; type DeepMerge = U extends PlainObject ? T extends PlainObject - ? Omit & - { - [key in keyof U]: T extends { [k in key]: any } ? DeepMerge : U[key]; - } + ? Omit & { + [key in keyof U]: T extends { [k in key]: any } ? DeepMerge : U[key]; + } : U : U; diff --git a/packages/kbn-legacy-logging/src/legacy_logging_server.ts b/packages/kbn-legacy-logging/src/legacy_logging_server.ts index 3ece0f6f1ee4..c02eb2803515 100644 --- a/packages/kbn-legacy-logging/src/legacy_logging_server.ts +++ b/packages/kbn-legacy-logging/src/legacy_logging_server.ts @@ -96,7 +96,7 @@ export class LegacyLoggingServer { }, }); - setupLogging((this as unknown) as Server, loggingConfig, 2147483647); + setupLogging(this as unknown as Server, loggingConfig, 2147483647); } public register({ plugin: { register }, options }: PluginRegisterParams): Promise { diff --git a/packages/kbn-optimizer/src/common/array_helpers.ts b/packages/kbn-optimizer/src/common/array_helpers.ts index b486f1a14c97..1dbce46f2e8a 100644 --- a/packages/kbn-optimizer/src/common/array_helpers.ts +++ b/packages/kbn-optimizer/src/common/array_helpers.ts @@ -22,28 +22,30 @@ type Comparator = (a: T, b: T) => number; * - If the values for a getter are equal the next getter is * used to compare the items. */ -export const ascending = (...getters: Array>): Comparator => (a, b) => { - for (const getter of getters) { - const valA = getter(a); - const valB = getter(b); +export const ascending = + (...getters: Array>): Comparator => + (a, b) => { + for (const getter of getters) { + const valA = getter(a); + const valB = getter(b); - if (valA === valB) { - continue; - } - if (valA === undefined) { - return -1; - } - if (valB === undefined) { - return 1; - } + if (valA === valB) { + continue; + } + if (valA === undefined) { + return -1; + } + if (valB === undefined) { + return 1; + } - return typeof valA === 'string' || typeof valB === 'string' - ? String(valA).localeCompare(String(valB)) - : valA - valB; - } + return typeof valA === 'string' || typeof valB === 'string' + ? String(valA).localeCompare(String(valB)) + : valA - valB; + } - return 0; -}; + return 0; + }; /** * create a sort comparator that sorts values in descending diff --git a/packages/kbn-optimizer/src/common/bundle.ts b/packages/kbn-optimizer/src/common/bundle.ts index 08946deec0b4..7feaa960b79e 100644 --- a/packages/kbn-optimizer/src/common/bundle.ts +++ b/packages/kbn-optimizer/src/common/bundle.ts @@ -179,76 +179,74 @@ export function parseBundles(json: string) { throw new Error('must be an array'); } - return specs.map( - (spec: UnknownVals): Bundle => { - if (!(spec && typeof spec === 'object')) { - throw new Error('`bundles[]` must be an object'); - } + return specs.map((spec: UnknownVals): Bundle => { + if (!(spec && typeof spec === 'object')) { + throw new Error('`bundles[]` must be an object'); + } - const { type } = spec; - if (!includes(VALID_BUNDLE_TYPES, type)) { - throw new Error('`bundles[]` must have a valid `type`'); - } + const { type } = spec; + if (!includes(VALID_BUNDLE_TYPES, type)) { + throw new Error('`bundles[]` must have a valid `type`'); + } - const { id } = spec; - if (!(typeof id === 'string')) { - throw new Error('`bundles[]` must have a string `id` property'); - } + const { id } = spec; + if (!(typeof id === 'string')) { + throw new Error('`bundles[]` must have a string `id` property'); + } - const { publicDirNames } = spec; - if (!Array.isArray(publicDirNames) || !publicDirNames.every((d) => typeof d === 'string')) { - throw new Error('`bundles[]` must have an array of strings `publicDirNames` property'); - } + const { publicDirNames } = spec; + if (!Array.isArray(publicDirNames) || !publicDirNames.every((d) => typeof d === 'string')) { + throw new Error('`bundles[]` must have an array of strings `publicDirNames` property'); + } - const { contextDir } = spec; - if (!(typeof contextDir === 'string' && Path.isAbsolute(contextDir))) { - throw new Error('`bundles[]` must have an absolute path `contextDir` property'); - } + const { contextDir } = spec; + if (!(typeof contextDir === 'string' && Path.isAbsolute(contextDir))) { + throw new Error('`bundles[]` must have an absolute path `contextDir` property'); + } - const { sourceRoot } = spec; - if (!(typeof sourceRoot === 'string' && Path.isAbsolute(sourceRoot))) { - throw new Error('`bundles[]` must have an absolute path `sourceRoot` property'); - } + const { sourceRoot } = spec; + if (!(typeof sourceRoot === 'string' && Path.isAbsolute(sourceRoot))) { + throw new Error('`bundles[]` must have an absolute path `sourceRoot` property'); + } - const { outputDir } = spec; - if (!(typeof outputDir === 'string' && Path.isAbsolute(outputDir))) { - throw new Error('`bundles[]` must have an absolute path `outputDir` property'); - } + const { outputDir } = spec; + if (!(typeof outputDir === 'string' && Path.isAbsolute(outputDir))) { + throw new Error('`bundles[]` must have an absolute path `outputDir` property'); + } - const { manifestPath } = spec; - if (manifestPath !== undefined) { - if (!(typeof manifestPath === 'string' && Path.isAbsolute(manifestPath))) { - throw new Error('`bundles[]` must have an absolute path `manifestPath` property'); - } + const { manifestPath } = spec; + if (manifestPath !== undefined) { + if (!(typeof manifestPath === 'string' && Path.isAbsolute(manifestPath))) { + throw new Error('`bundles[]` must have an absolute path `manifestPath` property'); } + } - const { banner } = spec; - if (banner !== undefined) { - if (!(typeof banner === 'string')) { - throw new Error('`bundles[]` must have a string `banner` property'); - } + const { banner } = spec; + if (banner !== undefined) { + if (!(typeof banner === 'string')) { + throw new Error('`bundles[]` must have a string `banner` property'); } + } - const { pageLoadAssetSizeLimit } = spec; - if (pageLoadAssetSizeLimit !== undefined) { - if (!(typeof pageLoadAssetSizeLimit === 'number')) { - throw new Error('`bundles[]` must have a numeric `pageLoadAssetSizeLimit` property'); - } + const { pageLoadAssetSizeLimit } = spec; + if (pageLoadAssetSizeLimit !== undefined) { + if (!(typeof pageLoadAssetSizeLimit === 'number')) { + throw new Error('`bundles[]` must have a numeric `pageLoadAssetSizeLimit` property'); } - - return new Bundle({ - type, - id, - publicDirNames, - contextDir, - sourceRoot, - outputDir, - banner, - manifestPath, - pageLoadAssetSizeLimit, - }); } - ); + + return new Bundle({ + type, + id, + publicDirNames, + contextDir, + sourceRoot, + outputDir, + banner, + manifestPath, + pageLoadAssetSizeLimit, + }); + }); } catch (error) { throw new Error(`unable to parse bundles: ${error.message}`); } diff --git a/packages/kbn-optimizer/src/common/bundle_refs.ts b/packages/kbn-optimizer/src/common/bundle_refs.ts index 91fc21780930..49628fcf0558 100644 --- a/packages/kbn-optimizer/src/common/bundle_refs.ts +++ b/packages/kbn-optimizer/src/common/bundle_refs.ts @@ -58,46 +58,44 @@ export class BundleRefs { } return new BundleRefs( - spec.map( - (refSpec: UnknownVals): BundleRef => { - if (typeof refSpec !== 'object' || !refSpec) { - throw new Error('`bundleRefs[]` must be an object'); - } - - const { bundleId } = refSpec; - if (typeof bundleId !== 'string') { - throw new Error('`bundleRefs[].bundleId` must be a string'); - } - - const { contextDir } = refSpec; - if (typeof contextDir !== 'string' || !Path.isAbsolute(contextDir)) { - throw new Error('`bundleRefs[].contextDir` must be an absolute directory'); - } - - const { contextPrefix } = refSpec; - if (typeof contextPrefix !== 'string' || !Path.isAbsolute(contextPrefix)) { - throw new Error('`bundleRefs[].contextPrefix` must be an absolute directory'); - } - - const { entry } = refSpec; - if (typeof entry !== 'string') { - throw new Error('`bundleRefs[].entry` must be a string'); - } - - const { exportId } = refSpec; - if (typeof exportId !== 'string') { - throw new Error('`bundleRefs[].exportId` must be a string'); - } - - return { - bundleId, - contextDir, - contextPrefix, - entry, - exportId, - }; + spec.map((refSpec: UnknownVals): BundleRef => { + if (typeof refSpec !== 'object' || !refSpec) { + throw new Error('`bundleRefs[]` must be an object'); } - ) + + const { bundleId } = refSpec; + if (typeof bundleId !== 'string') { + throw new Error('`bundleRefs[].bundleId` must be a string'); + } + + const { contextDir } = refSpec; + if (typeof contextDir !== 'string' || !Path.isAbsolute(contextDir)) { + throw new Error('`bundleRefs[].contextDir` must be an absolute directory'); + } + + const { contextPrefix } = refSpec; + if (typeof contextPrefix !== 'string' || !Path.isAbsolute(contextPrefix)) { + throw new Error('`bundleRefs[].contextPrefix` must be an absolute directory'); + } + + const { entry } = refSpec; + if (typeof entry !== 'string') { + throw new Error('`bundleRefs[].entry` must be a string'); + } + + const { exportId } = refSpec; + if (typeof exportId !== 'string') { + throw new Error('`bundleRefs[].exportId` must be a string'); + } + + return { + bundleId, + contextDir, + contextPrefix, + entry, + exportId, + }; + }) ); } 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 5bfca96d9679..2c5668766ed5 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 @@ -109,7 +109,7 @@ it('notifies of changes and completes once all bundles have changed', async () = ); expect(MockWatchPack.mock.instances).toHaveLength(1); - const [watcher] = (MockWatchPack.mock.instances as any) as Array>; + const [watcher] = MockWatchPack.mock.instances as any as Array>; expect(watcher.on).toHaveBeenCalledTimes(1); expect(watcher.on).toHaveBeenCalledWith('change', expect.any(Function)); const [, changeListener] = watcher.on.mock.calls[0]; diff --git a/packages/kbn-optimizer/src/optimizer/optimizer_config.test.ts b/packages/kbn-optimizer/src/optimizer/optimizer_config.test.ts index 39a7e0ab0e62..dff389f2e0de 100644 --- a/packages/kbn-optimizer/src/optimizer/optimizer_config.test.ts +++ b/packages/kbn-optimizer/src/optimizer/optimizer_config.test.ts @@ -380,10 +380,12 @@ describe('OptimizerConfig::parseOptions()', () => { * and just making sure that the arguments are coming from where we expect */ describe('OptimizerConfig::create()', () => { - const assignBundlesToWorkers: jest.Mock = jest.requireMock('./assign_bundles_to_workers.ts') - .assignBundlesToWorkers; - const findKibanaPlatformPlugins: jest.Mock = jest.requireMock('./kibana_platform_plugins.ts') - .findKibanaPlatformPlugins; + const assignBundlesToWorkers: jest.Mock = jest.requireMock( + './assign_bundles_to_workers.ts' + ).assignBundlesToWorkers; + const findKibanaPlatformPlugins: jest.Mock = jest.requireMock( + './kibana_platform_plugins.ts' + ).findKibanaPlatformPlugins; const getPluginBundles: jest.Mock = jest.requireMock('./get_plugin_bundles.ts').getPluginBundles; const filterById: jest.Mock = jest.requireMock('./filter_by_id.ts').filterById; const focusBundles: jest.Mock = jest.requireMock('./focus_bundles').focusBundles; @@ -404,24 +406,26 @@ describe('OptimizerConfig::create()', () => { focusBundles.mockReturnValue(Symbol('focused bundles')); readLimits.mockReturnValue(Symbol('limits')); - jest.spyOn(OptimizerConfig, 'parseOptions').mockImplementation((): { - [key in keyof ParsedOptions]: any; - } => ({ - cache: Symbol('parsed cache'), - dist: Symbol('parsed dist'), - maxWorkerCount: Symbol('parsed max worker count'), - pluginPaths: Symbol('parsed plugin paths'), - pluginScanDirs: Symbol('parsed plugin scan dirs'), - repoRoot: Symbol('parsed repo root'), - outputRoot: Symbol('parsed output root'), - watch: Symbol('parsed watch'), - themeTags: Symbol('theme tags'), - inspectWorkers: Symbol('parsed inspect workers'), - profileWebpack: Symbol('parsed profile webpack'), - filters: [], - focus: [], - includeCoreBundle: false, - })); + jest.spyOn(OptimizerConfig, 'parseOptions').mockImplementation( + (): { + [key in keyof ParsedOptions]: any; + } => ({ + cache: Symbol('parsed cache'), + dist: Symbol('parsed dist'), + maxWorkerCount: Symbol('parsed max worker count'), + pluginPaths: Symbol('parsed plugin paths'), + pluginScanDirs: Symbol('parsed plugin scan dirs'), + repoRoot: Symbol('parsed repo root'), + outputRoot: Symbol('parsed output root'), + watch: Symbol('parsed watch'), + themeTags: Symbol('theme tags'), + inspectWorkers: Symbol('parsed inspect workers'), + profileWebpack: Symbol('parsed profile webpack'), + filters: [], + focus: [], + includeCoreBundle: false, + }) + ); }); it('passes parsed options to findKibanaPlatformPlugins, getBundles, and assignBundlesToWorkers', () => { diff --git a/packages/kbn-optimizer/src/worker/bundle_refs_plugin.ts b/packages/kbn-optimizer/src/worker/bundle_refs_plugin.ts index 5396d11726f7..18b219336a92 100644 --- a/packages/kbn-optimizer/src/worker/bundle_refs_plugin.ts +++ b/packages/kbn-optimizer/src/worker/bundle_refs_plugin.ts @@ -65,21 +65,22 @@ export class BundleRefsPlugin { // entry then create a BundleRefModule instead of a NormalModule. compilationParams.normalModuleFactory.hooks.factory.tap( 'BundleRefsPlugin/normalModuleFactory/factory', - (wrappedFactory: ModuleFactory): ModuleFactory => (data, callback) => { - const context = data.context; - const dep = data.dependencies[0]; - - this.maybeReplaceImport(context, dep.request).then( - (module) => { - if (!module) { - wrappedFactory(data, callback); - } else { - callback(undefined, module); - } - }, - (error) => callback(error) - ); - } + (wrappedFactory: ModuleFactory): ModuleFactory => + (data, callback) => { + const context = data.context; + const dep = data.dependencies[0]; + + this.maybeReplaceImport(context, dep.request).then( + (module) => { + if (!module) { + wrappedFactory(data, callback); + } else { + callback(undefined, module); + } + }, + (error) => callback(error) + ); + } ); }); diff --git a/packages/kbn-securitysolution-autocomplete/src/field/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/field/index.test.tsx index 08f55cef89b6..626c791315c3 100644 --- a/packages/kbn-securitysolution-autocomplete/src/field/index.test.tsx +++ b/packages/kbn-securitysolution-autocomplete/src/field/index.test.tsx @@ -123,9 +123,11 @@ describe('field', () => { /> ); - ((wrapper.find(EuiComboBox).props() as unknown) as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - }).onChange([{ label: 'machine.os' }]); + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ label: 'machine.os' }]); expect(mockOnChange).toHaveBeenCalledWith([ { diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.test.tsx index 6fcf8ddf74b0..941eaf532200 100644 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.test.tsx +++ b/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.test.tsx @@ -202,9 +202,11 @@ describe('AutocompleteFieldListsComponent', () => { /> ); - ((wrapper.find(EuiComboBox).props() as unknown) as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - }).onChange([{ label: 'some name' }]); + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ label: 'some name' }]); await waitFor(() => { expect(mockOnChange).toHaveBeenCalledWith({ diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.tsx index 093643c3a546..cef46b9bcaa2 100644 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.tsx +++ b/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.tsx @@ -51,10 +51,10 @@ export const AutocompleteFieldListsComponent: React.FC name, []); - const optionsMemo = useMemo(() => filterFieldToList(lists, selectedField), [ - lists, - selectedField, - ]); + const optionsMemo = useMemo( + () => filterFieldToList(lists, selectedField), + [lists, selectedField] + ); const selectedOptionsMemo = useMemo(() => { if (selectedValue != null) { const list = lists.filter(({ id }) => id === selectedValue); diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.test.tsx index c0690774965c..195259b89eb6 100644 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.test.tsx +++ b/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.test.tsx @@ -188,9 +188,11 @@ describe('AutocompleteFieldMatchComponent', () => { /> ); - ((wrapper.find(EuiComboBox).props() as unknown) as { - onCreateOption: (a: string) => void; - }).onCreateOption('127.0.0.1'); + ( + wrapper.find(EuiComboBox).props() as unknown as { + onCreateOption: (a: string) => void; + } + ).onCreateOption('127.0.0.1'); expect(mockOnChange).toHaveBeenCalledWith('127.0.0.1'); }); @@ -216,9 +218,11 @@ describe('AutocompleteFieldMatchComponent', () => { /> ); - ((wrapper.find(EuiComboBox).props() as unknown) as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - }).onChange([{ label: 'value 1' }]); + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ label: 'value 1' }]); expect(mockOnChange).toHaveBeenCalledWith('value 1'); }); @@ -243,9 +247,11 @@ describe('AutocompleteFieldMatchComponent', () => { /> ); act(() => { - ((wrapper.find(EuiComboBox).props() as unknown) as { - onSearchChange: (a: string) => void; - }).onSearchChange('value 1'); + ( + wrapper.find(EuiComboBox).props() as unknown as { + onSearchChange: (a: string) => void; + } + ).onSearchChange('value 1'); }); expect(useFieldValueAutocomplete).toHaveBeenCalledWith({ @@ -331,9 +337,11 @@ describe('AutocompleteFieldMatchComponent', () => { /> ); - ((wrapper.find(EuiSuperSelect).props() as unknown) as { - onChange: (a: string) => void; - }).onChange('true'); + ( + wrapper.find(EuiSuperSelect).props() as unknown as { + onChange: (a: string) => void; + } + ).onChange('true'); expect(mockOnChange).toHaveBeenCalledWith('true'); }); @@ -359,9 +367,11 @@ describe('AutocompleteFieldMatchComponent', () => { /> ); - ((wrapper.find(EuiSuperSelect).props() as unknown) as { - onChange: (a: string) => void; - }).onChange('false'); + ( + wrapper.find(EuiSuperSelect).props() as unknown as { + onChange: (a: string) => void; + } + ).onChange('false'); expect(mockOnChange).toHaveBeenCalledWith('false'); }); diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.tsx index 9088517adbe5..b45d508ffdb2 100644 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.tsx +++ b/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.tsx @@ -187,10 +187,10 @@ export const AutocompleteFieldMatchComponent: React.FC isLoading || isLoadingSuggestions, [ - isLoading, - isLoadingSuggestions, - ]); + const isLoadingState = useMemo( + (): boolean => isLoading || isLoadingSuggestions, + [isLoading, isLoadingSuggestions] + ); useEffect((): void => { setError(undefined); diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.test.tsx index 389761c9a6df..3246e0febede 100644 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.test.tsx +++ b/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.test.tsx @@ -189,9 +189,11 @@ describe('AutocompleteFieldMatchAnyComponent', () => { /> ); - ((wrapper.find(EuiComboBox).props() as unknown) as { - onCreateOption: (a: string) => void; - }).onCreateOption('127.0.0.1'); + ( + wrapper.find(EuiComboBox).props() as unknown as { + onCreateOption: (a: string) => void; + } + ).onCreateOption('127.0.0.1'); expect(mockOnChange).toHaveBeenCalledWith(['127.0.0.1']); }); @@ -221,9 +223,11 @@ describe('AutocompleteFieldMatchAnyComponent', () => { /> ); - ((wrapper.find(EuiComboBox).props() as unknown) as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - }).onChange([{ label: 'value 1' }]); + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ label: 'value 1' }]); expect(mockOnChange).toHaveBeenCalledWith(['value 1']); }); @@ -250,9 +254,11 @@ describe('AutocompleteFieldMatchAnyComponent', () => { /> ); act(() => { - ((wrapper.find(EuiComboBox).props() as unknown) as { - onSearchChange: (a: string) => void; - }).onSearchChange('value 1'); + ( + wrapper.find(EuiComboBox).props() as unknown as { + onSearchChange: (a: string) => void; + } + ).onSearchChange('value 1'); }); expect(useFieldValueAutocomplete).toHaveBeenCalledWith({ autocompleteService: autocompleteStartMock, diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.tsx index bfcafd199dc3..8aa8d6ad5ff7 100644 --- a/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.tsx +++ b/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.tsx @@ -145,10 +145,10 @@ export const AutocompleteFieldMatchAnyComponent: React.FC isLoading || isLoadingSuggestions, [ - isLoading, - isLoadingSuggestions, - ]); + const isLoadingState = useMemo( + (): boolean => isLoading || isLoadingSuggestions, + [isLoading, isLoadingSuggestions] + ); const defaultInput = useMemo((): JSX.Element => { return ( diff --git a/packages/kbn-securitysolution-autocomplete/src/fields/index.mock.ts b/packages/kbn-securitysolution-autocomplete/src/fields/index.mock.ts index a79325e25343..d2f74a17561a 100644 --- a/packages/kbn-securitysolution-autocomplete/src/fields/index.mock.ts +++ b/packages/kbn-securitysolution-autocomplete/src/fields/index.mock.ts @@ -11,7 +11,7 @@ import { IndexPatternFieldBase } from '@kbn/es-query'; // Copied from "src/plugins/data/common/index_patterns/fields/fields.mocks.ts" but with the types changed to "IndexPatternFieldBase" since that type is compatible. // TODO: This should move out once those mocks are directly useable or in their own package, https://github.com/elastic/kibana/issues/100715 -export const fields: IndexPatternFieldBase[] = ([ +export const fields: IndexPatternFieldBase[] = [ { name: 'bytes', type: 'number', @@ -309,6 +309,6 @@ export const fields: IndexPatternFieldBase[] = ([ readFromDocValues: false, subType: { nested: { path: 'nestedField.nestedChild' } }, }, -] as unknown) as IndexPatternFieldBase[]; +] as unknown as IndexPatternFieldBase[]; export const getField = (name: string) => fields.find((field) => field.name === name); diff --git a/packages/kbn-securitysolution-autocomplete/src/operator/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/operator/index.test.tsx index e2af384215c2..6d1622f0fa95 100644 --- a/packages/kbn-securitysolution-autocomplete/src/operator/index.test.tsx +++ b/packages/kbn-securitysolution-autocomplete/src/operator/index.test.tsx @@ -210,9 +210,11 @@ describe('operator', () => { /> ); - ((wrapper.find(EuiComboBox).props() as unknown) as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - }).onChange([{ label: 'is not' }]); + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ label: 'is not' }]); expect(mockOnChange).toHaveBeenCalledWith([ { message: 'is not', operator: 'excluded', type: 'match', value: 'is_not' }, diff --git a/packages/kbn-securitysolution-autocomplete/src/operator/index.tsx b/packages/kbn-securitysolution-autocomplete/src/operator/index.tsx index dc12de7c398c..c791ef4ccb91 100644 --- a/packages/kbn-securitysolution-autocomplete/src/operator/index.tsx +++ b/packages/kbn-securitysolution-autocomplete/src/operator/index.tsx @@ -50,9 +50,10 @@ export const OperatorComponent: React.FC = ({ : getOperators(selectedField), [operatorOptions, selectedField] ); - const selectedOptionsMemo = useMemo((): OperatorOption[] => (operator ? [operator] : []), [ - operator, - ]); + const selectedOptionsMemo = useMemo( + (): OperatorOption[] => (operator ? [operator] : []), + [operator] + ); const { comboOptions, labels, selectedComboOptions } = useMemo( (): GetGenericComboBoxPropsReturn => getGenericComboBoxProps({ diff --git a/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.test.ts b/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.test.ts index c3c9702823ec..a35ed9d85122 100644 --- a/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.test.ts +++ b/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.test.ts @@ -15,17 +15,21 @@ describe('params_is_valid', () => { beforeEach(() => { // Disable momentJS deprecation warning and it looks like it is not typed either so // we have to disable the type as well and cannot extend it easily. - ((moment as unknown) as { - suppressDeprecationWarnings: boolean; - }).suppressDeprecationWarnings = true; + ( + moment as unknown as { + suppressDeprecationWarnings: boolean; + } + ).suppressDeprecationWarnings = true; }); afterEach(() => { // Re-enable momentJS deprecation warning and it looks like it is not typed either so // we have to disable the type as well and cannot extend it easily. - ((moment as unknown) as { - suppressDeprecationWarnings: boolean; - }).suppressDeprecationWarnings = false; + ( + moment as unknown as { + suppressDeprecationWarnings: boolean; + } + ).suppressDeprecationWarnings = false; }); test('returns no errors if no field has been selected', () => { diff --git a/packages/kbn-securitysolution-es-utils/src/encode_hit_version/index.ts b/packages/kbn-securitysolution-es-utils/src/encode_hit_version/index.ts index 29b5a18f7c30..fc44d605888d 100644 --- a/packages/kbn-securitysolution-es-utils/src/encode_hit_version/index.ts +++ b/packages/kbn-securitysolution-es-utils/src/encode_hit_version/index.ts @@ -16,7 +16,7 @@ */ export const encodeHitVersion = (hit: T): string | undefined => { // Have to do this "as cast" here as these two types aren't included in the SearchResponse hit type - const { _seq_no: seqNo, _primary_term: primaryTerm } = (hit as unknown) as { + const { _seq_no: seqNo, _primary_term: primaryTerm } = hit as unknown as { _seq_no: number; _primary_term: number; }; diff --git a/packages/kbn-securitysolution-es-utils/src/transform_error/index.test.ts b/packages/kbn-securitysolution-es-utils/src/transform_error/index.test.ts index e0f520f1ebfd..2b4bbf34c7c8 100644 --- a/packages/kbn-securitysolution-es-utils/src/transform_error/index.test.ts +++ b/packages/kbn-securitysolution-es-utils/src/transform_error/index.test.ts @@ -88,7 +88,7 @@ describe('transformError', () => { reason: 'detailed explanation', }, }, - meta: ({} as unknown) as errors.ResponseError['meta'], + meta: {} as unknown as errors.ResponseError['meta'], statusCode: 400, }; const transformed = transformError(error); diff --git a/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.ts b/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.ts index da6fd414abc5..c4b53abfa88f 100644 --- a/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.ts +++ b/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.ts @@ -18,9 +18,9 @@ export type OptionalSignalArgs = Omit & Partial(fn: (args: Args) => Result) => ( - args: OptionalSignalArgs -): Result => { - const signal = args.signal != null ? args.signal : new AbortController().signal; - return fn({ ...args, signal } as Args); -}; +export const withOptionalSignal = + (fn: (args: Args) => Result) => + (args: OptionalSignalArgs): Result => { + const signal = args.signal != null ? args.signal : new AbortController().signal; + return fn({ ...args, signal } as Args); + }; diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.test.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.test.ts index 16fd1647e5bf..6e2e671dbb02 100644 --- a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.test.ts +++ b/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.test.ts @@ -54,13 +54,13 @@ describe('threat_mapping', () => { }); test('it should fail validation with a non string', () => { - const payload = ([ + const payload = [ { field: 5, type: 'mapping', value: 'field.one', }, - ] as unknown) as ThreatMappingEntries[]; + ] as unknown as ThreatMappingEntries[]; const decoded = threatMappingEntries.decode(payload); const checked = exactCheck(payload, decoded); const message = pipe(checked, foldLeftRight); @@ -70,13 +70,13 @@ describe('threat_mapping', () => { }); test('it should fail validation with a wrong type', () => { - const payload = ([ + const payload = [ { field: 'field.one', type: 'invalid', value: 'field.one', }, - ] as unknown) as ThreatMappingEntries[]; + ] as unknown as ThreatMappingEntries[]; const decoded = threatMappingEntries.decode(payload); const checked = exactCheck(payload, decoded); const message = pipe(checked, foldLeftRight); @@ -155,7 +155,7 @@ describe('threat_mapping', () => { }); test('it should fail validate with an extra inner entry with the wrong data type', () => { - const payload = ([ + const payload = [ { entries: [ { @@ -165,7 +165,7 @@ describe('threat_mapping', () => { }, ], }, - ] as unknown) as ThreatMapping; + ] as unknown as ThreatMapping; const decoded = threat_mapping.decode(payload); const checked = exactCheck(payload, decoded); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.test.ts index 4af9be0a7f0e..1272eeed6ee1 100644 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.test.ts +++ b/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.test.ts @@ -193,7 +193,7 @@ describe('Comment', () => { }); test('it fails validation when array includes non Comment types', () => { - const payload = ([1] as unknown) as CommentsArray; + const payload = [1] as unknown as CommentsArray; const decoded = commentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -224,7 +224,7 @@ describe('Comment', () => { }); test('it fails validation when array includes non Comment types', () => { - const payload = ([1] as unknown) as CommentsArrayOrUndefined; + const payload = [1] as unknown as CommentsArrayOrUndefined; const decoded = commentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.test.ts index 3baf0054221d..1f5aa2118be4 100644 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.test.ts +++ b/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.test.ts @@ -90,7 +90,7 @@ describe('CreateComment', () => { }); test('it fails validation when array includes non comments types', () => { - const payload = ([1] as unknown) as CreateCommentsArray; + const payload = [1] as unknown as CreateCommentsArray; const decoded = createCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -121,7 +121,7 @@ describe('CreateComment', () => { }); test('it fails validation when array includes non comments types', () => { - const payload = ([1] as unknown) as CreateCommentsArrayOrUndefined; + const payload = [1] as unknown as CreateCommentsArrayOrUndefined; const decoded = createCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.test.ts index 88dcc1ced860..83e75a924f43 100644 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.test.ts +++ b/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.test.ts @@ -81,7 +81,7 @@ describe('Lists', () => { }); test('it should not validate when unexpected type found in array', () => { - const payload = ([1] as unknown) as ListArray; + const payload = [1] as unknown as ListArray; const decoded = listArray.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -112,7 +112,7 @@ describe('Lists', () => { }); test('it should not allow an item that is not of type "list" in array', () => { - const payload = ([1] as unknown) as ListArrayOrUndefined; + const payload = [1] as unknown as ListArrayOrUndefined; const decoded = listArrayOrUndefined.decode(payload); const message = pipe(decoded, foldLeftRight); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.test.ts index 8dd0301c54dd..7ddbdf31ca31 100644 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.test.ts +++ b/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.test.ts @@ -105,7 +105,7 @@ describe('CommentsUpdate', () => { }); test('it should fail validation when array includes non comments types', () => { - const payload = ([1] as unknown) as UpdateCommentsArray; + const payload = [1] as unknown as UpdateCommentsArray; const decoded = updateCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); @@ -136,7 +136,7 @@ describe('CommentsUpdate', () => { }); test('it should fail validation when array includes non comments types', () => { - const payload = ([1] as unknown) as UpdateCommentsArrayOrUndefined; + const payload = [1] as unknown as UpdateCommentsArrayOrUndefined; const decoded = updateCommentsArray.decode(payload); const message = pipe(decoded, foldLeftRight); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.mock.ts index 4ed62887ef9b..5b88de0c85c0 100644 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.mock.ts +++ b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.mock.ts @@ -51,11 +51,12 @@ export const getCreateExceptionListItemMinimalSchemaMock = (): CreateExceptionLi /** * Useful for end to end testing */ -export const getCreateExceptionListItemMinimalSchemaMockWithoutId = (): CreateExceptionListItemSchema => ({ - description: DESCRIPTION, - entries: ENTRIES, - list_id: LIST_ID, - name: NAME, - os_types: OS_TYPES, - type: ITEM_TYPE, -}); +export const getCreateExceptionListItemMinimalSchemaMockWithoutId = + (): CreateExceptionListItemSchema => ({ + description: DESCRIPTION, + entries: ENTRIES, + list_id: LIST_ID, + name: NAME, + os_types: OS_TYPES, + type: ITEM_TYPE, + }); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.mock.ts index f6548a2c5f4f..8f64dccf6d57 100644 --- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.mock.ts +++ b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.mock.ts @@ -30,22 +30,24 @@ export const getFindExceptionListItemSchemaMultipleMock = (): FindExceptionListI sort_order: undefined, }); -export const getFindExceptionListItemSchemaDecodedMock = (): FindExceptionListItemSchemaDecoded => ({ - filter: [FILTER], - list_id: [LIST_ID], - namespace_type: [NAMESPACE_TYPE], - page: 1, - per_page: 25, - sort_field: undefined, - sort_order: undefined, -}); +export const getFindExceptionListItemSchemaDecodedMock = + (): FindExceptionListItemSchemaDecoded => ({ + filter: [FILTER], + list_id: [LIST_ID], + namespace_type: [NAMESPACE_TYPE], + page: 1, + per_page: 25, + sort_field: undefined, + sort_order: undefined, + }); -export const getFindExceptionListItemSchemaDecodedMultipleMock = (): FindExceptionListItemSchemaDecoded => ({ - filter: ['name:Sofia Kovalevskaya', 'name:Hypatia', 'name:Sophie Germain'], - list_id: ['list-1', 'list-2', 'list-3'], - namespace_type: ['single', 'single', 'agnostic'], - page: 1, - per_page: 25, - sort_field: undefined, - sort_order: undefined, -}); +export const getFindExceptionListItemSchemaDecodedMultipleMock = + (): FindExceptionListItemSchemaDecoded => ({ + filter: ['name:Sofia Kovalevskaya', 'name:Hypatia', 'name:Sophie Germain'], + list_id: ['list-1', 'list-2', 'list-3'], + namespace_type: ['single', 'single', 'agnostic'], + page: 1, + per_page: 25, + sort_field: undefined, + sort_order: undefined, + }); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.mock.ts index 234858400047..c06a5439d11d 100644 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.mock.ts +++ b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.mock.ts @@ -53,17 +53,18 @@ export const getExceptionListItemSchemaMock = ( * This is useful for end to end tests where we remove the auto generated parts for comparisons * such as created_at, updated_at, and id. */ -export const getExceptionListItemResponseMockWithoutAutoGeneratedValues = (): Partial => ({ - comments: [], - created_by: ELASTIC_USER, - description: DESCRIPTION, - entries: ENTRIES, - item_id: ITEM_ID, - list_id: LIST_ID, - name: NAME, - namespace_type: 'single', - os_types: OS_TYPES, - tags: [], - type: ITEM_TYPE, - updated_by: ELASTIC_USER, -}); +export const getExceptionListItemResponseMockWithoutAutoGeneratedValues = + (): Partial => ({ + comments: [], + created_by: ELASTIC_USER, + description: DESCRIPTION, + entries: ENTRIES, + item_id: ITEM_ID, + list_id: LIST_ID, + name: NAME, + namespace_type: 'single', + os_types: OS_TYPES, + tags: [], + type: ITEM_TYPE, + updated_by: ELASTIC_USER, + }); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.mock.ts index c77fb35a40b6..c73b5a55d0c2 100644 --- a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.mock.ts +++ b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.mock.ts @@ -62,16 +62,17 @@ export const getTrustedAppsListSchemaMock = (): ExceptionListSchema => { * This is useful for end to end tests where we remove the auto generated parts for comparisons * such as created_at, updated_at, and id. */ -export const getExceptionResponseMockWithoutAutoGeneratedValues = (): Partial => ({ - created_by: ELASTIC_USER, - description: DESCRIPTION, - immutable: IMMUTABLE, - list_id: LIST_ID, - name: NAME, - namespace_type: 'single', - os_types: [], - tags: [], - type: ENDPOINT_TYPE, - updated_by: ELASTIC_USER, - version: VERSION, -}); +export const getExceptionResponseMockWithoutAutoGeneratedValues = + (): Partial => ({ + created_by: ELASTIC_USER, + description: DESCRIPTION, + immutable: IMMUTABLE, + list_id: LIST_ID, + name: NAME, + namespace_type: 'single', + os_types: [], + tags: [], + type: ENDPOINT_TYPE, + updated_by: ELASTIC_USER, + version: VERSION, + }); diff --git a/packages/kbn-securitysolution-io-ts-utils/src/format_errors/index.test.ts b/packages/kbn-securitysolution-io-ts-utils/src/format_errors/index.test.ts index f47f8f87f6a7..17a551b09876 100644 --- a/packages/kbn-securitysolution-io-ts-utils/src/format_errors/index.test.ts +++ b/packages/kbn-securitysolution-io-ts-utils/src/format_errors/index.test.ts @@ -60,7 +60,7 @@ describe('utils', () => { }); test('will use message before context if it is set', () => { - const context: t.Context = ([{ key: 'some string key' }] as unknown) as t.Context; + const context: t.Context = [{ key: 'some string key' }] as unknown as t.Context; const validationError1: t.ValidationError = { value: 'Some existing error 1', context, @@ -72,7 +72,7 @@ describe('utils', () => { }); test('will use context entry of a single string', () => { - const context: t.Context = ([{ key: 'some string key' }] as unknown) as t.Context; + const context: t.Context = [{ key: 'some string key' }] as unknown as t.Context; const validationError1: t.ValidationError = { value: 'Some existing error 1', context, @@ -83,10 +83,10 @@ describe('utils', () => { }); test('will use two context entries of two strings', () => { - const context: t.Context = ([ + const context: t.Context = [ { key: 'some string key 1' }, { key: 'some string key 2' }, - ] as unknown) as t.Context; + ] as unknown as t.Context; const validationError1: t.ValidationError = { value: 'Some existing error 1', context, @@ -99,10 +99,7 @@ describe('utils', () => { }); test('will filter out and not use any strings of numbers', () => { - const context: t.Context = ([ - { key: '5' }, - { key: 'some string key 2' }, - ] as unknown) as t.Context; + const context: t.Context = [{ key: '5' }, { key: 'some string key 2' }] as unknown as t.Context; const validationError1: t.ValidationError = { value: 'Some existing error 1', context, @@ -115,10 +112,10 @@ describe('utils', () => { }); test('will filter out and not use null', () => { - const context: t.Context = ([ + const context: t.Context = [ { key: null }, { key: 'some string key 2' }, - ] as unknown) as t.Context; + ] as unknown as t.Context; const validationError1: t.ValidationError = { value: 'Some existing error 1', context, @@ -131,10 +128,7 @@ describe('utils', () => { }); test('will filter out and not use empty strings', () => { - const context: t.Context = ([ - { key: '' }, - { key: 'some string key 2' }, - ] as unknown) as t.Context; + const context: t.Context = [{ key: '' }, { key: 'some string key 2' }] as unknown as t.Context; const validationError1: t.ValidationError = { value: 'Some existing error 1', context, @@ -147,10 +141,10 @@ describe('utils', () => { }); test('will use a name context if it cannot find a keyContext', () => { - const context: t.Context = ([ + const context: t.Context = [ { key: '' }, { key: '', type: { name: 'someName' } }, - ] as unknown) as t.Context; + ] as unknown as t.Context; const validationError1: t.ValidationError = { value: 'Some existing error 1', context, @@ -161,7 +155,7 @@ describe('utils', () => { }); test('will return an empty string if name does not exist but type does', () => { - const context: t.Context = ([{ key: '' }, { key: '', type: {} }] as unknown) as t.Context; + const context: t.Context = [{ key: '' }, { key: '', type: {} }] as unknown as t.Context; const validationError1: t.ValidationError = { value: 'Some existing error 1', context, @@ -172,10 +166,7 @@ describe('utils', () => { }); test('will stringify an error value', () => { - const context: t.Context = ([ - { key: '' }, - { key: 'some string key 2' }, - ] as unknown) as t.Context; + const context: t.Context = [{ key: '' }, { key: 'some string key 2' }] as unknown as t.Context; const validationError1: t.ValidationError = { value: { foo: 'some error' }, context, diff --git a/packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.ts index 722a7918c412..c0a5325377dc 100644 --- a/packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.ts +++ b/packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.ts @@ -72,7 +72,12 @@ export const useExceptionLists = ({ abortCtrlRef.current = new AbortController(); - const { page, per_page: perPage, total, data } = await fetchExceptionLists({ + const { + page, + per_page: perPage, + total, + data, + } = await fetchExceptionLists({ filters, http, namespaceTypes: namespaceTypesAsString, diff --git a/packages/kbn-server-route-repository/src/typings.ts b/packages/kbn-server-route-repository/src/typings.ts index c27f67c71e88..dde957f46990 100644 --- a/packages/kbn-server-route-repository/src/typings.ts +++ b/packages/kbn-server-route-repository/src/typings.ts @@ -70,16 +70,15 @@ export interface ServerRouteRepository< ): ServerRouteRepository< TRouteHandlerResources, TRouteCreateOptions, - TRouteState & - { - [key in TEndpoint]: ServerRoute< - TEndpoint, - TRouteParamsRT, - TRouteHandlerResources, - TReturnType, - TRouteCreateOptions - >; - } + TRouteState & { + [key in TEndpoint]: ServerRoute< + TEndpoint, + TRouteParamsRT, + TRouteHandlerResources, + TReturnType, + TRouteCreateOptions + >; + } >; merge< TServerRouteRepository extends ServerRouteRepository< @@ -104,27 +103,24 @@ export interface ServerRouteRepository< >; } -type ClientRequestParamsOfType< - TRouteParamsRT extends RouteParamsRT -> = TRouteParamsRT extends t.Mixed - ? MaybeOptional<{ - params: t.OutputOf; - }> - : {}; +type ClientRequestParamsOfType = + TRouteParamsRT extends t.Mixed + ? MaybeOptional<{ + params: t.OutputOf; + }> + : {}; -type DecodedRequestParamsOfType< - TRouteParamsRT extends RouteParamsRT -> = TRouteParamsRT extends t.Mixed - ? MaybeOptional<{ - params: t.TypeOf; - }> - : {}; +type DecodedRequestParamsOfType = + TRouteParamsRT extends t.Mixed + ? MaybeOptional<{ + params: t.TypeOf; + }> + : {}; -export type EndpointOf< - TServerRouteRepository extends ServerRouteRepository -> = TServerRouteRepository extends ServerRouteRepository - ? keyof TRouteState - : never; +export type EndpointOf> = + TServerRouteRepository extends ServerRouteRepository + ? keyof TRouteState + : never; export type ReturnOf< TServerRouteRepository extends ServerRouteRepository, diff --git a/packages/kbn-test/src/es/test_es_cluster.ts b/packages/kbn-test/src/es/test_es_cluster.ts index 2fbba7b9bd5a..026a57ff0a7a 100644 --- a/packages/kbn-test/src/es/test_es_cluster.ts +++ b/packages/kbn-test/src/es/test_es_cluster.ts @@ -55,11 +55,10 @@ export interface ICluster { getHostUrls: () => string[]; } -export type EsTestCluster< - Options extends CreateTestEsClusterOptions = CreateTestEsClusterOptions -> = Options['nodes'] extends TestEsClusterNodesOptions[] - ? ICluster - : ICluster & { getUrl: () => string }; // Only allow use of `getUrl` if `nodes` option isn't provided. +export type EsTestCluster = + Options['nodes'] extends TestEsClusterNodesOptions[] + ? ICluster + : ICluster & { getUrl: () => string }; // Only allow use of `getUrl` if `nodes` option isn't provided. export interface CreateTestEsClusterOptions { basePath?: string; 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 0a2dba60742a..b5d379d3426e 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 @@ -5,7 +5,6 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ -import { relative } from 'path'; import { ToolingLog } from '@kbn/dev-utils'; @@ -121,9 +120,6 @@ export class FunctionalTestRunner { throw new Error('No tests defined.'); } - // eslint-disable-next-line - console.log(`--- Running ${relative(process.cwd(), this.configFile)}`); - const dockerServers = new DockerServersService( config.get('dockerServers'), this.log, 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 2d05d5bba5ff..69a5973168f0 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 @@ -67,7 +67,7 @@ export class ProviderCollection { }; if (provider.prototype instanceof GenericFtrService) { - const Constructor = (provider as any) as new (ctx: any) => any; + const Constructor = provider as any as new (ctx: any) => any; return new Constructor(ctx); } diff --git a/packages/kbn-test/src/functional_test_runner/lib/snapshots/decorate_snapshot_ui.test.ts b/packages/kbn-test/src/functional_test_runner/lib/snapshots/decorate_snapshot_ui.test.ts index 707aba593217..c199dfc09278 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/snapshots/decorate_snapshot_ui.test.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/snapshots/decorate_snapshot_ui.test.ts @@ -34,11 +34,11 @@ const registerTest = ({ title?: string; passed?: boolean; }) => { - const test = ({ + const test = { file: __filename, fullTitle: () => title, isPassed: () => passed, - } as unknown) as Test; + } as unknown as Test; parent.tests.push(test); test.parent = parent; 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 ac715da7d2a0..e87f316a100a 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 @@ -51,12 +51,12 @@ describe('SuiteTracker', () => { let MOCKS: Record; const createMock = (overrides = {}) => { - return ({ + return { file: resolve(REPO_ROOT, MOCK_TEST_PATH), title: 'A Test', suiteTag: MOCK_TEST_PATH, ...overrides, - } as unknown) as Suite; + } as unknown as Suite; }; const runLifecycleWithMocks = async (mocks: Suite[], fn: (objs: any) => any = () => {}) => { diff --git a/packages/kbn-test/src/functional_tests/tasks.ts b/packages/kbn-test/src/functional_tests/tasks.ts index 76443293be75..d45f8656ed72 100644 --- a/packages/kbn-test/src/functional_tests/tasks.ts +++ b/packages/kbn-test/src/functional_tests/tasks.ts @@ -9,7 +9,7 @@ import { relative } from 'path'; import * as Rx from 'rxjs'; import { startWith, switchMap, take } from 'rxjs/operators'; -import { withProcRunner, ToolingLog } from '@kbn/dev-utils'; +import { withProcRunner, ToolingLog, REPO_ROOT } from '@kbn/dev-utils'; import dedent from 'dedent'; import { @@ -72,37 +72,49 @@ export async function runTests(options: RunTestsParams) { log.warning('❗️❗️❗️'); } - for (const configPath of options.configs) { - const log = options.createLogger(); - const opts = { - ...options, - log, - }; - - log.info('Running', configPath); - log.indent(2); + const log = options.createLogger(); - if (options.assertNoneExcluded) { - await assertNoneExcluded({ configPath, options: opts }); + if (options.assertNoneExcluded) { + log.write('--- asserting that all tests belong to a ciGroup'); + for (const configPath of options.configs) { + log.info('loading', configPath); + log.indent(4); + try { + await assertNoneExcluded({ configPath, options: { ...options, log } }); + } finally { + log.indent(-4); + } continue; } - if (!(await hasTests({ configPath, options: opts }))) { - log.info('Skipping', configPath, 'since all tests are excluded'); - continue; + return; + } + + log.write('--- determining which ftr configs to run'); + const configPathsWithTests: string[] = []; + for (const configPath of options.configs) { + log.info('testing', configPath); + log.indent(4); + try { + if (await hasTests({ configPath, options: { ...options, log } })) { + configPathsWithTests.push(configPath); + } + } finally { + log.indent(-4); } + } - // eslint-disable-next-line no-console - console.log(`--- Running ${relative(process.cwd(), configPath)}`); + for (const configPath of configPathsWithTests) { + log.write(`--- Running ${relative(REPO_ROOT, configPath)}`); await withProcRunner(log, async (procs) => { const config = await readConfigFile(log, configPath); let es; try { - es = await runElasticsearch({ config, options: opts }); - await runKibanaServer({ procs, config, options: opts }); - await runFtr({ configPath, options: opts }); + es = await runElasticsearch({ config, options: { ...options, log } }); + await runKibanaServer({ procs, config, options }); + await runFtr({ configPath, options: { ...options, log } }); } finally { try { const delay = config.get('kbnTestServer.delayShutdown'); diff --git a/packages/kbn-test/src/jest/utils/enzyme_helpers.tsx b/packages/kbn-test/src/jest/utils/enzyme_helpers.tsx index 686a201761dc..0aa93dc51446 100644 --- a/packages/kbn-test/src/jest/utils/enzyme_helpers.tsx +++ b/packages/kbn-test/src/jest/utils/enzyme_helpers.tsx @@ -19,11 +19,13 @@ import React, { ReactElement, ValidationMap } from 'react'; import { act as reactAct } from 'react-dom/test-utils'; // Use fake component to extract `intl` property to use in tests. -const { intl } = (mount( - -
-
-).find('IntlProvider') as ReactWrapper<{}, {}, __IntlProvider>) +const { intl } = ( + mount( + +
+
+ ).find('IntlProvider') as ReactWrapper<{}, {}, __IntlProvider> +) .instance() .getChildContext(); diff --git a/packages/kbn-test/src/jest/utils/redux_helpers.tsx b/packages/kbn-test/src/jest/utils/redux_helpers.tsx index 906cad2444b2..3bbdfb965f32 100644 --- a/packages/kbn-test/src/jest/utils/redux_helpers.tsx +++ b/packages/kbn-test/src/jest/utils/redux_helpers.tsx @@ -9,8 +9,9 @@ import React, { ComponentType } from 'react'; import { Provider } from 'react-redux'; -export const WithStore = (store: any) => (WrappedComponent: ComponentType) => (props: any) => ( - - - -); +export const WithStore = (store: any) => (WrappedComponent: ComponentType) => (props: any) => + ( + + + + ); diff --git a/packages/kbn-test/src/jest/utils/router_helpers.tsx b/packages/kbn-test/src/jest/utils/router_helpers.tsx index 85ef27488a4c..7c40e50bf646 100644 --- a/packages/kbn-test/src/jest/utils/router_helpers.tsx +++ b/packages/kbn-test/src/jest/utils/router_helpers.tsx @@ -30,42 +30,45 @@ const locationDescriptorToRoutePath = ( return stringifyPath(paths); }; -export const WithMemoryRouter = ( - initialEntries: LocationDescriptor[] = ['/'], - initialIndex: number = 0 -) => (WrappedComponent: ComponentType) => (props: any) => ( - - - -); +export const WithMemoryRouter = + (initialEntries: LocationDescriptor[] = ['/'], initialIndex: number = 0) => + (WrappedComponent: ComponentType) => + (props: any) => + ( + + + + ); -export const WithRoute = ( - componentRoutePath: LocationDescriptor | LocationDescriptor[] = ['/'], - onRouter = (router: any) => {} -) => (WrappedComponent: ComponentType) => { - // Create a class component that will catch the router - // and forward it to our "onRouter()" handler. - const CatchRouter = withRouter( - class extends Component { - componentDidMount() { - const { match, location, history } = this.props; - const router = { route: { match, location }, history }; - onRouter(router); - } +export const WithRoute = + ( + componentRoutePath: LocationDescriptor | LocationDescriptor[] = ['/'], + onRouter = (router: any) => {} + ) => + (WrappedComponent: ComponentType) => { + // Create a class component that will catch the router + // and forward it to our "onRouter()" handler. + const CatchRouter = withRouter( + class extends Component { + componentDidMount() { + const { match, location, history } = this.props; + const router = { route: { match, location }, history }; + onRouter(router); + } - render() { - return ; + render() { + return ; + } } - } - ); + ); - return (props: any) => ( - } - /> - ); -}; + return (props: any) => ( + } + /> + ); + }; interface Router { history: Partial; diff --git a/packages/kbn-test/types/ftr_globals/snapshots.d.ts b/packages/kbn-test/types/ftr_globals/snapshots.d.ts index ba7a4c114370..d244e6cc90bb 100644 --- a/packages/kbn-test/types/ftr_globals/snapshots.d.ts +++ b/packages/kbn-test/types/ftr_globals/snapshots.d.ts @@ -6,9 +6,7 @@ * Side Public License, v 1. */ -declare const expectSnapshot: ( - received: any -) => { +declare const expectSnapshot: (received: any) => { toMatch: () => void; toMatchInline: (_actual?: any) => void; }; diff --git a/packages/kbn-tinymath/test/functions/degtorad.test.js b/packages/kbn-tinymath/test/functions/degtorad.test.js index 857447ab7051..0988db251743 100644 --- a/packages/kbn-tinymath/test/functions/degtorad.test.js +++ b/packages/kbn-tinymath/test/functions/degtorad.test.js @@ -16,10 +16,7 @@ describe('Degrees to Radians', () => { it('arrays', () => { expect(degtorad([0, 90, 180, 360])).toEqual([ - 0, - 1.5707963267948966, - 3.141592653589793, - 6.283185307179586, + 0, 1.5707963267948966, 3.141592653589793, 6.283185307179586, ]); }); }); diff --git a/packages/kbn-tinymath/test/functions/radtodeg.test.js b/packages/kbn-tinymath/test/functions/radtodeg.test.js index 03a10f59d60c..e2059df464f2 100644 --- a/packages/kbn-tinymath/test/functions/radtodeg.test.js +++ b/packages/kbn-tinymath/test/functions/radtodeg.test.js @@ -16,10 +16,7 @@ describe('Radians to Degrees', () => { it('arrays', () => { expect(radtodeg([0, 1.5707963267948966, 3.141592653589793, 6.283185307179586])).toEqual([ - 0, - 90, - 180, - 360, + 0, 90, 180, 360, ]); }); }); diff --git a/packages/kbn-typed-react-router-config/src/types/index.ts b/packages/kbn-typed-react-router-config/src/types/index.ts index e6c70001ef4b..9c19c8dca323 100644 --- a/packages/kbn-typed-react-router-config/src/types/index.ts +++ b/packages/kbn-typed-react-router-config/src/types/index.ts @@ -252,10 +252,9 @@ type AppendPath< TPath extends string > = NormalizePath<`${TPrefix}${NormalizePath<`/${TPath}`>}`>; -type MaybeUnion, U extends Record> = Omit & - { - [key in keyof U]: key extends keyof T ? T[key] | U[key] : U[key]; - }; +type MaybeUnion, U extends Record> = Omit & { + [key in keyof U]: key extends keyof T ? T[key] | U[key] : U[key]; +}; type MapRoute = TRoute extends Route ? MaybeUnion< diff --git a/packages/kbn-utility-types/src/jest/index.ts b/packages/kbn-utility-types/src/jest/index.ts index f6d14f23b504..e146e19d10f1 100644 --- a/packages/kbn-utility-types/src/jest/index.ts +++ b/packages/kbn-utility-types/src/jest/index.ts @@ -10,7 +10,6 @@ export type DeeplyMockedKeys = { [P in keyof T]: T[P] extends (...args: any[]) => any ? jest.MockInstance, Parameters> : DeeplyMockedKeys; -} & - T; +} & T; export type MockedKeys = { [P in keyof T]: jest.Mocked }; diff --git a/src/cli_encryption_keys/encryption_config.js b/src/cli_encryption_keys/encryption_config.js index 3f68ab9ef918..4ad46d65c08c 100644 --- a/src/cli_encryption_keys/encryption_config.js +++ b/src/cli_encryption_keys/encryption_config.js @@ -23,18 +23,15 @@ export class EncryptionConfig { ]; #encryptionMeta = { 'xpack.encryptedSavedObjects.encryptionKey': { - docs: - 'https://www.elastic.co/guide/en/kibana/current/xpack-security-secure-saved-objects.html#xpack-security-secure-saved-objects', + docs: 'https://www.elastic.co/guide/en/kibana/current/xpack-security-secure-saved-objects.html#xpack-security-secure-saved-objects', description: 'Used to encrypt stored objects such as dashboards and visualizations', }, 'xpack.reporting.encryptionKey': { - docs: - 'https://www.elastic.co/guide/en/kibana/current/reporting-settings-kb.html#general-reporting-settings', + docs: 'https://www.elastic.co/guide/en/kibana/current/reporting-settings-kb.html#general-reporting-settings', description: 'Used to encrypt saved reports', }, 'xpack.security.encryptionKey': { - docs: - 'https://www.elastic.co/guide/en/kibana/current/security-settings-kb.html#security-session-and-cookie-settings', + docs: 'https://www.elastic.co/guide/en/kibana/current/security-settings-kb.html#security-session-and-cookie-settings', description: 'Used to encrypt session information', }, }; diff --git a/src/core/public/apm_system.ts b/src/core/public/apm_system.ts index f5af7011e632..1a653636c54d 100644 --- a/src/core/public/apm_system.ts +++ b/src/core/public/apm_system.ts @@ -11,7 +11,8 @@ import { modifyUrl } from '@kbn/std'; import type { InternalApplicationStart } from './application'; /** "GET protocol://hostname:port/pathname" */ -const HTTP_REQUEST_TRANSACTION_NAME_REGEX = /^(GET|POST|PUT|HEAD|PATCH|DELETE|OPTIONS|CONNECT|TRACE)\s(.*)$/; +const HTTP_REQUEST_TRANSACTION_NAME_REGEX = + /^(GET|POST|PUT|HEAD|PATCH|DELETE|OPTIONS|CONNECT|TRACE)\s(.*)$/; /** * This is the entry point used to boot the frontend when serving a application diff --git a/src/core/public/application/scoped_history.ts b/src/core/public/application/scoped_history.ts index b932465f800c..2ab60e66b860 100644 --- a/src/core/public/application/scoped_history.ts +++ b/src/core/public/application/scoped_history.ts @@ -32,7 +32,8 @@ import { * @public */ export class ScopedHistory - implements History { + implements History +{ /** * Tracks whether or not the user has left this history's scope. All methods throw errors if called after scope has * been left. diff --git a/src/core/public/chrome/ui/header/header_action_menu.test.tsx b/src/core/public/chrome/ui/header/header_action_menu.test.tsx index 201be8848bac..e75b3b978bc1 100644 --- a/src/core/public/chrome/ui/header/header_action_menu.test.tsx +++ b/src/core/public/chrome/ui/header/header_action_menu.test.tsx @@ -41,17 +41,17 @@ describe('HeaderActionMenu', () => { }); }; - const createMountPoint = (id: string, content: string = id): MountPoint => ( - root - ): MockedUnmount => { - const container = document.createElement('DIV'); - // eslint-disable-next-line no-unsanitized/property - container.innerHTML = content; - root.appendChild(container); - const unmount = jest.fn(() => container.remove()); - unmounts[id] = unmount; - return unmount; - }; + const createMountPoint = + (id: string, content: string = id): MountPoint => + (root): MockedUnmount => { + const container = document.createElement('DIV'); + // eslint-disable-next-line no-unsanitized/property + container.innerHTML = content; + root.appendChild(container); + const unmount = jest.fn(() => container.remove()); + unmounts[id] = unmount; + return unmount; + }; it('mounts the current value of the provided observable', async () => { component = mount(); diff --git a/src/core/public/notifications/toasts/error_toast.test.tsx b/src/core/public/notifications/toasts/error_toast.test.tsx index 2fac3019db93..e0f917fb7f07 100644 --- a/src/core/public/notifications/toasts/error_toast.test.tsx +++ b/src/core/public/notifications/toasts/error_toast.test.tsx @@ -29,7 +29,9 @@ function render(props: ErrorToastProps = {}) { error={props.error || new Error('error message')} title={props.title || 'An error occured'} toastMessage={props.toastMessage || 'This is the toast message'} - i18nContext={() => ({ children }) => {children}} + i18nContext={() => + ({ children }) => + {children}} /> ); } diff --git a/src/core/public/overlays/banners/user_banner_service.test.ts b/src/core/public/overlays/banners/user_banner_service.test.ts index a13d7b0ca8e6..ff46a03886d7 100644 --- a/src/core/public/overlays/banners/user_banner_service.test.ts +++ b/src/core/public/overlays/banners/user_banner_service.test.ts @@ -72,7 +72,7 @@ describe('OverlayBannersService', () => { startService(); expect(banners.replace).toHaveBeenCalledTimes(0); - const update$ = (uiSettings.getUpdate$() as any) as Subject<{ + const update$ = uiSettings.getUpdate$() as any as Subject<{ key: string; }>; @@ -87,7 +87,7 @@ describe('OverlayBannersService', () => { it('removes banner when changed to empty string', () => { startService('remove me!'); - const update$ = (uiSettings.getUpdate$() as any) as Subject<{ + const update$ = uiSettings.getUpdate$() as any as Subject<{ key: string; }>; @@ -98,7 +98,7 @@ describe('OverlayBannersService', () => { it('removes banner when changed to undefined', () => { startService('remove me!'); - const update$ = (uiSettings.getUpdate$() as any) as Subject<{ + const update$ = uiSettings.getUpdate$() as any as Subject<{ key: string; }>; @@ -111,7 +111,7 @@ describe('OverlayBannersService', () => { startService('initial banner!'); expect(banners.replace).toHaveBeenCalledTimes(1); - const update$ = (uiSettings.getUpdate$() as any) as Subject<{ + const update$ = uiSettings.getUpdate$() as any as Subject<{ key: string; }>; diff --git a/src/core/public/plugins/plugin_context.ts b/src/core/public/plugins/plugin_context.ts index 49c895aa80fc..3461f570333d 100644 --- a/src/core/public/plugins/plugin_context.ts +++ b/src/core/public/plugins/plugin_context.ts @@ -56,7 +56,7 @@ export function createPluginInitializerContext( env: coreContext.env, config: { get() { - return (pluginConfig as unknown) as T; + return pluginConfig as unknown as T; }, }, }; diff --git a/src/core/public/plugins/plugin_reader.ts b/src/core/public/plugins/plugin_reader.ts index db3085930888..24508075975d 100644 --- a/src/core/public/plugins/plugin_reader.ts +++ b/src/core/public/plugins/plugin_reader.ts @@ -29,7 +29,7 @@ export interface CoreWindow { * Reads the plugin's bundle declared in the global context. */ export function read(name: string) { - const coreWindow = (window as unknown) as CoreWindow; + const coreWindow = window as unknown as CoreWindow; const exportId = `plugin/${name}/public`; if (!coreWindow.__kbnBundles__.has(exportId)) { diff --git a/src/core/public/plugins/plugins_service.test.mocks.ts b/src/core/public/plugins/plugins_service.test.mocks.ts index 1f85482569db..1858008e2801 100644 --- a/src/core/public/plugins/plugins_service.test.mocks.ts +++ b/src/core/public/plugins/plugins_service.test.mocks.ts @@ -14,12 +14,11 @@ export type MockedPluginInitializer = jest.Mock< any >; -export const mockPluginInitializerProvider: jest.Mock< - MockedPluginInitializer, - [PluginName] -> = jest.fn().mockImplementation(() => () => { - throw new Error('No provider specified'); -}); +export const mockPluginInitializerProvider: jest.Mock = jest + .fn() + .mockImplementation(() => () => { + throw new Error('No provider specified'); + }); jest.mock('./plugin_reader', () => ({ read: mockPluginInitializerProvider, diff --git a/src/core/public/plugins/plugins_service.test.ts b/src/core/public/plugins/plugins_service.test.ts index d85f8538e3a6..6bed95800941 100644 --- a/src/core/public/plugins/plugins_service.test.ts +++ b/src/core/public/plugins/plugins_service.test.ts @@ -117,7 +117,7 @@ describe('PluginsService', () => { }; // Reset these for each test. - mockPluginInitializers = new Map(([ + mockPluginInitializers = new Map([ [ 'pluginA', jest.fn(() => ({ @@ -146,7 +146,7 @@ describe('PluginsService', () => { stop: jest.fn(), })), ], - ] as unknown) as [[PluginName, any]]); + ] as unknown as [[PluginName, any]]); }); describe('#getOpaqueIds()', () => { diff --git a/src/core/public/utils/crypto/sha256.ts b/src/core/public/utils/crypto/sha256.ts index 009f0ee69a9e..c36099279d8f 100644 --- a/src/core/public/utils/crypto/sha256.ts +++ b/src/core/public/utils/crypto/sha256.ts @@ -39,70 +39,14 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ const K = [ - 0x428a2f98, - 0x71374491, - 0xb5c0fbcf, - 0xe9b5dba5, - 0x3956c25b, - 0x59f111f1, - 0x923f82a4, - 0xab1c5ed5, - 0xd807aa98, - 0x12835b01, - 0x243185be, - 0x550c7dc3, - 0x72be5d74, - 0x80deb1fe, - 0x9bdc06a7, - 0xc19bf174, - 0xe49b69c1, - 0xefbe4786, - 0x0fc19dc6, - 0x240ca1cc, - 0x2de92c6f, - 0x4a7484aa, - 0x5cb0a9dc, - 0x76f988da, - 0x983e5152, - 0xa831c66d, - 0xb00327c8, - 0xbf597fc7, - 0xc6e00bf3, - 0xd5a79147, - 0x06ca6351, - 0x14292967, - 0x27b70a85, - 0x2e1b2138, - 0x4d2c6dfc, - 0x53380d13, - 0x650a7354, - 0x766a0abb, - 0x81c2c92e, - 0x92722c85, - 0xa2bfe8a1, - 0xa81a664b, - 0xc24b8b70, - 0xc76c51a3, - 0xd192e819, - 0xd6990624, - 0xf40e3585, - 0x106aa070, - 0x19a4c116, - 0x1e376c08, - 0x2748774c, - 0x34b0bcb5, - 0x391c0cb3, - 0x4ed8aa4a, - 0x5b9cca4f, - 0x682e6ff3, - 0x748f82ee, - 0x78a5636f, - 0x84c87814, - 0x8cc70208, - 0x90befffa, - 0xa4506ceb, - 0xbef9a3f7, - 0xc67178f2, + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ]; const W = new Array(64); diff --git a/src/core/public/utils/mount.tsx b/src/core/public/utils/mount.tsx index 43d96c7f712c..fc23202e2c71 100644 --- a/src/core/public/utils/mount.tsx +++ b/src/core/public/utils/mount.tsx @@ -30,7 +30,9 @@ export const MountWrapper: React.FunctionComponent<{ mount: MountPoint; classNam * * @param node to get a mount for */ -export const mountReactNode = (node: React.ReactNode): MountPoint => (element: HTMLElement) => { - render({node}, element); - return () => unmountComponentAtNode(element); -}; +export const mountReactNode = + (node: React.ReactNode): MountPoint => + (element: HTMLElement) => { + render({node}, element); + return () => unmountComponentAtNode(element); + }; diff --git a/src/core/server/capabilities/resolve_capabilities.ts b/src/core/server/capabilities/resolve_capabilities.ts index 89da7b6c30a1..34d7894543b0 100644 --- a/src/core/server/capabilities/resolve_capabilities.ts +++ b/src/core/server/capabilities/resolve_capabilities.ts @@ -16,22 +16,24 @@ export type CapabilitiesResolver = ( useDefaultCapabilities: boolean ) => Promise; -export const getCapabilitiesResolver = ( - capabilities: () => Capabilities, - switchers: () => CapabilitiesSwitcher[] -): CapabilitiesResolver => async ( - request: KibanaRequest, - applications: string[], - useDefaultCapabilities: boolean -): Promise => { - return resolveCapabilities( - capabilities(), - switchers(), - request, - applications, - useDefaultCapabilities - ); -}; +export const getCapabilitiesResolver = + ( + capabilities: () => Capabilities, + switchers: () => CapabilitiesSwitcher[] + ): CapabilitiesResolver => + async ( + request: KibanaRequest, + applications: string[], + useDefaultCapabilities: boolean + ): Promise => { + return resolveCapabilities( + capabilities(), + switchers(), + request, + applications, + useDefaultCapabilities + ); + }; export const resolveCapabilities = async ( capabilities: Capabilities, diff --git a/src/core/server/config/test_utils.ts b/src/core/server/config/test_utils.ts index ab06ff50012b..e3f9ca7eb29f 100644 --- a/src/core/server/config/test_utils.ts +++ b/src/core/server/config/test_utils.ts @@ -22,7 +22,9 @@ function collectDeprecations( deprecation, path, })), - () => ({ message }) => deprecationMessages.push(message) + () => + ({ message }) => + deprecationMessages.push(message) ); return { messages: deprecationMessages, diff --git a/src/core/server/context/container/context.mock.ts b/src/core/server/context/container/context.mock.ts index 2a43006301c0..9996d609fc07 100644 --- a/src/core/server/context/container/context.mock.ts +++ b/src/core/server/context/container/context.mock.ts @@ -16,8 +16,10 @@ const createContextMock = (mockContext: any = {}) => { registerContext: jest.fn(), createHandler: jest.fn(), }; - contextMock.createHandler.mockImplementation((pluginId, handler) => (...args) => - Promise.resolve(handler(mockContext, ...args)) + contextMock.createHandler.mockImplementation( + (pluginId, handler) => + (...args) => + Promise.resolve(handler(mockContext, ...args)) ); return contextMock; }; diff --git a/src/core/server/context/container/context.ts b/src/core/server/context/container/context.ts index f3d91e268bd1..2650c2185360 100644 --- a/src/core/server/context/container/context.ts +++ b/src/core/server/context/container/context.ts @@ -288,15 +288,14 @@ export class ContextContainer implements IContextContainer { } /** Sorts context provider pairs by core pairs first. */ -const sortByCoreFirst = ( - coreId: symbol -): ((left: [any, { source: symbol }], right: [any, { source: symbol }]) => number) => ( - [leftName, leftProvider], - [rightName, rightProvider] -) => { - if (leftProvider.source === coreId) { - return rightProvider.source === coreId ? 0 : -1; - } else { - return rightProvider.source === coreId ? 1 : 0; - } -}; +const sortByCoreFirst = + ( + coreId: symbol + ): ((left: [any, { source: symbol }], right: [any, { source: symbol }]) => number) => + ([leftName, leftProvider], [rightName, rightProvider]) => { + if (leftProvider.source === coreId) { + return rightProvider.source === coreId ? 0 : -1; + } else { + return rightProvider.source === coreId ? 1 : 0; + } + }; diff --git a/src/core/server/core_app/core_app.test.ts b/src/core/server/core_app/core_app.test.ts index e5c3a592a72c..c13116577af7 100644 --- a/src/core/server/core_app/core_app.test.ts +++ b/src/core/server/core_app/core_app.test.ts @@ -132,7 +132,7 @@ describe('CoreApp', () => { const [[, handler]] = prebootHTTPResourcesRegistrar.register.mock.calls; const mockResponseFactory = httpResourcesMock.createResponseFactory(); handler( - ({} as unknown) as RequestHandlerContext, + {} as unknown as RequestHandlerContext, httpServerMock.createKibanaRequest(), mockResponseFactory ); diff --git a/src/core/server/core_usage_data/core_usage_stats_client.mock.ts b/src/core/server/core_usage_data/core_usage_stats_client.mock.ts index 438424f76d05..ac5855c3a4ba 100644 --- a/src/core/server/core_usage_data/core_usage_stats_client.mock.ts +++ b/src/core/server/core_usage_data/core_usage_stats_client.mock.ts @@ -9,7 +9,7 @@ import { CoreUsageStatsClient } from '.'; const createUsageStatsClientMock = () => - (({ + ({ getUsageStats: jest.fn().mockResolvedValue({}), incrementSavedObjectsBulkCreate: jest.fn().mockResolvedValue(null), incrementSavedObjectsBulkGet: jest.fn().mockResolvedValue(null), @@ -26,7 +26,7 @@ const createUsageStatsClientMock = () => incrementSavedObjectsExport: jest.fn().mockResolvedValue(null), incrementLegacyDashboardsImport: jest.fn().mockResolvedValue(null), incrementLegacyDashboardsExport: jest.fn().mockResolvedValue(null), - } as unknown) as jest.Mocked); + } as unknown as jest.Mocked); export const coreUsageStatsClientMock = { create: createUsageStatsClientMock, diff --git a/src/core/server/deprecations/deprecations_factory.test.ts b/src/core/server/deprecations/deprecations_factory.test.ts index 73beb84f57fa..85ef521538b1 100644 --- a/src/core/server/deprecations/deprecations_factory.test.ts +++ b/src/core/server/deprecations/deprecations_factory.test.ts @@ -55,10 +55,10 @@ describe('DeprecationsFactory', () => { }); describe('getAllDeprecations', () => { - const mockDependencies = ({ + const mockDependencies = { esClient: jest.fn(), savedObjectsClient: jest.fn(), - } as unknown) as GetDeprecationsContext; + } as unknown as GetDeprecationsContext; it('returns a flattened array of deprecations', async () => { const deprecationsFactory = new DeprecationsFactory({ logger }); @@ -184,10 +184,10 @@ describe('DeprecationsFactory', () => { }); describe('getDeprecations', () => { - const mockDependencies = ({ + const mockDependencies = { esClient: jest.fn(), savedObjectsClient: jest.fn(), - } as unknown) as GetDeprecationsContext; + } as unknown as GetDeprecationsContext; it('returns a flattened array of DeprecationInfo', async () => { const deprecationsFactory = new DeprecationsFactory({ logger }); diff --git a/src/core/server/deprecations/deprecations_registry.test.ts b/src/core/server/deprecations/deprecations_registry.test.ts index 82b09beaa512..0e4f48b18a0a 100644 --- a/src/core/server/deprecations/deprecations_registry.test.ts +++ b/src/core/server/deprecations/deprecations_registry.test.ts @@ -14,9 +14,9 @@ describe('DeprecationsRegistry', () => { describe('registerDeprecations', () => { it('throws if getDeprecations is not a function', async () => { const deprecationsRegistry = new DeprecationsRegistry(); - const deprecationsConfig = ({ + const deprecationsConfig = { getDeprecations: null, - } as unknown) as RegisterDeprecationsConfig; + } as unknown as RegisterDeprecationsConfig; expect(() => deprecationsRegistry.registerDeprecations(deprecationsConfig)).toThrowError( /getDeprecations must be a function/ ); @@ -46,7 +46,7 @@ describe('DeprecationsRegistry', () => { describe('getDeprecations', () => { it('returns all settled deprecations', async () => { const deprecationsRegistry = new DeprecationsRegistry(); - const mockContext = ({} as unknown) as GetDeprecationsContext; + const mockContext = {} as unknown as GetDeprecationsContext; const mockError = new Error(); const deprecationsConfigA = { getDeprecations: jest.fn().mockResolvedValue('hi') }; const deprecationsConfigB = { getDeprecations: jest.fn().mockRejectedValue(mockError) }; @@ -67,7 +67,7 @@ describe('DeprecationsRegistry', () => { it('passes dependencies to registered getDeprecations function', async () => { const deprecationsRegistry = new DeprecationsRegistry(); - const mockContext = ({} as unknown) as GetDeprecationsContext; + const mockContext = {} as unknown as GetDeprecationsContext; const deprecationsConfig = { getDeprecations: jest.fn().mockResolvedValue('hi') }; deprecationsRegistry.registerDeprecations(deprecationsConfig); const deprecations = await deprecationsRegistry.getDeprecations(mockContext); diff --git a/src/core/server/deprecations/deprecations_service.test.ts b/src/core/server/deprecations/deprecations_service.test.ts index bc0dbcef4a5b..0067cff1d230 100644 --- a/src/core/server/deprecations/deprecations_service.test.ts +++ b/src/core/server/deprecations/deprecations_service.test.ts @@ -93,9 +93,10 @@ describe('DeprecationsService', () => { expect(deprecationsFactory.getRegistry).toBeCalledTimes(1); expect(deprecationsFactory.getRegistry).toBeCalledWith('testDomain'); expect(deprecationsRegistry.registerDeprecations).toBeCalledTimes(1); - const configDeprecations = await deprecationsRegistry.registerDeprecations.mock.calls[0][0].getDeprecations( - getDeprecationsContext - ); + const configDeprecations = + await deprecationsRegistry.registerDeprecations.mock.calls[0][0].getDeprecations( + getDeprecationsContext + ); expect(configDeprecations).toMatchInlineSnapshot(` Array [ Object { @@ -136,9 +137,10 @@ describe('DeprecationsService', () => { deprecationsFactory.getRegistry.mockReturnValue(deprecationsRegistry); deprecationsService['registerConfigDeprecationsInfo'](deprecationsFactory); - const configDeprecations = await deprecationsRegistry.registerDeprecations.mock.calls[0][0].getDeprecations( - getDeprecationsContext - ); + const configDeprecations = + await deprecationsRegistry.registerDeprecations.mock.calls[0][0].getDeprecations( + getDeprecationsContext + ); expect(configDeprecations[0].level).toBe('warning'); }); }); diff --git a/src/core/server/deprecations/deprecations_service.ts b/src/core/server/deprecations/deprecations_service.ts index bc981c21ba97..cfc0aae443d1 100644 --- a/src/core/server/deprecations/deprecations_service.ts +++ b/src/core/server/deprecations/deprecations_service.ts @@ -126,7 +126,8 @@ export interface DeprecationsSetupDeps { /** @internal */ export class DeprecationsService - implements CoreService { + implements CoreService +{ private readonly logger: Logger; private readonly deprecationsFactory: DeprecationsFactory; diff --git a/src/core/server/elasticsearch/client/configure_client.test.ts b/src/core/server/elasticsearch/client/configure_client.test.ts index 4e2c9c22f42f..35fcb5819d01 100644 --- a/src/core/server/elasticsearch/client/configure_client.test.ts +++ b/src/core/server/elasticsearch/client/configure_client.test.ts @@ -25,10 +25,10 @@ import { configureClient } from './configure_client'; const createFakeConfig = ( parts: Partial = {} ): ElasticsearchClientConfig => { - return ({ + return { type: 'fake-config', ...parts, - } as unknown) as ElasticsearchClientConfig; + } as unknown as ElasticsearchClientConfig; }; const createFakeClient = () => { diff --git a/src/core/server/elasticsearch/client/configure_client.ts b/src/core/server/elasticsearch/client/configure_client.ts index efd22365d44f..93c404593af3 100644 --- a/src/core/server/elasticsearch/client/configure_client.ts +++ b/src/core/server/elasticsearch/client/configure_client.ts @@ -102,9 +102,12 @@ function getResponseMessage(event: RequestEvent): string { * Returns stringified debug information from an Elasticsearch request event * useful for logging in case of an unexpected failure. */ -export function getRequestDebugMeta( - event: RequestEvent -): { url: string; body: string; statusCode: number | null; method: string } { +export function getRequestDebugMeta(event: RequestEvent): { + url: string; + body: string; + statusCode: number | null; + method: string; +} { const params = event.meta.request.params; // definition is wrong, `params.querystring` can be either a string or an object const querystring = convertQueryString(params.querystring); diff --git a/src/core/server/elasticsearch/client/mocks.ts b/src/core/server/elasticsearch/client/mocks.ts index 5e2bf784b2a1..7c4cde1ae424 100644 --- a/src/core/server/elasticsearch/client/mocks.ts +++ b/src/core/server/elasticsearch/client/mocks.ts @@ -92,7 +92,7 @@ const createInternalClientMock = ( export type ElasticsearchClientMock = DeeplyMockedKeys; const createClientMock = (res?: MockedTransportRequestPromise): ElasticsearchClientMock => - (createInternalClientMock(res) as unknown) as ElasticsearchClientMock; + createInternalClientMock(res) as unknown as ElasticsearchClientMock; export interface ScopedClusterClientMock { asInternalUser: ElasticsearchClientMock; diff --git a/src/core/server/elasticsearch/elasticsearch_service.ts b/src/core/server/elasticsearch/elasticsearch_service.ts index eebd73274928..09c96696b798 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.ts @@ -38,7 +38,8 @@ export interface SetupDeps { /** @internal */ export class ElasticsearchService - implements CoreService { + implements CoreService +{ private readonly log: Logger; private readonly config$: Observable; private stop$ = new Subject(); diff --git a/src/core/server/elasticsearch/integration_tests/client.test.ts b/src/core/server/elasticsearch/integration_tests/client.test.ts index 6e40c638614b..f4046be7b20e 100644 --- a/src/core/server/elasticsearch/integration_tests/client.test.ts +++ b/src/core/server/elasticsearch/integration_tests/client.test.ts @@ -38,24 +38,27 @@ describe('elasticsearch clients', () => { it('does not return deprecation warning when x-elastic-product-origin header is set', async () => { // Header should be automatically set by Core - const resp1 = await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings( - { index: '.kibana' } - ); + const resp1 = + await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings({ + index: '.kibana', + }); expect(resp1.headers).not.toHaveProperty('warning'); // Also test setting it explicitly - const resp2 = await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings( - { index: '.kibana' }, - { headers: { 'x-elastic-product-origin': 'kibana' } } - ); + const resp2 = + await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings( + { index: '.kibana' }, + { headers: { 'x-elastic-product-origin': 'kibana' } } + ); expect(resp2.headers).not.toHaveProperty('warning'); }); it('returns deprecation warning when x-elastic-product-orign header is not set', async () => { - const resp = await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings( - { index: '.kibana' }, - { headers: { 'x-elastic-product-origin': null } } - ); + const resp = + await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings( + { index: '.kibana' }, + { headers: { 'x-elastic-product-origin': null } } + ); expect(resp.headers).toHaveProperty('warning'); expect(resp.headers!.warning).toMatch('system indices'); diff --git a/src/core/server/environment/resolve_uuid.test.ts b/src/core/server/environment/resolve_uuid.test.ts index 40db2d697906..3ee65e8ac99c 100644 --- a/src/core/server/environment/resolve_uuid.test.ts +++ b/src/core/server/environment/resolve_uuid.test.ts @@ -35,7 +35,7 @@ const mockReadFile = ({ uuid: string; error: any; }>) => { - ((readFile as unknown) as jest.Mock).mockImplementation(() => { + (readFile as unknown as jest.Mock).mockImplementation(() => { if (error) { return Promise.reject(error); } else { @@ -45,7 +45,7 @@ const mockReadFile = ({ }; const mockWriteFile = (error?: object) => { - ((writeFile as unknown) as jest.Mock).mockImplementation(() => { + (writeFile as unknown as jest.Mock).mockImplementation(() => { if (error) { return Promise.reject(error); } else { diff --git a/src/core/server/execution_context/execution_context_service.ts b/src/core/server/execution_context/execution_context_service.ts index d8ff5fca7847..6e2b809e2304 100644 --- a/src/core/server/execution_context/execution_context_service.ts +++ b/src/core/server/execution_context/execution_context_service.ts @@ -69,7 +69,8 @@ export interface ExecutionContextSetup { export type ExecutionContextStart = ExecutionContextSetup; export class ExecutionContextService - implements CoreService { + implements CoreService +{ private readonly log: Logger; private readonly contextStore: AsyncLocalStorage; private readonly requestIdStore: AsyncLocalStorage<{ requestId: string }>; diff --git a/src/core/server/http/http_service.mock.ts b/src/core/server/http/http_service.mock.ts index 4cb1bc9867d2..894ff38e12a3 100644 --- a/src/core/server/http/http_service.mock.ts +++ b/src/core/server/http/http_service.mock.ts @@ -108,7 +108,7 @@ const createPrebootContractMock = () => { const createInternalSetupContractMock = () => { const mock: InternalHttpServiceSetupMock = { // we can mock other hapi server methods when we need it - server: ({ + server: { name: 'http-server-test', version: 'kibana', route: jest.fn(), @@ -116,7 +116,7 @@ const createInternalSetupContractMock = () => { stop: jest.fn(), config: jest.fn().mockReturnValue(configMock.create()), // @ts-expect-error somehow it thinks that `Server` isn't a `Construtable` - } as unknown) as jest.MockedClass, + } as unknown as jest.MockedClass, createCookieSessionStorageFactory: jest.fn(), registerOnPreRouting: jest.fn(), registerOnPreAuth: jest.fn(), diff --git a/src/core/server/http/http_service.ts b/src/core/server/http/http_service.ts index 538a4c065e99..98ae0f8b81aa 100644 --- a/src/core/server/http/http_service.ts +++ b/src/core/server/http/http_service.ts @@ -51,7 +51,8 @@ interface SetupDeps { /** @internal */ export class HttpService - implements CoreService { + implements CoreService +{ private readonly prebootServer: HttpServer; private isPrebootServerStopped = false; private readonly httpServer: HttpServer; diff --git a/src/core/server/http/integration_tests/lifecycle.test.ts b/src/core/server/http/integration_tests/lifecycle.test.ts index 098dfbebfa7b..1db0b3c13152 100644 --- a/src/core/server/http/integration_tests/lifecycle.test.ts +++ b/src/core/server/http/integration_tests/lifecycle.test.ts @@ -51,9 +51,11 @@ interface StorageData { describe('OnPreRouting', () => { it('supports registering a request interceptor', async () => { - const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreRouting, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/', validate: false }, (context, req, res) => res.ok({ body: 'ok' })); @@ -76,9 +78,11 @@ describe('OnPreRouting', () => { }); it('supports request forwarding to specified url', async () => { - const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreRouting, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/initial', validate: false }, (context, req, res) => @@ -110,9 +114,11 @@ describe('OnPreRouting', () => { }); it('provides original request url', async () => { - const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreRouting, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/login', validate: false }, (context, req, res) => { @@ -135,9 +141,11 @@ describe('OnPreRouting', () => { }); it('provides original request url if rewritten several times', async () => { - const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreRouting, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/reroute-2', validate: false }, (context, req, res) => { @@ -161,9 +169,11 @@ describe('OnPreRouting', () => { }); it('does not provide request url if interceptor does not rewrite url', async () => { - const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreRouting, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/login', validate: false }, (context, req, res) => { @@ -184,9 +194,11 @@ describe('OnPreRouting', () => { }); it('supports redirection from the interceptor', async () => { - const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreRouting, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); const redirectUrl = '/redirectUrl'; @@ -207,9 +219,11 @@ describe('OnPreRouting', () => { }); it('supports rejecting request and adjusting response headers', async () => { - const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreRouting, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/', validate: false }, (context, req, res) => res.ok()); @@ -229,9 +243,11 @@ describe('OnPreRouting', () => { }); it('does not expose error details if interceptor throws', async () => { - const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreRouting, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/', validate: false }, (context, req, res) => res.ok()); @@ -254,9 +270,11 @@ describe('OnPreRouting', () => { }); it('returns internal error if interceptor returns unexpected result', async () => { - const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreRouting, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/', validate: false }, (context, req, res) => res.ok()); @@ -277,9 +295,11 @@ describe('OnPreRouting', () => { }); it(`doesn't share request object between interceptors`, async () => { - const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreRouting, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); registerOnPreRouting((req, res, t) => { @@ -1172,9 +1192,11 @@ describe('Auth', () => { describe('OnPreResponse', () => { it('supports registering response interceptors', async () => { - const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreResponse, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/', validate: false }, (context, req, res) => res.ok({ body: 'ok' })); @@ -1197,9 +1219,11 @@ describe('OnPreResponse', () => { }); it('supports additional headers attachments', async () => { - const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreResponse, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/', validate: false }, (context, req, res) => @@ -1226,9 +1250,11 @@ describe('OnPreResponse', () => { }); it('logs a warning if interceptor rewrites response header', async () => { - const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreResponse, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/', validate: false }, (context, req, res) => @@ -1255,9 +1281,11 @@ describe('OnPreResponse', () => { }); it("doesn't expose error details if interceptor throws", async () => { - const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreResponse, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/', validate: false }, (context, req, res) => res.ok(undefined)); @@ -1279,9 +1307,11 @@ describe('OnPreResponse', () => { }); it('returns internal error if interceptor returns unexpected result', async () => { - const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreResponse, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/', validate: false }, (context, req, res) => res.ok()); @@ -1301,9 +1331,11 @@ describe('OnPreResponse', () => { }); it('cannot change response statusCode', async () => { - const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreResponse, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); registerOnPreResponse((req, res, t) => { @@ -1319,9 +1351,11 @@ describe('OnPreResponse', () => { }); it('has no access to request body', async () => { - const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreResponse, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); let requestBody = null; registerOnPreResponse((req, res, t) => { @@ -1354,9 +1388,11 @@ describe('OnPreResponse', () => { }); it('supports rendering a different response body', async () => { - const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreResponse, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/', validate: false }, (context, req, res) => { @@ -1380,9 +1416,11 @@ describe('OnPreResponse', () => { }); it('supports rendering a different response body + headers', async () => { - const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup( - setupDeps - ); + const { + registerOnPreResponse, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/', validate: false }, (context, req, res) => { diff --git a/src/core/server/http/integration_tests/request.test.ts b/src/core/server/http/integration_tests/request.test.ts index 0a30bfac85f5..a2560c2c39fa 100644 --- a/src/core/server/http/integration_tests/request.test.ts +++ b/src/core/server/http/integration_tests/request.test.ts @@ -245,9 +245,11 @@ describe('KibanaRequest', () => { }); it('does not complete before response has been sent', async () => { - const { server: innerServer, createRouter, registerOnPreAuth } = await server.setup( - setupDeps - ); + const { + server: innerServer, + createRouter, + registerOnPreAuth, + } = await server.setup(setupDeps); const router = createRouter('/'); const nextSpy = jest.fn(); diff --git a/src/core/server/http/integration_tests/router.test.ts b/src/core/server/http/integration_tests/router.test.ts index a3e872ee3ea8..80676b6be6c6 100644 --- a/src/core/server/http/integration_tests/router.test.ts +++ b/src/core/server/http/integration_tests/router.test.ts @@ -64,9 +64,12 @@ describe('Options', () => { }); it('Authenticated user has access to a route', async () => { - const { server: innerServer, createRouter, registerAuth, auth } = await server.setup( - setupDeps - ); + const { + server: innerServer, + createRouter, + registerAuth, + auth, + } = await server.setup(setupDeps); const router = createRouter('/'); registerAuth((req, res, toolkit) => { @@ -91,9 +94,12 @@ describe('Options', () => { }); it('User with no credentials can access a route', async () => { - const { server: innerServer, createRouter, registerAuth, auth } = await server.setup( - setupDeps - ); + const { + server: innerServer, + createRouter, + registerAuth, + auth, + } = await server.setup(setupDeps); const router = createRouter('/'); registerAuth((req, res, toolkit) => toolkit.notHandled()); @@ -117,9 +123,12 @@ describe('Options', () => { }); it('User with invalid credentials can access a route', async () => { - const { server: innerServer, createRouter, registerAuth, auth } = await server.setup( - setupDeps - ); + const { + server: innerServer, + createRouter, + registerAuth, + auth, + } = await server.setup(setupDeps); const router = createRouter('/'); registerAuth((req, res, toolkit) => res.unauthorized()); @@ -143,9 +152,12 @@ describe('Options', () => { }); it('does not redirect user and allows access to a resource', async () => { - const { server: innerServer, createRouter, registerAuth, auth } = await server.setup( - setupDeps - ); + const { + server: innerServer, + createRouter, + registerAuth, + auth, + } = await server.setup(setupDeps); const router = createRouter('/'); registerAuth((req, res, toolkit) => @@ -197,9 +209,12 @@ describe('Options', () => { }); it('Authenticated user has access to a route', async () => { - const { server: innerServer, createRouter, registerAuth, auth } = await server.setup( - setupDeps - ); + const { + server: innerServer, + createRouter, + registerAuth, + auth, + } = await server.setup(setupDeps); const router = createRouter('/'); registerAuth((req, res, toolkit) => { @@ -277,9 +292,12 @@ describe('Options', () => { describe('false', () => { it('does not try to authenticate a user', async () => { - const { server: innerServer, createRouter, registerAuth, auth } = await server.setup( - setupDeps - ); + const { + server: innerServer, + createRouter, + registerAuth, + auth, + } = await server.setup(setupDeps); const router = createRouter('/'); const authHook = jest.fn(); @@ -1844,9 +1862,11 @@ describe('ETag', () => { describe('registerRouterAfterListening', () => { it('allows a router to be registered before server has started listening', async () => { - const { server: innerServer, createRouter, registerRouterAfterListening } = await server.setup( - setupDeps - ); + const { + server: innerServer, + createRouter, + registerRouterAfterListening, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/', validate: false }, (context, req, res) => { @@ -1869,9 +1889,11 @@ describe('registerRouterAfterListening', () => { }); it('allows a router to be registered after server has started listening', async () => { - const { server: innerServer, createRouter, registerRouterAfterListening } = await server.setup( - setupDeps - ); + const { + server: innerServer, + createRouter, + registerRouterAfterListening, + } = await server.setup(setupDeps); const router = createRouter('/'); router.get({ path: '/', validate: false }, (context, req, res) => { diff --git a/src/core/server/http/logging/get_payload_size.test.ts b/src/core/server/http/logging/get_payload_size.test.ts index 30cb547dd98b..36ef2e9c8e5a 100644 --- a/src/core/server/http/logging/get_payload_size.test.ts +++ b/src/core/server/http/logging/get_payload_size.test.ts @@ -226,11 +226,11 @@ describe('getPayloadSize', () => { test('always provides content-length header if available', () => { const headers = { 'content-length': '123' }; const result = getResponsePayloadBytes( - ({ + { headers, variety: 'plain', source: 'abc', - } as unknown) as Response, + } as unknown as Response, logger ); expect(result).toBe(123); @@ -238,19 +238,19 @@ describe('getPayloadSize', () => { test('uses first value when hapi header is an array', () => { const headers = { 'content-length': ['123', '456'] }; - const result = getResponsePayloadBytes(({ headers } as unknown) as Response, logger); + const result = getResponsePayloadBytes({ headers } as unknown as Response, logger); expect(result).toBe(123); }); test('returns undefined if length is NaN', () => { const headers = { 'content-length': 'oops' }; - const result = getResponsePayloadBytes(({ headers } as unknown) as Response, logger); + const result = getResponsePayloadBytes({ headers } as unknown as Response, logger); expect(result).toBeUndefined(); }); }); test('defaults to undefined', () => { - const result = getResponsePayloadBytes(({} as unknown) as Response, logger); + const result = getResponsePayloadBytes({} as unknown as Response, logger); expect(result).toBeUndefined(); }); @@ -262,10 +262,10 @@ describe('getPayloadSize', () => { }, }; const result = getResponsePayloadBytes( - ({ + { variety: 'plain', source: payload.circular, - } as unknown) as Response, + } as unknown as Response, logger ); expect(result).toBeUndefined(); @@ -279,10 +279,10 @@ describe('getPayloadSize', () => { }, }; getResponsePayloadBytes( - ({ + { variety: 'plain', source: payload.circular, - } as unknown) as Response, + } as unknown as Response, logger ); expect(logger.warn.mock.calls[0][0]).toMatchInlineSnapshot( diff --git a/src/core/server/http/logging/get_response_log.test.ts b/src/core/server/http/logging/get_response_log.test.ts index 5f749220138d..df91ae9c1a98 100644 --- a/src/core/server/http/logging/get_response_log.test.ts +++ b/src/core/server/http/logging/get_response_log.test.ts @@ -40,7 +40,7 @@ function createMockHapiRequest({ query = {}, response = { headers: {}, statusCode: 200 }, }: RequestFixtureOptions = {}): Request { - return ({ + return { auth, body, headers, @@ -50,7 +50,7 @@ function createMockHapiRequest({ path, query, response, - } as unknown) as Request; + } as unknown as Request; } describe('getEcsResponseLog', () => { diff --git a/src/core/server/http/router/error_wrapper.test.ts b/src/core/server/http/router/error_wrapper.test.ts index 53ee3bff61d9..a25e9bb1df9b 100644 --- a/src/core/server/http/router/error_wrapper.test.ts +++ b/src/core/server/http/router/error_wrapper.test.ts @@ -11,9 +11,11 @@ import { KibanaResponse, KibanaResponseFactory, kibanaResponseFactory } from './ import { wrapErrors } from './error_wrapper'; import { KibanaRequest, RequestHandler, RequestHandlerContext } from 'kibana/server'; -const createHandler = (handler: () => any): RequestHandler => () => { - return handler(); -}; +const createHandler = + (handler: () => any): RequestHandler => + () => { + return handler(); + }; describe('wrapErrors', () => { let context: RequestHandlerContext; diff --git a/src/core/server/http/router/request.ts b/src/core/server/http/router/request.ts index 42e342f762e4..1f5c03953c9f 100644 --- a/src/core/server/http/router/request.ts +++ b/src/core/server/http/router/request.ts @@ -240,13 +240,18 @@ export class KibanaRequest< private getRouteInfo(request: Request): KibanaRequestRoute { const method = request.method as Method; - const { parse, maxBytes, allow, output, timeout: payloadTimeout } = - request.route.settings.payload || {}; + const { + parse, + maxBytes, + allow, + output, + timeout: payloadTimeout, + } = request.route.settings.payload || {}; // net.Socket#timeout isn't documented, yet, and isn't part of the types... https://github.com/nodejs/node/pull/34543 // the socket is also undefined when using @hapi/shot, or when a "fake request" is used const socketTimeout = (request.raw.req.socket as any)?.timeout; - const options = ({ + const options = { authRequired: this.getAuthRequired(request), // TypeScript note: Casting to `RouterOptions` to fix the following error: // @@ -271,7 +276,7 @@ export class KibanaRequest< accepts: allow, output: output as typeof validBodyOutput[number], // We do not support all the HAPI-supported outputs and TS complains }, - } as unknown) as KibanaRequestRouteOptions; // TS does not understand this is OK so I'm enforced to do this enforced casting + } as unknown as KibanaRequestRouteOptions; // TS does not understand this is OK so I'm enforced to do this enforced casting return { path: request.path, diff --git a/src/core/server/http/router/response.ts b/src/core/server/http/router/response.ts index 6cea7fcf4c94..331a1ab38f06 100644 --- a/src/core/server/http/router/response.ts +++ b/src/core/server/http/router/response.ts @@ -45,7 +45,8 @@ export function isKibanaResponse(response: Record): response is IKi * @internal */ export class KibanaResponse - implements IKibanaResponse { + implements IKibanaResponse +{ constructor( public readonly status: number, public readonly payload?: T, diff --git a/src/core/server/http/router/router.ts b/src/core/server/http/router/router.ts index 75fcc1bb0e08..d2d8dfa2cc72 100644 --- a/src/core/server/http/router/router.ts +++ b/src/core/server/http/router/router.ts @@ -203,7 +203,8 @@ function validOptions( * @internal */ export class Router - implements IRouter { + implements IRouter +{ public routes: Array> = []; public get: IRouter['get']; public post: IRouter['post']; @@ -216,25 +217,27 @@ export class Router ) { - const buildMethod = (method: Method) => ( - route: RouteConfig, - handler: RequestHandler - ) => { - const routeSchemas = routeSchemasFromRouteConfig(route, method); - - this.routes.push({ - handler: async (req, responseToolkit) => - await this.handle({ - routeSchemas, - request: req, - responseToolkit, - handler: this.enhanceWithContext(handler), - }), - method, - path: getRouteFullPath(this.routerPath, route.path), - options: validOptions(method, route), - }); - }; + const buildMethod = + (method: Method) => + ( + route: RouteConfig, + handler: RequestHandler + ) => { + const routeSchemas = routeSchemasFromRouteConfig(route, method); + + this.routes.push({ + handler: async (req, responseToolkit) => + await this.handle({ + routeSchemas, + request: req, + responseToolkit, + handler: this.enhanceWithContext(handler), + }), + method, + path: getRouteFullPath(this.routerPath, route.path), + options: validOptions(method, route), + }); + }; this.get = buildMethod('get'); this.post = buildMethod('post'); diff --git a/src/core/server/logging/appenders/rewrite/policies/meta/meta_policy.test.ts b/src/core/server/logging/appenders/rewrite/policies/meta/meta_policy.test.ts index faa026363ed4..f03c5bd9d1f8 100644 --- a/src/core/server/logging/appenders/rewrite/policies/meta/meta_policy.test.ts +++ b/src/core/server/logging/appenders/rewrite/policies/meta/meta_policy.test.ts @@ -93,10 +93,10 @@ describe('MetaRewritePolicy', () => { it('does not touch anything outside of LogMeta', () => { const policy = createPolicy('update', [{ path: 'a', value: 'bar' }]); const message = Symbol(); - expect( - policy.rewrite(({ message, meta: { a: 'foo' } } as unknown) as LogRecord).message - ).toBe(message); - expect(policy.rewrite(({ message, meta: { a: 'foo' } } as unknown) as LogRecord)) + expect(policy.rewrite({ message, meta: { a: 'foo' } } as unknown as LogRecord).message).toBe( + message + ); + expect(policy.rewrite({ message, meta: { a: 'foo' } } as unknown as LogRecord)) .toMatchInlineSnapshot(` Object { "message": Symbol(), @@ -147,9 +147,9 @@ describe('MetaRewritePolicy', () => { const policy = createPolicy('remove', [{ path: 'message' }]); const message = Symbol(); expect( - policy.rewrite(({ message, meta: { message: 'foo' } } as unknown) as LogRecord).message + policy.rewrite({ message, meta: { message: 'foo' } } as unknown as LogRecord).message ).toBe(message); - expect(policy.rewrite(({ message, meta: { message: 'foo' } } as unknown) as LogRecord)) + expect(policy.rewrite({ message, meta: { message: 'foo' } } as unknown as LogRecord)) .toMatchInlineSnapshot(` Object { "message": Symbol(), diff --git a/src/core/server/logging/logging_system.mock.ts b/src/core/server/logging/logging_system.mock.ts index c74c7d962ff7..1ca778afa31a 100644 --- a/src/core/server/logging/logging_system.mock.ts +++ b/src/core/server/logging/logging_system.mock.ts @@ -42,7 +42,7 @@ const collectLoggingSystemMock = (loggerFactory: LoggerFactory) => { }; const clearLoggingSystemMock = (loggerFactory: LoggerFactory) => { - const mockedLoggerFactory = (loggerFactory as unknown) as jest.Mocked; + const mockedLoggerFactory = loggerFactory as unknown as jest.Mocked; mockedLoggerFactory.get.mockClear(); mockedLoggerFactory.asLoggerFactory.mockClear(); mockedLoggerFactory.upgrade.mockClear(); diff --git a/src/core/server/logging/logging_system.test.ts b/src/core/server/logging/logging_system.test.ts index 8eed2aecb21d..dd546d4e7eac 100644 --- a/src/core/server/logging/logging_system.test.ts +++ b/src/core/server/logging/logging_system.test.ts @@ -24,7 +24,7 @@ const timestamp = new Date(Date.UTC(2012, 1, 1, 14, 33, 22, 11)); let mockConsoleLog: jest.SpyInstance; import { createWriteStream } from 'fs'; -const mockCreateWriteStream = (createWriteStream as unknown) as jest.Mock; +const mockCreateWriteStream = createWriteStream as unknown as jest.Mock; import { LoggingSystem, config } from '.'; diff --git a/src/core/server/metrics/event_loop_delays/event_loop_delays_monitor.mocks.ts b/src/core/server/metrics/event_loop_delays/event_loop_delays_monitor.mocks.ts index ee96668cf3e7..691bfc5030c9 100644 --- a/src/core/server/metrics/event_loop_delays/event_loop_delays_monitor.mocks.ts +++ b/src/core/server/metrics/event_loop_delays/event_loop_delays_monitor.mocks.ts @@ -32,13 +32,13 @@ function createMockHistogram(overwrites: Partial = {}): Inter function createMockEventLoopDelaysMonitor() { const mockCollect = jest.fn(); - const MockEventLoopDelaysMonitor: jest.MockedClass< - typeof EventLoopDelaysMonitor - > = jest.fn().mockReturnValue({ - collect: mockCollect, - reset: jest.fn(), - stop: jest.fn(), - }); + const MockEventLoopDelaysMonitor: jest.MockedClass = jest + .fn() + .mockReturnValue({ + collect: mockCollect, + reset: jest.fn(), + stop: jest.fn(), + }); mockCollect.mockReturnValue(createMockHistogram()); diff --git a/src/core/server/metrics/logging/get_ops_metrics_log.test.ts b/src/core/server/metrics/logging/get_ops_metrics_log.test.ts index 2d7a6bebf255..cba188c94c74 100644 --- a/src/core/server/metrics/logging/get_ops_metrics_log.test.ts +++ b/src/core/server/metrics/logging/get_ops_metrics_log.test.ts @@ -37,7 +37,7 @@ function createMockOpsMetrics(testMetrics: Partial): OpsMetrics { ...testMetrics, }; } -const testMetrics = ({ +const testMetrics = { process: { memory: { heap: { used_in_bytes: 100 } }, uptime_in_millis: 1500, @@ -50,7 +50,7 @@ const testMetrics = ({ '15m': 30, }, }, -} as unknown) as Partial; +} as unknown as Partial; describe('getEcsOpsMetricsLog', () => { it('provides correctly formatted message', () => { @@ -67,11 +67,11 @@ describe('getEcsOpsMetricsLog', () => { it('excludes values from the message if unavailable', () => { const baseMetrics = createBaseOpsMetrics(); - const missingMetrics = ({ + const missingMetrics = { ...baseMetrics, process: {}, os: {}, - } as unknown) as OpsMetrics; + } as unknown as OpsMetrics; const logMeta = getEcsOpsMetricsLog(missingMetrics); expect(logMeta.message).toMatchInlineSnapshot(`""`); }); diff --git a/src/core/server/metrics/metrics_service.ts b/src/core/server/metrics/metrics_service.ts index 78e4dd98f93d..8e9604b50fb5 100644 --- a/src/core/server/metrics/metrics_service.ts +++ b/src/core/server/metrics/metrics_service.ts @@ -23,7 +23,8 @@ interface MetricsServiceSetupDeps { /** @internal */ export class MetricsService - implements CoreService { + implements CoreService +{ private readonly logger: Logger; private readonly opsMetricsLogger: Logger; private metricsCollector?: OpsMetricsCollector; diff --git a/src/core/server/plugins/discovery/plugins_discovery.test.ts b/src/core/server/plugins/discovery/plugins_discovery.test.ts index 15e53b0a34f7..958e051d0476 100644 --- a/src/core/server/plugins/discovery/plugins_discovery.test.ts +++ b/src/core/server/plugins/discovery/plugins_discovery.test.ts @@ -417,9 +417,8 @@ describe('plugins discovery system', () => { [`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/plugin`]: Plugins.valid('plugin3'), [`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/plugin`]: Plugins.valid('plugin4'), [`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/sub5/plugin`]: Plugins.valid('plugin5'), - [`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/sub5/sub6/plugin`]: Plugins.valid( - 'plugin6' - ), + [`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/sub5/sub6/plugin`]: + Plugins.valid('plugin6'), }, { createCwd: false } ); diff --git a/src/core/server/plugins/discovery/scan_plugin_search_paths.test.ts b/src/core/server/plugins/discovery/scan_plugin_search_paths.test.ts index 8c5e1f256aaa..548c479975dd 100644 --- a/src/core/server/plugins/discovery/scan_plugin_search_paths.test.ts +++ b/src/core/server/plugins/discovery/scan_plugin_search_paths.test.ts @@ -196,9 +196,8 @@ describe('scanPluginSearchPaths', () => { [`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/plugin`]: Plugins.valid('plugin3'), [`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/plugin`]: Plugins.valid('plugin4'), [`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/sub5/plugin`]: Plugins.valid('plugin5'), - [`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/sub5/sub6/plugin`]: Plugins.valid( - 'plugin6' - ), + [`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/sub5/sub6/plugin`]: + Plugins.valid('plugin6'), }, { createCwd: false } ); 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 792858b53b5e..cf30d6c80393 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 @@ -69,7 +69,7 @@ describe('#importSavedObjectsFromStream', () => { let readStream: Readable; const objectLimit = 10; - const overwrite = (Symbol() as unknown) as boolean; + const overwrite = Symbol() as unknown as boolean; let savedObjectsClient: jest.Mocked; let typeRegistry: jest.Mocked; const namespace = 'some-namespace'; diff --git a/src/core/server/saved_objects/import/lib/check_conflicts.test.ts b/src/core/server/saved_objects/import/lib/check_conflicts.test.ts index 3370dda05f68..6ab37b0122e4 100644 --- a/src/core/server/saved_objects/import/lib/check_conflicts.test.ts +++ b/src/core/server/saved_objects/import/lib/check_conflicts.test.ts @@ -23,7 +23,7 @@ const createObject = (type: string, id: string): SavedObjectType => ({ type, id, attributes: { title: 'some-title' }, - references: (Symbol() as unknown) as SavedObjectReference[], + references: Symbol() as unknown as SavedObjectReference[], }); const getResultMock = { diff --git a/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts b/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts index 011e5500b8d9..03d94492e7ec 100644 --- a/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts +++ b/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts @@ -34,7 +34,7 @@ const createObject = ( type, id, attributes: { title: `Title for ${type}:${id}` }, - references: (Symbol() as unknown) as SavedObjectReference[], + references: Symbol() as unknown as SavedObjectReference[], ...(originId && { originId }), ...(updatedAt && { updated_at: updatedAt }), }); diff --git a/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts b/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts index 8c5d05b253f1..38372e8fad6f 100644 --- a/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts +++ b/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts @@ -120,7 +120,7 @@ describe('#createSavedObjects', () => { }), conflict: (type: string, id: string) => { const error = SavedObjectsErrorHelpers.createConflictError(type, id).output.payload; - return ({ type, id, error } as unknown) as SavedObject; + return { type, id, error } as unknown as SavedObject; }, unresolvableConflict: (type: string, id: string) => { const conflictMock = getResultMock.conflict(type, id); @@ -253,7 +253,7 @@ describe('#createSavedObjects', () => { expectBulkCreateArgs.objects(1, argObjs); }; const testBulkCreateOptions = async (namespace?: string) => { - const overwrite = (Symbol() as unknown) as boolean; + const overwrite = Symbol() as unknown as boolean; const options = setupParams({ objects: objs, namespace, overwrite }); setupMockResults(options); diff --git a/src/core/server/saved_objects/import/lib/regenerate_ids.test.ts b/src/core/server/saved_objects/import/lib/regenerate_ids.test.ts index e70476205f03..2696a52e0554 100644 --- a/src/core/server/saved_objects/import/lib/regenerate_ids.test.ts +++ b/src/core/server/saved_objects/import/lib/regenerate_ids.test.ts @@ -11,11 +11,11 @@ import { regenerateIds } from './regenerate_ids'; import { SavedObject } from '../../types'; describe('#regenerateIds', () => { - const objects = ([ + const objects = [ { type: 'foo', id: '1' }, { type: 'bar', id: '2' }, { type: 'baz', id: '3' }, - ] as any) as SavedObject[]; + ] as any as SavedObject[]; test('returns expected values', () => { mockUuidv4 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 3d4e95cf709d..d7d7544baafc 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 @@ -259,7 +259,7 @@ describe('#importSavedObjectsFromStream', () => { }); test('checks conflicts', async () => { - const createNewCopies = (Symbol() as unknown) as boolean; + const createNewCopies = Symbol() as unknown as boolean; const retries = [createRetry()]; const options = setupOptions({ retries, createNewCopies }); const collectedObjects = [createObject()]; @@ -282,7 +282,7 @@ describe('#importSavedObjectsFromStream', () => { test('gets import ID map for retries', async () => { const retries = [createRetry()]; - const createNewCopies = (Symbol() as unknown) as boolean; + const createNewCopies = Symbol() as unknown as boolean; const options = setupOptions({ retries, createNewCopies }); const filteredObjects = [createObject()]; getMockFn(checkConflicts).mockResolvedValue({ diff --git a/src/core/server/saved_objects/migrations/mocks.ts b/src/core/server/saved_objects/migrations/mocks.ts index ef806aa5f0fc..4bd4e2a1e52f 100644 --- a/src/core/server/saved_objects/migrations/mocks.ts +++ b/src/core/server/saved_objects/migrations/mocks.ts @@ -9,17 +9,18 @@ import { SavedObjectMigrationContext } from './types'; import { SavedObjectsMigrationLogger } from './core'; -export const createSavedObjectsMigrationLoggerMock = (): jest.Mocked => { - const mock = { - debug: jest.fn(), - info: jest.fn(), - warning: jest.fn(), - warn: jest.fn(), - error: jest.fn(), - }; +export const createSavedObjectsMigrationLoggerMock = + (): jest.Mocked => { + const mock = { + debug: jest.fn(), + info: jest.fn(), + warning: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + }; - return mock; -}; + return mock; + }; const createContextMock = ({ migrationVersion = '8.0.0', diff --git a/src/core/server/saved_objects/migrationsv2/actions/bulk_overwrite_transformed_documents.ts b/src/core/server/saved_objects/migrationsv2/actions/bulk_overwrite_transformed_documents.ts index 82f642b92805..9353ede9be6a 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/bulk_overwrite_transformed_documents.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/bulk_overwrite_transformed_documents.ts @@ -56,68 +56,70 @@ export interface BulkOverwriteTransformedDocumentsParams { * Write the up-to-date transformed documents to the index, overwriting any * documents that are still on their outdated version. */ -export const bulkOverwriteTransformedDocuments = ({ - client, - index, - transformedDocs, - refresh = false, -}: BulkOverwriteTransformedDocumentsParams): TaskEither.TaskEither< - | RetryableEsClientError - | TargetIndexHadWriteBlock - | IndexNotFound - | RequestEntityTooLargeException, - 'bulk_index_succeeded' -> => () => { - const body = transformedDocs.flatMap((doc) => { - return createBulkOperationBody(doc, index); - }); +export const bulkOverwriteTransformedDocuments = + ({ + client, + index, + transformedDocs, + refresh = false, + }: BulkOverwriteTransformedDocumentsParams): TaskEither.TaskEither< + | RetryableEsClientError + | TargetIndexHadWriteBlock + | IndexNotFound + | RequestEntityTooLargeException, + 'bulk_index_succeeded' + > => + () => { + const body = transformedDocs.flatMap((doc) => { + return createBulkOperationBody(doc, index); + }); - return client - .bulk({ - // Because we only add aliases in the MARK_VERSION_INDEX_READY step we - // can't bulkIndex to an alias with require_alias=true. This means if - // users tamper during this operation (delete indices or restore a - // snapshot), we could end up auto-creating an index without the correct - // mappings. Such tampering could lead to many other problems and is - // probably unlikely so for now we'll accept this risk and wait till - // system indices puts in place a hard control. - require_alias: false, - wait_for_active_shards: WAIT_FOR_ALL_SHARDS_TO_BE_ACTIVE, - refresh, - filter_path: ['items.*.error'], - body, - }) - .then((res) => { - // Filter out version_conflict_engine_exception since these just mean - // that another instance already updated these documents - const errors = (res.body.items ?? []) - .filter((item) => item.index?.error) - .map((item) => item.index!.error!) - .filter(({ type }) => type !== 'version_conflict_engine_exception'); + return client + .bulk({ + // Because we only add aliases in the MARK_VERSION_INDEX_READY step we + // can't bulkIndex to an alias with require_alias=true. This means if + // users tamper during this operation (delete indices or restore a + // snapshot), we could end up auto-creating an index without the correct + // mappings. Such tampering could lead to many other problems and is + // probably unlikely so for now we'll accept this risk and wait till + // system indices puts in place a hard control. + require_alias: false, + wait_for_active_shards: WAIT_FOR_ALL_SHARDS_TO_BE_ACTIVE, + refresh, + filter_path: ['items.*.error'], + body, + }) + .then((res) => { + // Filter out version_conflict_engine_exception since these just mean + // that another instance already updated these documents + const errors = (res.body.items ?? []) + .filter((item) => item.index?.error) + .map((item) => item.index!.error!) + .filter(({ type }) => type !== 'version_conflict_engine_exception'); - if (errors.length === 0) { - return Either.right('bulk_index_succeeded' as const); - } else { - if (errors.every(isWriteBlockException)) { - return Either.left({ - type: 'target_index_had_write_block' as const, - }); + if (errors.length === 0) { + return Either.right('bulk_index_succeeded' as const); + } else { + if (errors.every(isWriteBlockException)) { + return Either.left({ + type: 'target_index_had_write_block' as const, + }); + } + if (errors.every(isIndexNotFoundException)) { + return Either.left({ + type: 'index_not_found_exception' as const, + index, + }); + } + throw new Error(JSON.stringify(errors)); } - if (errors.every(isIndexNotFoundException)) { - return Either.left({ - type: 'index_not_found_exception' as const, - index, - }); + }) + .catch((error) => { + if (error instanceof esErrors.ResponseError && error.statusCode === 413) { + return Either.left({ type: 'request_entity_too_large_exception' as const }); + } else { + throw error; } - throw new Error(JSON.stringify(errors)); - } - }) - .catch((error) => { - if (error instanceof esErrors.ResponseError && error.statusCode === 413) { - return Either.left({ type: 'request_entity_too_large_exception' as const }); - } else { - throw error; - } - }) - .catch(catchRetryableEsClientErrors); -}; + }) + .catch(catchRetryableEsClientErrors); + }; diff --git a/src/core/server/saved_objects/migrationsv2/actions/calculate_exclude_filters.ts b/src/core/server/saved_objects/migrationsv2/actions/calculate_exclude_filters.ts index 9d57db079e33..9ba098d01870 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/calculate_exclude_filters.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/calculate_exclude_filters.ts @@ -28,80 +28,82 @@ export interface CalculatedExcludeFilter { errorsByType: Record; } -export const calculateExcludeFilters = ({ - client, - excludeFromUpgradeFilterHooks, - hookTimeoutMs = 30_000, // default to 30s, exposed for testing -}: CalculateExcludeFiltersParams): TaskEither.TaskEither< - RetryableEsClientError, - CalculatedExcludeFilter -> => () => { - return Promise.all< - | Either.Right - | Either.Left<{ soType: string; error: Error | RetryableEsClientError }> - >( - Object.entries(excludeFromUpgradeFilterHooks).map(([soType, hook]) => - withTimeout({ - promise: Promise.resolve( - hook({ readonlyEsClient: { search: client.search.bind(client) } }) - ), - timeoutMs: hookTimeoutMs, - }) - .then((result) => - result.timedout - ? Either.left({ +export const calculateExcludeFilters = + ({ + client, + excludeFromUpgradeFilterHooks, + hookTimeoutMs = 30_000, // default to 30s, exposed for testing + }: CalculateExcludeFiltersParams): TaskEither.TaskEither< + RetryableEsClientError, + CalculatedExcludeFilter + > => + () => { + return Promise.all< + | Either.Right + | Either.Left<{ soType: string; error: Error | RetryableEsClientError }> + >( + Object.entries(excludeFromUpgradeFilterHooks).map(([soType, hook]) => + withTimeout({ + promise: Promise.resolve( + hook({ readonlyEsClient: { search: client.search.bind(client) } }) + ), + timeoutMs: hookTimeoutMs, + }) + .then((result) => + result.timedout + ? Either.left({ + soType, + error: new Error( + `excludeFromUpgrade hook timed out after ${hookTimeoutMs / 1000} seconds.` + ), + }) + : Either.right(result.value) + ) + .catch((error) => { + const retryableError = catchRetryableEsClientErrors(error); + if (Either.isLeft(retryableError)) { + return Either.left({ soType, error: retryableError.left }); + } else { + // Really should never happen, only here to satisfy TypeScript + return Either.left({ soType, error: new Error( - `excludeFromUpgrade hook timed out after ${hookTimeoutMs / 1000} seconds.` + `Unexpected return value from catchRetryableEsClientErrors: "${retryableError.toString()}"` ), - }) - : Either.right(result.value) - ) - .catch((error) => { - const retryableError = catchRetryableEsClientErrors(error); - if (Either.isLeft(retryableError)) { - return Either.left({ soType, error: retryableError.left }); - } else { - // Really should never happen, only here to satisfy TypeScript - return Either.left({ - soType, - error: new Error( - `Unexpected return value from catchRetryableEsClientErrors: "${retryableError.toString()}"` - ), - }); - } - }) - .catch((error: Error) => Either.left({ soType, error })) - ) - ).then((results) => { - const retryableError = results.find( - (r) => - Either.isLeft(r) && - !(r.left.error instanceof Error) && - r.left.error.type === 'retryable_es_client_error' - ) as Either.Left<{ soType: string; error: RetryableEsClientError }> | undefined; - if (retryableError) { - return Either.left(retryableError.left.error); - } + }); + } + }) + .catch((error: Error) => Either.left({ soType, error })) + ) + ).then((results) => { + const retryableError = results.find( + (r) => + Either.isLeft(r) && + !(r.left.error instanceof Error) && + r.left.error.type === 'retryable_es_client_error' + ) as Either.Left<{ soType: string; error: RetryableEsClientError }> | undefined; + if (retryableError) { + return Either.left(retryableError.left.error); + } - const errorsByType: Array<[string, Error]> = []; - const filters: estypes.QueryDslQueryContainer[] = []; + const errorsByType: Array<[string, Error]> = []; + const filters: estypes.QueryDslQueryContainer[] = []; - // Loop through all results and collect successes and errors - results.forEach((r) => - Either.isRight(r) - ? filters.push(r.right) - : Either.isLeft(r) && errorsByType.push([r.left.soType, r.left.error as Error]) - ); + // Loop through all results and collect successes and errors + results.forEach((r) => + Either.isRight(r) + ? filters.push(r.right) + : Either.isLeft(r) && errorsByType.push([r.left.soType, r.left.error as Error]) + ); - // Composite filter from all calculated filters that successfully executed - const excludeFilter: estypes.QueryDslQueryContainer = { - bool: { must_not: filters }, - }; + // Composite filter from all calculated filters that successfully executed + const excludeFilter: estypes.QueryDslQueryContainer = { + bool: { must_not: filters }, + }; - return Either.right({ - excludeFilter, - errorsByType: Object.fromEntries(errorsByType), + return Either.right({ + excludeFilter, + errorsByType: Object.fromEntries(errorsByType), + }); }); - }); -}; + }; diff --git a/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.ts b/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.ts index e3d72fbdf866..1db47f008346 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.ts @@ -35,32 +35,31 @@ export interface UnknownDocsFound { unknownDocs: CheckForUnknownDocsFoundDoc[]; } -export const checkForUnknownDocs = ({ - client, - indexName, - unusedTypesQuery, - knownTypes, -}: CheckForUnknownDocsParams): TaskEither.TaskEither< - RetryableEsClientError, - UnknownDocsFound -> => () => { - const query = createUnknownDocQuery(unusedTypesQuery, knownTypes); +export const checkForUnknownDocs = + ({ + client, + indexName, + unusedTypesQuery, + knownTypes, + }: CheckForUnknownDocsParams): TaskEither.TaskEither => + () => { + const query = createUnknownDocQuery(unusedTypesQuery, knownTypes); - return client - .search({ - index: indexName, - body: { - query, - }, - }) - .then((response) => { - const { hits } = response.body.hits; - return Either.right({ - unknownDocs: hits.map((hit) => ({ id: hit._id, type: hit._source?.type ?? 'unknown' })), - }); - }) - .catch(catchRetryableEsClientErrors); -}; + return client + .search({ + index: indexName, + body: { + query, + }, + }) + .then((response) => { + const { hits } = response.body.hits; + return Either.right({ + unknownDocs: hits.map((hit) => ({ id: hit._id, type: hit._source?.type ?? 'unknown' })), + }); + }) + .catch(catchRetryableEsClientErrors); + }; const createUnknownDocQuery = ( unusedTypesQuery: estypes.QueryDslQueryContainer, diff --git a/src/core/server/saved_objects/migrationsv2/actions/close_pit.ts b/src/core/server/saved_objects/migrationsv2/actions/close_pit.ts index d421950c839e..9dd7f1d22386 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/close_pit.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/close_pit.ts @@ -23,19 +23,18 @@ export interface ClosePitParams { * Closes PIT. * See https://www.elastic.co/guide/en/elasticsearch/reference/current/point-in-time-api.html * */ -export const closePit = ({ - client, - pitId, -}: ClosePitParams): TaskEither.TaskEither => () => { - return client - .closePointInTime({ - body: { id: pitId }, - }) - .then((response) => { - if (!response.body.succeeded) { - throw new Error(`Failed to close PointInTime with id: ${pitId}`); - } - return Either.right({}); - }) - .catch(catchRetryableEsClientErrors); -}; +export const closePit = + ({ client, pitId }: ClosePitParams): TaskEither.TaskEither => + () => { + return client + .closePointInTime({ + body: { id: pitId }, + }) + .then((response) => { + if (!response.body.succeeded) { + throw new Error(`Failed to close PointInTime with id: ${pitId}`); + } + return Either.right({}); + }) + .catch(catchRetryableEsClientErrors); + }; diff --git a/src/core/server/saved_objects/migrationsv2/actions/create_index.ts b/src/core/server/saved_objects/migrationsv2/actions/create_index.ts index 8e5042a5ff8f..d5269233344c 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/create_index.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/create_index.ts @@ -55,74 +55,72 @@ export const createIndex = ({ mappings, aliases = [], }: CreateIndexParams): TaskEither.TaskEither => { - const createIndexTask: TaskEither.TaskEither< - RetryableEsClientError, - AcknowledgeResponse - > = () => { - const aliasesObject = aliasArrayToRecord(aliases); + const createIndexTask: TaskEither.TaskEither = + () => { + const aliasesObject = aliasArrayToRecord(aliases); - return client.indices - .create( - { - index: indexName, - // wait until all shards are available before creating the index - // (since number_of_shards=1 this does not have any effect atm) - wait_for_active_shards: WAIT_FOR_ALL_SHARDS_TO_BE_ACTIVE, - // Wait up to 60s for the cluster state to update and all shards to be - // started - timeout: DEFAULT_TIMEOUT, - body: { - mappings, - aliases: aliasesObject, - settings: { - index: { - // ES rule of thumb: shards should be several GB to 10's of GB, so - // Kibana is unlikely to cross that limit. - number_of_shards: 1, - auto_expand_replicas: INDEX_AUTO_EXPAND_REPLICAS, - // Set an explicit refresh interval so that we don't inherit the - // value from incorrectly configured index templates (not required - // after we adopt system indices) - refresh_interval: '1s', - // Bump priority so that recovery happens before newer indices - priority: 10, + return client.indices + .create( + { + index: indexName, + // wait until all shards are available before creating the index + // (since number_of_shards=1 this does not have any effect atm) + wait_for_active_shards: WAIT_FOR_ALL_SHARDS_TO_BE_ACTIVE, + // Wait up to 60s for the cluster state to update and all shards to be + // started + timeout: DEFAULT_TIMEOUT, + body: { + mappings, + aliases: aliasesObject, + settings: { + index: { + // ES rule of thumb: shards should be several GB to 10's of GB, so + // Kibana is unlikely to cross that limit. + number_of_shards: 1, + auto_expand_replicas: INDEX_AUTO_EXPAND_REPLICAS, + // Set an explicit refresh interval so that we don't inherit the + // value from incorrectly configured index templates (not required + // after we adopt system indices) + refresh_interval: '1s', + // Bump priority so that recovery happens before newer indices + priority: 10, + }, }, }, }, - }, - { maxRetries: 0 /** handle retry ourselves for now */ } - ) - .then((res) => { - /** - * - acknowledged=false, we timed out before the cluster state was - * updated on all nodes with the newly created index, but it - * probably will be created sometime soon. - * - shards_acknowledged=false, we timed out before all shards were - * started - * - acknowledged=true, shards_acknowledged=true, index creation complete - */ - return Either.right({ - acknowledged: res.body.acknowledged, - shardsAcknowledged: res.body.shards_acknowledged, - }); - }) - .catch((error) => { - if (error?.body?.error?.type === 'resource_already_exists_exception') { + { maxRetries: 0 /** handle retry ourselves for now */ } + ) + .then((res) => { /** - * If the target index already exists it means a previous create - * operation had already been started. However, we can't be sure - * that all shards were started so return shardsAcknowledged: false + * - acknowledged=false, we timed out before the cluster state was + * updated on all nodes with the newly created index, but it + * probably will be created sometime soon. + * - shards_acknowledged=false, we timed out before all shards were + * started + * - acknowledged=true, shards_acknowledged=true, index creation complete */ return Either.right({ - acknowledged: true, - shardsAcknowledged: false, + acknowledged: res.body.acknowledged, + shardsAcknowledged: res.body.shards_acknowledged, }); - } else { - throw error; - } - }) - .catch(catchRetryableEsClientErrors); - }; + }) + .catch((error) => { + if (error?.body?.error?.type === 'resource_already_exists_exception') { + /** + * If the target index already exists it means a previous create + * operation had already been started. However, we can't be sure + * that all shards were started so return shardsAcknowledged: false + */ + return Either.right({ + acknowledged: true, + shardsAcknowledged: false, + }); + } else { + throw error; + } + }) + .catch(catchRetryableEsClientErrors); + }; return pipe( createIndexTask, diff --git a/src/core/server/saved_objects/migrationsv2/actions/fetch_indices.ts b/src/core/server/saved_objects/migrationsv2/actions/fetch_indices.ts index 3847252eb6db..1256b2d85890 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/fetch_indices.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/fetch_indices.ts @@ -28,10 +28,11 @@ export interface FetchIndicesParams { * Fetches information about the given indices including aliases, mappings and * settings. */ -export const fetchIndices = ({ - client, - indices, -}: FetchIndicesParams): TaskEither.TaskEither => +export const fetchIndices = + ({ + client, + indices, + }: FetchIndicesParams): TaskEither.TaskEither => // @ts-expect-error @elastic/elasticsearch IndexState.alias and IndexState.mappings should be required () => { return client.indices diff --git a/src/core/server/saved_objects/migrationsv2/actions/integration_tests/actions.test.ts b/src/core/server/saved_objects/migrationsv2/actions/integration_tests/actions.test.ts index 0ae6464f2623..936746ddc693 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/integration_tests/actions.test.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/integration_tests/actions.test.ts @@ -82,13 +82,13 @@ describe('migration actions', () => { properties: {}, }, })(); - const sourceDocs = ([ + const sourceDocs = [ { _source: { title: 'doc 1' } }, { _source: { title: 'doc 2' } }, { _source: { title: 'doc 3' } }, { _source: { title: 'saved object 4', type: 'another_unused_type' } }, { _source: { title: 'f-agent-event 5', type: 'f_agent_event' } }, - ] as unknown) as SavedObjectsRawDoc[]; + ] as unknown as SavedObjectsRawDoc[]; await bulkOverwriteTransformedDocuments({ client, index: 'existing_index_with_docs', @@ -182,12 +182,12 @@ describe('migration actions', () => { expect.assertions(1); const task = setWriteBlock({ client, index: 'new_index_without_write_block' }); await task(); - const sourceDocs = ([ + const sourceDocs = [ { _source: { title: 'doc 1' } }, { _source: { title: 'doc 2' } }, { _source: { title: 'doc 3' } }, { _source: { title: 'doc 4' } }, - ] as unknown) as SavedObjectsRawDoc[]; + ] as unknown as SavedObjectsRawDoc[]; const res = (await bulkOverwriteTransformedDocuments({ client, @@ -452,11 +452,13 @@ describe('migration actions', () => { } `); - const results = ((await searchForOutdatedDocuments(client, { - batchSize: 1000, - targetIndex: 'reindex_target', - outdatedDocumentsQuery: undefined, - })()) as Either.Right).right.outdatedDocuments; + const results = ( + (await searchForOutdatedDocuments(client, { + batchSize: 1000, + targetIndex: 'reindex_target', + outdatedDocumentsQuery: undefined, + })()) as Either.Right + ).right.outdatedDocuments; expect(results.map((doc) => doc._source.title).sort()).toMatchInlineSnapshot(` Array [ "doc 1", @@ -490,11 +492,13 @@ describe('migration actions', () => { } `); - const results = ((await searchForOutdatedDocuments(client, { - batchSize: 1000, - targetIndex: 'reindex_target_excluded_docs', - outdatedDocumentsQuery: undefined, - })()) as Either.Right).right.outdatedDocuments; + const results = ( + (await searchForOutdatedDocuments(client, { + batchSize: 1000, + targetIndex: 'reindex_target_excluded_docs', + outdatedDocumentsQuery: undefined, + })()) as Either.Right + ).right.outdatedDocuments; expect(results.map((doc) => doc._source.title).sort()).toMatchInlineSnapshot(` Array [ "doc 1", @@ -520,11 +524,13 @@ describe('migration actions', () => { "right": "reindex_succeeded", } `); - const results = ((await searchForOutdatedDocuments(client, { - batchSize: 1000, - targetIndex: 'reindex_target_2', - outdatedDocumentsQuery: undefined, - })()) as Either.Right).right.outdatedDocuments; + const results = ( + (await searchForOutdatedDocuments(client, { + batchSize: 1000, + targetIndex: 'reindex_target_2', + outdatedDocumentsQuery: undefined, + })()) as Either.Right + ).right.outdatedDocuments; expect(results.map((doc) => doc._source.title).sort()).toMatchInlineSnapshot(` Array [ "doc 1_updated", @@ -572,11 +578,13 @@ describe('migration actions', () => { `); // Assert that documents weren't overridden by the second, unscripted reindex - const results = ((await searchForOutdatedDocuments(client, { - batchSize: 1000, - targetIndex: 'reindex_target_3', - outdatedDocumentsQuery: undefined, - })()) as Either.Right).right.outdatedDocuments; + const results = ( + (await searchForOutdatedDocuments(client, { + batchSize: 1000, + targetIndex: 'reindex_target_3', + outdatedDocumentsQuery: undefined, + })()) as Either.Right + ).right.outdatedDocuments; expect(results.map((doc) => doc._source.title).sort()).toMatchInlineSnapshot(` Array [ "doc 1_updated", @@ -592,11 +600,13 @@ describe('migration actions', () => { // Simulate a reindex that only adds some of the documents from the // source index into the target index await createIndex({ client, indexName: 'reindex_target_4', mappings: { properties: {} } })(); - const sourceDocs = ((await searchForOutdatedDocuments(client, { - batchSize: 1000, - targetIndex: 'existing_index_with_docs', - outdatedDocumentsQuery: undefined, - })()) as Either.Right).right.outdatedDocuments + const sourceDocs = ( + (await searchForOutdatedDocuments(client, { + batchSize: 1000, + targetIndex: 'existing_index_with_docs', + outdatedDocumentsQuery: undefined, + })()) as Either.Right + ).right.outdatedDocuments .slice(0, 2) .map(({ _id, _source }) => ({ _id, @@ -627,11 +637,13 @@ describe('migration actions', () => { `); // Assert that existing documents weren't overridden, but that missing // documents were added by the reindex - const results = ((await searchForOutdatedDocuments(client, { - batchSize: 1000, - targetIndex: 'reindex_target_4', - outdatedDocumentsQuery: undefined, - })()) as Either.Right).right.outdatedDocuments; + const results = ( + (await searchForOutdatedDocuments(client, { + batchSize: 1000, + targetIndex: 'reindex_target_4', + outdatedDocumentsQuery: undefined, + })()) as Either.Right + ).right.outdatedDocuments; expect(results.map((doc) => doc._source.title).sort()).toMatchInlineSnapshot(` Array [ "doc 1", @@ -1106,8 +1118,9 @@ describe('migration actions', () => { outdatedDocuments: originalDocs, }); - const resultsWithProcessDocs = ((await transformTask()) as Either.Right) - .right.processedDocs; + const resultsWithProcessDocs = ( + (await transformTask()) as Either.Right + ).right.processedDocs; expect(resultsWithProcessDocs.length).toEqual(2); const foo2 = resultsWithProcessDocs.find((h) => h._id === 'foo:2'); expect(foo2?._source?.value).toBe(3); @@ -1130,7 +1143,8 @@ describe('migration actions', () => { // We can't do a snapshot match because the response includes an index // id which ES assigns dynamically await expect(task()).rejects.toMatchObject({ - message: /pickupUpdatedMappings task failed with the following failures:\n\[\{\"index\":\"existing_index_with_write_block\"/, + message: + /pickupUpdatedMappings task failed with the following failures:\n\[\{\"index\":\"existing_index_with_write_block\"/, }); }); it('rejects if there is an error', async () => { @@ -1202,12 +1216,12 @@ describe('migration actions', () => { properties: {}, }, })(); - const sourceDocs = ([ + const sourceDocs = [ { _source: { title: 'doc 1' } }, { _source: { title: 'doc 2' } }, { _source: { title: 'doc 3' } }, { _source: { title: 'doc 4' } }, - ] as unknown) as SavedObjectsRawDoc[]; + ] as unknown as SavedObjectsRawDoc[]; await bulkOverwriteTransformedDocuments({ client, index: 'existing_index_without_mappings', @@ -1216,13 +1230,15 @@ describe('migration actions', () => { })(); // Assert that we can't search over the unmapped fields of the document - const originalSearchResults = ((await searchForOutdatedDocuments(client, { - batchSize: 1000, - targetIndex: 'existing_index_without_mappings', - outdatedDocumentsQuery: { - match: { title: { query: 'doc' } }, - }, - })()) as Either.Right).right.outdatedDocuments; + const originalSearchResults = ( + (await searchForOutdatedDocuments(client, { + batchSize: 1000, + targetIndex: 'existing_index_without_mappings', + outdatedDocumentsQuery: { + match: { title: { query: 'doc' } }, + }, + })()) as Either.Right + ).right.outdatedDocuments; expect(originalSearchResults.length).toBe(0); // Update and pickup mappings so that the title field is searchable @@ -1240,13 +1256,15 @@ describe('migration actions', () => { await waitForPickupUpdatedMappingsTask({ client, taskId, timeout: '60s' })(); // Repeat the search expecting to be able to find the existing documents - const pickedUpSearchResults = ((await searchForOutdatedDocuments(client, { - batchSize: 1000, - targetIndex: 'existing_index_without_mappings', - outdatedDocumentsQuery: { - match: { title: { query: 'doc' } }, - }, - })()) as Either.Right).right.outdatedDocuments; + const pickedUpSearchResults = ( + (await searchForOutdatedDocuments(client, { + batchSize: 1000, + targetIndex: 'existing_index_without_mappings', + outdatedDocumentsQuery: { + match: { title: { query: 'doc' } }, + }, + })()) as Either.Right + ).right.outdatedDocuments; expect(pickedUpSearchResults.length).toBe(4); }); }); @@ -1461,11 +1479,11 @@ describe('migration actions', () => { describe('bulkOverwriteTransformedDocuments', () => { it('resolves right when documents do not yet exist in the index', async () => { - const newDocs = ([ + const newDocs = [ { _source: { title: 'doc 5' } }, { _source: { title: 'doc 6' } }, { _source: { title: 'doc 7' } }, - ] as unknown) as SavedObjectsRawDoc[]; + ] as unknown as SavedObjectsRawDoc[]; const task = bulkOverwriteTransformedDocuments({ client, index: 'existing_index_with_docs', @@ -1481,18 +1499,20 @@ describe('migration actions', () => { `); }); it('resolves right even if there were some version_conflict_engine_exception', async () => { - const existingDocs = ((await searchForOutdatedDocuments(client, { - batchSize: 1000, - targetIndex: 'existing_index_with_docs', - outdatedDocumentsQuery: undefined, - })()) as Either.Right).right.outdatedDocuments; + const existingDocs = ( + (await searchForOutdatedDocuments(client, { + batchSize: 1000, + targetIndex: 'existing_index_with_docs', + outdatedDocumentsQuery: undefined, + })()) as Either.Right + ).right.outdatedDocuments; const task = bulkOverwriteTransformedDocuments({ client, index: 'existing_index_with_docs', transformedDocs: [ ...existingDocs, - ({ _source: { title: 'doc 8' } } as unknown) as SavedObjectsRawDoc, + { _source: { title: 'doc 8' } } as unknown as SavedObjectsRawDoc, ], refresh: 'wait_for', }); @@ -1504,11 +1524,11 @@ describe('migration actions', () => { `); }); it('resolves left target_index_had_write_block if there are write_block errors', async () => { - const newDocs = ([ + const newDocs = [ { _source: { title: 'doc 5' } }, { _source: { title: 'doc 6' } }, { _source: { title: 'doc 7' } }, - ] as unknown) as SavedObjectsRawDoc[]; + ] as unknown as SavedObjectsRawDoc[]; await expect( bulkOverwriteTransformedDocuments({ client, diff --git a/src/core/server/saved_objects/migrationsv2/actions/open_pit.ts b/src/core/server/saved_objects/migrationsv2/actions/open_pit.ts index e740dc00ac27..43c84a2b2661 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/open_pit.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/open_pit.ts @@ -29,15 +29,17 @@ export const pitKeepAlive = '10m'; * Creates a lightweight view of data when the request has been initiated. * See https://www.elastic.co/guide/en/elasticsearch/reference/current/point-in-time-api.html * */ -export const openPit = ({ - client, - index, -}: OpenPitParams): TaskEither.TaskEither => () => { - return client - .openPointInTime({ - index, - keep_alive: pitKeepAlive, - }) - .then((response) => Either.right({ pitId: response.body.id })) - .catch(catchRetryableEsClientErrors); -}; +export const openPit = + ({ + client, + index, + }: OpenPitParams): TaskEither.TaskEither => + () => { + return client + .openPointInTime({ + index, + keep_alive: pitKeepAlive, + }) + .then((response) => Either.right({ pitId: response.body.id })) + .catch(catchRetryableEsClientErrors); + }; diff --git a/src/core/server/saved_objects/migrationsv2/actions/pickup_updated_mappings.ts b/src/core/server/saved_objects/migrationsv2/actions/pickup_updated_mappings.ts index 8cc609e5277b..2db6b1833c6d 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/pickup_updated_mappings.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/pickup_updated_mappings.ts @@ -31,27 +31,29 @@ export interface UpdateByQueryResponse { * This action uses `conflicts: 'proceed'` allowing several Kibana instances * to run this in parallel. */ -export const pickupUpdatedMappings = ( - client: ElasticsearchClient, - index: string -): TaskEither.TaskEither => () => { - return client - .updateByQuery({ - // Ignore version conflicts that can occur from parallel update by query operations - conflicts: 'proceed', - // Return an error when targeting missing or closed indices - allow_no_indices: false, - index, - // How many documents to update per batch - scroll_size: BATCH_SIZE, - // force a refresh so that we can query the updated index immediately - // after the operation completes - refresh: true, - // Create a task and return task id instead of blocking until complete - wait_for_completion: false, - }) - .then(({ body: { task: taskId } }) => { - return Either.right({ taskId: String(taskId!) }); - }) - .catch(catchRetryableEsClientErrors); -}; +export const pickupUpdatedMappings = + ( + client: ElasticsearchClient, + index: string + ): TaskEither.TaskEither => + () => { + return client + .updateByQuery({ + // Ignore version conflicts that can occur from parallel update by query operations + conflicts: 'proceed', + // Return an error when targeting missing or closed indices + allow_no_indices: false, + index, + // How many documents to update per batch + scroll_size: BATCH_SIZE, + // force a refresh so that we can query the updated index immediately + // after the operation completes + refresh: true, + // Create a task and return task id instead of blocking until complete + wait_for_completion: false, + }) + .then(({ body: { task: taskId } }) => { + return Either.right({ taskId: String(taskId!) }); + }) + .catch(catchRetryableEsClientErrors); + }; diff --git a/src/core/server/saved_objects/migrationsv2/actions/read_with_pit.ts b/src/core/server/saved_objects/migrationsv2/actions/read_with_pit.ts index b101e7db0141..c8e7d61dce81 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/read_with_pit.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/read_with_pit.ts @@ -37,56 +37,58 @@ export interface ReadWithPitParams { /* * Requests documents from the index using PIT mechanism. * */ -export const readWithPit = ({ - client, - pitId, - query, - batchSize, - searchAfter, - seqNoPrimaryTerm, -}: ReadWithPitParams): TaskEither.TaskEither => () => { - return client - .search({ - seq_no_primary_term: seqNoPrimaryTerm, - body: { - // Sort fields are required to use searchAfter - sort: { - // the most efficient option as order is not important for the migration - _shard_doc: { order: 'asc' }, +export const readWithPit = + ({ + client, + pitId, + query, + batchSize, + searchAfter, + seqNoPrimaryTerm, + }: ReadWithPitParams): TaskEither.TaskEither => + () => { + return client + .search({ + seq_no_primary_term: seqNoPrimaryTerm, + body: { + // Sort fields are required to use searchAfter + sort: { + // the most efficient option as order is not important for the migration + _shard_doc: { order: 'asc' }, + }, + pit: { id: pitId, keep_alive: pitKeepAlive }, + size: batchSize, + search_after: searchAfter, + /** + * We want to know how many documents we need to process so we can log the progress. + * But we also want to increase the performance of these requests, + * so we ask ES to report the total count only on the first request (when searchAfter does not exist) + */ + track_total_hits: typeof searchAfter === 'undefined', + query, }, - pit: { id: pitId, keep_alive: pitKeepAlive }, - size: batchSize, - search_after: searchAfter, - /** - * We want to know how many documents we need to process so we can log the progress. - * But we also want to increase the performance of these requests, - * so we ask ES to report the total count only on the first request (when searchAfter does not exist) - */ - track_total_hits: typeof searchAfter === 'undefined', - query, - }, - }) - .then((response) => { - const totalHits = - typeof response.body.hits.total === 'number' - ? response.body.hits.total // This format is to be removed in 8.0 - : response.body.hits.total?.value; - const hits = response.body.hits.hits; + }) + .then((response) => { + const totalHits = + typeof response.body.hits.total === 'number' + ? response.body.hits.total // This format is to be removed in 8.0 + : response.body.hits.total?.value; + const hits = response.body.hits.hits; + + if (hits.length > 0) { + return Either.right({ + // @ts-expect-error @elastic/elasticsearch _source is optional + outdatedDocuments: hits as SavedObjectsRawDoc[], + lastHitSortValue: hits[hits.length - 1].sort as number[], + totalHits, + }); + } - if (hits.length > 0) { return Either.right({ - // @ts-expect-error @elastic/elasticsearch _source is optional - outdatedDocuments: hits as SavedObjectsRawDoc[], - lastHitSortValue: hits[hits.length - 1].sort as number[], + outdatedDocuments: [], + lastHitSortValue: undefined, totalHits, }); - } - - return Either.right({ - outdatedDocuments: [], - lastHitSortValue: undefined, - totalHits, - }); - }) - .catch(catchRetryableEsClientErrors); -}; + }) + .catch(catchRetryableEsClientErrors); + }; diff --git a/src/core/server/saved_objects/migrationsv2/actions/refresh_index.ts b/src/core/server/saved_objects/migrationsv2/actions/refresh_index.ts index e7bcbfb7d2d5..371247789af2 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/refresh_index.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/refresh_index.ts @@ -22,19 +22,18 @@ export interface RefreshIndexParams { /** * Wait for Elasticsearch to reindex all the changes. */ -export const refreshIndex = ({ - client, - targetIndex, -}: RefreshIndexParams): TaskEither.TaskEither< - RetryableEsClientError, - { refreshed: boolean } -> => () => { - return client.indices - .refresh({ - index: targetIndex, - }) - .then(() => { - return Either.right({ refreshed: true }); - }) - .catch(catchRetryableEsClientErrors); -}; +export const refreshIndex = + ({ + client, + targetIndex, + }: RefreshIndexParams): TaskEither.TaskEither => + () => { + return client.indices + .refresh({ + index: targetIndex, + }) + .then(() => { + return Either.right({ refreshed: true }); + }) + .catch(catchRetryableEsClientErrors); + }; diff --git a/src/core/server/saved_objects/migrationsv2/actions/reindex.ts b/src/core/server/saved_objects/migrationsv2/actions/reindex.ts index e9cfb4b61dac..92134d2755ac 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/reindex.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/reindex.ts @@ -42,49 +42,51 @@ export interface ReindexParams { * this in parallel. By using `op_type: 'create', conflicts: 'proceed'` there * will be only one write per reindexed document. */ -export const reindex = ({ - client, - sourceIndex, - targetIndex, - reindexScript, - requireAlias, - unusedTypesQuery, -}: ReindexParams): TaskEither.TaskEither => () => { - return client - .reindex({ - // Require targetIndex to be an alias. Prevents a new index from being - // created if targetIndex doesn't exist. - require_alias: requireAlias, - body: { - // Ignore version conflicts from existing documents - conflicts: 'proceed', - source: { - index: sourceIndex, - // Set reindex batch size - size: BATCH_SIZE, - // Exclude saved object types - query: unusedTypesQuery, +export const reindex = + ({ + client, + sourceIndex, + targetIndex, + reindexScript, + requireAlias, + unusedTypesQuery, + }: ReindexParams): TaskEither.TaskEither => + () => { + return client + .reindex({ + // Require targetIndex to be an alias. Prevents a new index from being + // created if targetIndex doesn't exist. + require_alias: requireAlias, + body: { + // Ignore version conflicts from existing documents + conflicts: 'proceed', + source: { + index: sourceIndex, + // Set reindex batch size + size: BATCH_SIZE, + // Exclude saved object types + query: unusedTypesQuery, + }, + dest: { + index: targetIndex, + // Don't override existing documents, only create if missing + op_type: 'create', + }, + script: Option.fold( + () => undefined, + (script) => ({ + source: script, + lang: 'painless', + }) + )(reindexScript), }, - dest: { - index: targetIndex, - // Don't override existing documents, only create if missing - op_type: 'create', - }, - script: Option.fold( - () => undefined, - (script) => ({ - source: script, - lang: 'painless', - }) - )(reindexScript), - }, - // force a refresh so that we can query the target index - refresh: true, - // Create a task and return task id instead of blocking until complete - wait_for_completion: false, - }) - .then(({ body: { task: taskId } }) => { - return Either.right({ taskId: String(taskId) }); - }) - .catch(catchRetryableEsClientErrors); -}; + // force a refresh so that we can query the target index + refresh: true, + // Create a task and return task id instead of blocking until complete + wait_for_completion: false, + }) + .then(({ body: { task: taskId } }) => { + return Either.right({ taskId: String(taskId) }); + }) + .catch(catchRetryableEsClientErrors); + }; diff --git a/src/core/server/saved_objects/migrationsv2/actions/remove_write_block.ts b/src/core/server/saved_objects/migrationsv2/actions/remove_write_block.ts index b5bf64d5c29f..77445654d3cc 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/remove_write_block.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/remove_write_block.ts @@ -22,39 +22,41 @@ export interface RemoveWriteBlockParams { /** * Removes a write block from an index */ -export const removeWriteBlock = ({ - client, - index, -}: RemoveWriteBlockParams): TaskEither.TaskEither< - RetryableEsClientError, - 'remove_write_block_succeeded' -> => () => { - return client.indices - .putSettings<{ - acknowledged: boolean; - shards_acknowledged: boolean; - }>( - { - index, - // Don't change any existing settings - preserve_existing: true, - body: { - settings: { - blocks: { - write: false, +export const removeWriteBlock = + ({ + client, + index, + }: RemoveWriteBlockParams): TaskEither.TaskEither< + RetryableEsClientError, + 'remove_write_block_succeeded' + > => + () => { + return client.indices + .putSettings<{ + acknowledged: boolean; + shards_acknowledged: boolean; + }>( + { + index, + // Don't change any existing settings + preserve_existing: true, + body: { + settings: { + blocks: { + write: false, + }, }, }, }, - }, - { maxRetries: 0 /** handle retry ourselves for now */ } - ) - .then((res) => { - return res.body.acknowledged === true - ? Either.right('remove_write_block_succeeded' as const) - : Either.left({ - type: 'retryable_es_client_error' as const, - message: 'remove_write_block_failed', - }); - }) - .catch(catchRetryableEsClientErrors); -}; + { maxRetries: 0 /** handle retry ourselves for now */ } + ) + .then((res) => { + return res.body.acknowledged === true + ? Either.right('remove_write_block_succeeded' as const) + : Either.left({ + type: 'retryable_es_client_error' as const, + message: 'remove_write_block_failed', + }); + }) + .catch(catchRetryableEsClientErrors); + }; diff --git a/src/core/server/saved_objects/migrationsv2/actions/search_for_outdated_documents.ts b/src/core/server/saved_objects/migrationsv2/actions/search_for_outdated_documents.ts index c27170a78245..5a6cb3a3d048 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/search_for_outdated_documents.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/search_for_outdated_documents.ts @@ -34,44 +34,46 @@ export interface SearchForOutdatedDocumentsOptions { * * Used for testing only */ -export const searchForOutdatedDocuments = ( - client: ElasticsearchClient, - options: SearchForOutdatedDocumentsOptions -): TaskEither.TaskEither => () => { - return client - .search({ - index: options.targetIndex, - // Return the _seq_no and _primary_term so we can use optimistic - // concurrency control for updates - seq_no_primary_term: true, - size: options.batchSize, - body: { - query: options.outdatedDocumentsQuery, - // Optimize search performance by sorting by the "natural" index order - sort: ['_doc'], - }, - // Return an error when targeting missing or closed indices - allow_no_indices: false, - // Don't return partial results if timeouts or shard failures are - // encountered. This is important because 0 search hits is interpreted as - // there being no more outdated documents left that require - // transformation. Although the default is `false`, we set this - // explicitly to avoid users overriding the - // search.default_allow_partial_results cluster setting to true. - allow_partial_search_results: false, - // Improve performance by not calculating the total number of hits - // matching the query. - track_total_hits: false, - // Reduce the response payload size by only returning the data we care about - filter_path: [ - 'hits.hits._id', - 'hits.hits._source', - 'hits.hits._seq_no', - 'hits.hits._primary_term', - ], - }) - .then((res) => - Either.right({ outdatedDocuments: (res.body.hits?.hits as SavedObjectsRawDoc[]) ?? [] }) - ) - .catch(catchRetryableEsClientErrors); -}; +export const searchForOutdatedDocuments = + ( + client: ElasticsearchClient, + options: SearchForOutdatedDocumentsOptions + ): TaskEither.TaskEither => + () => { + return client + .search({ + index: options.targetIndex, + // Return the _seq_no and _primary_term so we can use optimistic + // concurrency control for updates + seq_no_primary_term: true, + size: options.batchSize, + body: { + query: options.outdatedDocumentsQuery, + // Optimize search performance by sorting by the "natural" index order + sort: ['_doc'], + }, + // Return an error when targeting missing or closed indices + allow_no_indices: false, + // Don't return partial results if timeouts or shard failures are + // encountered. This is important because 0 search hits is interpreted as + // there being no more outdated documents left that require + // transformation. Although the default is `false`, we set this + // explicitly to avoid users overriding the + // search.default_allow_partial_results cluster setting to true. + allow_partial_search_results: false, + // Improve performance by not calculating the total number of hits + // matching the query. + track_total_hits: false, + // Reduce the response payload size by only returning the data we care about + filter_path: [ + 'hits.hits._id', + 'hits.hits._source', + 'hits.hits._seq_no', + 'hits.hits._primary_term', + ], + }) + .then((res) => + Either.right({ outdatedDocuments: (res.body.hits?.hits as SavedObjectsRawDoc[]) ?? [] }) + ) + .catch(catchRetryableEsClientErrors); + }; diff --git a/src/core/server/saved_objects/migrationsv2/actions/set_write_block.ts b/src/core/server/saved_objects/migrationsv2/actions/set_write_block.ts index 5aed316306cf..db519d024651 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/set_write_block.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/set_write_block.ts @@ -31,43 +31,45 @@ export interface SetWriteBlockParams { * include `shards_acknowledged: true` but once the block is in place, * subsequent calls return `shards_acknowledged: false` */ -export const setWriteBlock = ({ - client, - index, -}: SetWriteBlockParams): TaskEither.TaskEither< - IndexNotFound | RetryableEsClientError, - 'set_write_block_succeeded' -> => () => { - return ( - client.indices - .addBlock<{ - acknowledged: boolean; - shards_acknowledged: boolean; - }>( - { - index, - block: 'write', - }, - { maxRetries: 0 /** handle retry ourselves for now */ } - ) - // not typed yet - .then((res: any) => { - return res.body.acknowledged === true - ? Either.right('set_write_block_succeeded' as const) - : Either.left({ - type: 'retryable_es_client_error' as const, - message: 'set_write_block_failed', - }); - }) - .catch((e: ElasticsearchClientError) => { - if (e instanceof EsErrors.ResponseError) { - if (e.body?.error?.type === 'index_not_found_exception') { - return Either.left({ type: 'index_not_found_exception' as const, index }); +export const setWriteBlock = + ({ + client, + index, + }: SetWriteBlockParams): TaskEither.TaskEither< + IndexNotFound | RetryableEsClientError, + 'set_write_block_succeeded' + > => + () => { + return ( + client.indices + .addBlock<{ + acknowledged: boolean; + shards_acknowledged: boolean; + }>( + { + index, + block: 'write', + }, + { maxRetries: 0 /** handle retry ourselves for now */ } + ) + // not typed yet + .then((res: any) => { + return res.body.acknowledged === true + ? Either.right('set_write_block_succeeded' as const) + : Either.left({ + type: 'retryable_es_client_error' as const, + message: 'set_write_block_failed', + }); + }) + .catch((e: ElasticsearchClientError) => { + if (e instanceof EsErrors.ResponseError) { + if (e.body?.error?.type === 'index_not_found_exception') { + return Either.left({ type: 'index_not_found_exception' as const, index }); + } } - } - throw e; - }) - .catch(catchRetryableEsClientErrors) - ); -}; + throw e; + }) + .catch(catchRetryableEsClientErrors) + ); + }; // diff --git a/src/core/server/saved_objects/migrationsv2/actions/update_aliases.ts b/src/core/server/saved_objects/migrationsv2/actions/update_aliases.ts index ffb8002f0921..5f1903f010a4 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/update_aliases.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/update_aliases.ts @@ -39,60 +39,62 @@ export interface UpdateAliasesParams { /** * Calls the Update index alias API `_alias` with the provided alias actions. */ -export const updateAliases = ({ - client, - aliasActions, -}: UpdateAliasesParams): TaskEither.TaskEither< - IndexNotFound | AliasNotFound | RemoveIndexNotAConcreteIndex | RetryableEsClientError, - 'update_aliases_succeeded' -> => () => { - return client.indices - .updateAliases( - { - body: { - actions: aliasActions, +export const updateAliases = + ({ + client, + aliasActions, + }: UpdateAliasesParams): TaskEither.TaskEither< + IndexNotFound | AliasNotFound | RemoveIndexNotAConcreteIndex | RetryableEsClientError, + 'update_aliases_succeeded' + > => + () => { + return client.indices + .updateAliases( + { + body: { + actions: aliasActions, + }, }, - }, - { maxRetries: 0 } - ) - .then(() => { - // Ignore `acknowledged: false`. When the coordinating node accepts - // the new cluster state update but not all nodes have applied the - // update within the timeout `acknowledged` will be false. However, - // retrying this update will always immediately result in `acknowledged: - // true` even if there are still nodes which are falling behind with - // cluster state updates. - // The only impact for using `updateAliases` to mark the version index - // as ready is that it could take longer for other Kibana instances to - // see that the version index is ready so they are more likely to - // perform unecessary duplicate work. - return Either.right('update_aliases_succeeded' as const); - }) - .catch((err: EsErrors.ElasticsearchClientError) => { - if (err instanceof EsErrors.ResponseError) { - if (err?.body?.error?.type === 'index_not_found_exception') { - return Either.left({ - type: 'index_not_found_exception' as const, - index: err.body.error.index, - }); - } else if ( - err?.body?.error?.type === 'illegal_argument_exception' && - err?.body?.error?.reason?.match( - /The provided expression \[.+\] matches an alias, specify the corresponding concrete indices instead./ - ) - ) { - return Either.left({ type: 'remove_index_not_a_concrete_index' as const }); - } else if ( - err?.body?.error?.type === 'aliases_not_found_exception' || - (err?.body?.error?.type === 'resource_not_found_exception' && - err?.body?.error?.reason?.match(/required alias \[.+\] does not exist/)) - ) { - return Either.left({ - type: 'alias_not_found_exception' as const, - }); + { maxRetries: 0 } + ) + .then(() => { + // Ignore `acknowledged: false`. When the coordinating node accepts + // the new cluster state update but not all nodes have applied the + // update within the timeout `acknowledged` will be false. However, + // retrying this update will always immediately result in `acknowledged: + // true` even if there are still nodes which are falling behind with + // cluster state updates. + // The only impact for using `updateAliases` to mark the version index + // as ready is that it could take longer for other Kibana instances to + // see that the version index is ready so they are more likely to + // perform unecessary duplicate work. + return Either.right('update_aliases_succeeded' as const); + }) + .catch((err: EsErrors.ElasticsearchClientError) => { + if (err instanceof EsErrors.ResponseError) { + if (err?.body?.error?.type === 'index_not_found_exception') { + return Either.left({ + type: 'index_not_found_exception' as const, + index: err.body.error.index, + }); + } else if ( + err?.body?.error?.type === 'illegal_argument_exception' && + err?.body?.error?.reason?.match( + /The provided expression \[.+\] matches an alias, specify the corresponding concrete indices instead./ + ) + ) { + return Either.left({ type: 'remove_index_not_a_concrete_index' as const }); + } else if ( + err?.body?.error?.type === 'aliases_not_found_exception' || + (err?.body?.error?.type === 'resource_not_found_exception' && + err?.body?.error?.reason?.match(/required alias \[.+\] does not exist/)) + ) { + return Either.left({ + type: 'alias_not_found_exception' as const, + }); + } } - } - throw err; - }) - .catch(catchRetryableEsClientErrors); -}; + throw err; + }) + .catch(catchRetryableEsClientErrors); + }; diff --git a/src/core/server/saved_objects/migrationsv2/actions/update_and_pickup_mappings.ts b/src/core/server/saved_objects/migrationsv2/actions/update_and_pickup_mappings.ts index 8c742005a01c..52065ba60cb8 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/update_and_pickup_mappings.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/update_and_pickup_mappings.ts @@ -41,35 +41,33 @@ export const updateAndPickupMappings = ({ RetryableEsClientError, UpdateAndPickupMappingsResponse > => { - const putMappingTask: TaskEither.TaskEither< - RetryableEsClientError, - 'update_mappings_succeeded' - > = () => { - return client.indices - .putMapping({ - index, - timeout: DEFAULT_TIMEOUT, - body: mappings, - }) - .then((res) => { - // Ignore `acknowledged: false`. When the coordinating node accepts - // the new cluster state update but not all nodes have applied the - // update within the timeout `acknowledged` will be false. However, - // retrying this update will always immediately result in `acknowledged: - // true` even if there are still nodes which are falling behind with - // cluster state updates. - // For updateAndPickupMappings this means that there is the potential - // that some existing document's fields won't be picked up if the node - // on which the Kibana shard is running has fallen behind with cluster - // state updates and the mapping update wasn't applied before we run - // `pickupUpdatedMappings`. ES tries to limit this risk by blocking - // index operations (including update_by_query used by - // updateAndPickupMappings) if there are pending mappings changes. But - // not all mapping changes will prevent this. - return Either.right('update_mappings_succeeded' as const); - }) - .catch(catchRetryableEsClientErrors); - }; + const putMappingTask: TaskEither.TaskEither = + () => { + return client.indices + .putMapping({ + index, + timeout: DEFAULT_TIMEOUT, + body: mappings, + }) + .then((res) => { + // Ignore `acknowledged: false`. When the coordinating node accepts + // the new cluster state update but not all nodes have applied the + // update within the timeout `acknowledged` will be false. However, + // retrying this update will always immediately result in `acknowledged: + // true` even if there are still nodes which are falling behind with + // cluster state updates. + // For updateAndPickupMappings this means that there is the potential + // that some existing document's fields won't be picked up if the node + // on which the Kibana shard is running has fallen behind with cluster + // state updates and the mapping update wasn't applied before we run + // `pickupUpdatedMappings`. ES tries to limit this risk by blocking + // index operations (including update_by_query used by + // updateAndPickupMappings) if there are pending mappings changes. But + // not all mapping changes will prevent this. + return Either.right('update_mappings_succeeded' as const); + }) + .catch(catchRetryableEsClientErrors); + }; return pipe( putMappingTask, diff --git a/src/core/server/saved_objects/migrationsv2/actions/verify_reindex.ts b/src/core/server/saved_objects/migrationsv2/actions/verify_reindex.ts index 4db599d8fbad..a344bf5a97ff 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/verify_reindex.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/verify_reindex.ts @@ -21,32 +21,34 @@ export interface VerifyReindexParams { targetIndex: string; } -export const verifyReindex = ({ - client, - sourceIndex, - targetIndex, -}: VerifyReindexParams): TaskEither.TaskEither< - RetryableEsClientError | { type: 'verify_reindex_failed' }, - 'verify_reindex_succeeded' -> => () => { - const count = (index: string) => - client - .count<{ count: number }>({ - index, - // Return an error when targeting missing or closed indices - allow_no_indices: false, - }) - .then((res) => { - return res.body.count; - }); +export const verifyReindex = + ({ + client, + sourceIndex, + targetIndex, + }: VerifyReindexParams): TaskEither.TaskEither< + RetryableEsClientError | { type: 'verify_reindex_failed' }, + 'verify_reindex_succeeded' + > => + () => { + const count = (index: string) => + client + .count<{ count: number }>({ + index, + // Return an error when targeting missing or closed indices + allow_no_indices: false, + }) + .then((res) => { + return res.body.count; + }); - return Promise.all([count(sourceIndex), count(targetIndex)]) - .then(([sourceCount, targetCount]) => { - if (targetCount >= sourceCount) { - return Either.right('verify_reindex_succeeded' as const); - } else { - return Either.left({ type: 'verify_reindex_failed' as const }); - } - }) - .catch(catchRetryableEsClientErrors); -}; + return Promise.all([count(sourceIndex), count(targetIndex)]) + .then(([sourceCount, targetCount]) => { + if (targetCount >= sourceCount) { + return Either.right('verify_reindex_succeeded' as const); + } else { + return Either.left({ type: 'verify_reindex_failed' as const }); + } + }) + .catch(catchRetryableEsClientErrors); + }; diff --git a/src/core/server/saved_objects/migrationsv2/actions/wait_for_index_status_yellow.ts b/src/core/server/saved_objects/migrationsv2/actions/wait_for_index_status_yellow.ts index 57e49b8d51cd..2880dfaff0d4 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/wait_for_index_status_yellow.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/wait_for_index_status_yellow.ts @@ -32,15 +32,17 @@ export interface WaitForIndexStatusYellowParams { * yellow at any point in the future. So ultimately data-redundancy is up to * users to maintain. */ -export const waitForIndexStatusYellow = ({ - client, - index, - timeout = DEFAULT_TIMEOUT, -}: WaitForIndexStatusYellowParams): TaskEither.TaskEither => () => { - return client.cluster - .health({ index, wait_for_status: 'yellow', timeout }) - .then(() => { - return Either.right({}); - }) - .catch(catchRetryableEsClientErrors); -}; +export const waitForIndexStatusYellow = + ({ + client, + index, + timeout = DEFAULT_TIMEOUT, + }: WaitForIndexStatusYellowParams): TaskEither.TaskEither => + () => { + return client.cluster + .health({ index, wait_for_status: 'yellow', timeout }) + .then(() => { + return Either.right({}); + }) + .catch(catchRetryableEsClientErrors); + }; diff --git a/src/core/server/saved_objects/migrationsv2/actions/wait_for_task.ts b/src/core/server/saved_objects/migrationsv2/actions/wait_for_task.ts index 0cdaa88c535a..af0ed3613bd6 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/wait_for_task.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/wait_for_task.ts @@ -65,30 +65,32 @@ export interface WaitForTaskParams { * * TODO: delete completed tasks */ -export const waitForTask = ({ - client, - taskId, - timeout, -}: WaitForTaskParams): TaskEither.TaskEither< - RetryableEsClientError | WaitForTaskCompletionTimeout, - WaitForTaskResponse -> => () => { - return client.tasks - .get({ - task_id: taskId, - wait_for_completion: true, - timeout, - }) - .then((res) => { - const body = res.body; - const failures = body.response?.failures ?? []; - return Either.right({ - completed: body.completed, - error: Option.fromNullable(body.error), - failures: failures.length > 0 ? Option.some(failures) : Option.none, - description: body.task.description, - }); - }) - .catch(catchWaitForTaskCompletionTimeout) - .catch(catchRetryableEsClientErrors); -}; +export const waitForTask = + ({ + client, + taskId, + timeout, + }: WaitForTaskParams): TaskEither.TaskEither< + RetryableEsClientError | WaitForTaskCompletionTimeout, + WaitForTaskResponse + > => + () => { + return client.tasks + .get({ + task_id: taskId, + wait_for_completion: true, + timeout, + }) + .then((res) => { + const body = res.body; + const failures = body.response?.failures ?? []; + return Either.right({ + completed: body.completed, + error: Option.fromNullable(body.error), + failures: failures.length > 0 ? Option.some(failures) : Option.none, + description: body.task.description, + }); + }) + .catch(catchWaitForTaskCompletionTimeout) + .catch(catchRetryableEsClientErrors); + }; diff --git a/src/core/server/saved_objects/migrationsv2/initial_state.test.ts b/src/core/server/saved_objects/migrationsv2/initial_state.test.ts index 26ba129cbeab..601eb7cf1ce3 100644 --- a/src/core/server/saved_objects/migrationsv2/initial_state.test.ts +++ b/src/core/server/saved_objects/migrationsv2/initial_state.test.ts @@ -19,11 +19,11 @@ describe('createInitialState', () => { typeRegistry = new SavedObjectTypeRegistry(); }); - const migrationsConfig = ({ + const migrationsConfig = { retryAttempts: 15, batchSize: 1000, maxBatchSizeBytes: ByteSizeValue.parse('100mb'), - } as unknown) as SavedObjectsMigrationConfigType; + } as unknown as SavedObjectsMigrationConfigType; it('creates the initial state for the model based on the passed in parameters', () => { expect( createInitialState({ diff --git a/src/core/server/saved_objects/migrationsv2/model/model.test.ts b/src/core/server/saved_objects/migrationsv2/model/model.test.ts index 1d017116bf3f..033a18b48884 100644 --- a/src/core/server/saved_objects/migrationsv2/model/model.test.ts +++ b/src/core/server/saved_objects/migrationsv2/model/model.test.ts @@ -556,9 +556,8 @@ describe('migrations v2 model', () => { legacyIndex: '', }; test('LEGACY_CREATE_REINDEX_TARGET -> LEGACY_REINDEX', () => { - const res: ResponseType<'LEGACY_CREATE_REINDEX_TARGET'> = Either.right( - 'create_index_succeeded' - ); + const res: ResponseType<'LEGACY_CREATE_REINDEX_TARGET'> = + Either.right('create_index_succeeded'); const newState = model(legacyCreateReindexTargetState, res); expect(newState.controlState).toEqual('LEGACY_REINDEX'); expect(newState.retryCount).toEqual(0); @@ -1143,9 +1142,8 @@ describe('migrations v2 model', () => { progress: createInitialProgress(), }; test('REINDEX_SOURCE_TO_TEMP_INDEX_BULK -> REINDEX_SOURCE_TO_TEMP_READ if action succeeded', () => { - const res: ResponseType<'REINDEX_SOURCE_TO_TEMP_INDEX_BULK'> = Either.right( - 'bulk_index_succeeded' - ); + const res: ResponseType<'REINDEX_SOURCE_TO_TEMP_INDEX_BULK'> = + Either.right('bulk_index_succeeded'); const newState = model(reindexSourceToTempIndexBulkState, res); expect(newState.controlState).toEqual('REINDEX_SOURCE_TO_TEMP_READ'); expect(newState.retryCount).toEqual(0); @@ -1563,9 +1561,8 @@ describe('migrations v2 model', () => { }; test('TRANSFORMED_DOCUMENTS_BULK_INDEX -> TRANSFORMED_DOCUMENTS_BULK_INDEX and increments currentBatch if more batches are left', () => { - const res: ResponseType<'TRANSFORMED_DOCUMENTS_BULK_INDEX'> = Either.right( - 'bulk_index_succeeded' - ); + const res: ResponseType<'TRANSFORMED_DOCUMENTS_BULK_INDEX'> = + Either.right('bulk_index_succeeded'); const newState = model( transformedDocumentsBulkIndexState, res @@ -1575,9 +1572,8 @@ describe('migrations v2 model', () => { }); test('TRANSFORMED_DOCUMENTS_BULK_INDEX -> OUTDATED_DOCUMENTS_SEARCH_READ if all batches were written', () => { - const res: ResponseType<'TRANSFORMED_DOCUMENTS_BULK_INDEX'> = Either.right( - 'bulk_index_succeeded' - ); + const res: ResponseType<'TRANSFORMED_DOCUMENTS_BULK_INDEX'> = + Either.right('bulk_index_succeeded'); const newState = model( { ...transformedDocumentsBulkIndexState, ...{ currentBatch: 1 } }, res diff --git a/src/core/server/saved_objects/routes/create.ts b/src/core/server/saved_objects/routes/create.ts index 2fa7acfb6cab..a8e54f31d51b 100644 --- a/src/core/server/saved_objects/routes/create.ts +++ b/src/core/server/saved_objects/routes/create.ts @@ -47,13 +47,8 @@ export const registerCreateRoute = (router: IRouter, { coreUsageData }: RouteDep catchAndReturnBoomErrors(async (context, req, res) => { const { type, id } = req.params; const { overwrite } = req.query; - const { - attributes, - migrationVersion, - coreMigrationVersion, - references, - initialNamespaces, - } = req.body; + const { attributes, migrationVersion, coreMigrationVersion, references, initialNamespaces } = + req.body; const usageStatsClient = coreUsageData.getClient(); usageStatsClient.incrementSavedObjectsCreate({ request: req }).catch(() => {}); diff --git a/src/core/server/saved_objects/routes/utils.test.ts b/src/core/server/saved_objects/routes/utils.test.ts index 2127352e4c60..51dd5d0918fd 100644 --- a/src/core/server/saved_objects/routes/utils.test.ts +++ b/src/core/server/saved_objects/routes/utils.test.ts @@ -174,9 +174,11 @@ describe('catchAndReturnBoomErrors', () => { let request: KibanaRequest; let response: KibanaResponseFactory; - const createHandler = (handler: () => any): RequestHandler => () => { - return handler(); - }; + const createHandler = + (handler: () => any): RequestHandler => + () => { + return handler(); + }; beforeEach(() => { context = {} as any; diff --git a/src/core/server/saved_objects/saved_objects_config.ts b/src/core/server/saved_objects/saved_objects_config.ts index e7bbd706762f..0c27f170f590 100644 --- a/src/core/server/saved_objects/saved_objects_config.ts +++ b/src/core/server/saved_objects/saved_objects_config.ts @@ -39,11 +39,12 @@ const migrationDeprecations: ConfigDeprecationProvider = () => [ }, ]; -export const savedObjectsMigrationConfig: ServiceConfigDescriptor = { - path: 'migrations', - schema: migrationSchema, - deprecations: migrationDeprecations, -}; +export const savedObjectsMigrationConfig: ServiceConfigDescriptor = + { + path: 'migrations', + schema: migrationSchema, + deprecations: migrationDeprecations, + }; const soSchema = schema.object({ maxImportPayloadBytes: schema.byteSize({ defaultValue: 26_214_400 }), diff --git a/src/core/server/saved_objects/saved_objects_service.mock.ts b/src/core/server/saved_objects/saved_objects_service.mock.ts index b26e9ff4db00..cd7310e226f6 100644 --- a/src/core/server/saved_objects/saved_objects_service.mock.ts +++ b/src/core/server/saved_objects/saved_objects_service.mock.ts @@ -49,9 +49,8 @@ const createStartContractMock = (typeRegistry?: jest.Mocked) => { - const internalStartContract: jest.Mocked = createStartContractMock( - typeRegistry - ); + const internalStartContract: jest.Mocked = + createStartContractMock(typeRegistry); return internalStartContract; }; 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 6477d1a3dfbe..1d860d2c5a69 100644 --- a/src/core/server/saved_objects/saved_objects_service.test.ts +++ b/src/core/server/saved_objects/saved_objects_service.test.ts @@ -97,7 +97,8 @@ describe('SavedObjectsService', () => { deprecationsSetup.getRegistry.mockReturnValue(mockRegistry); const deprecations = Symbol('deprecations'); - const mockedGetSavedObjectsDeprecationsProvider = getSavedObjectsDeprecationsProvider as jest.Mock; + const mockedGetSavedObjectsDeprecationsProvider = + getSavedObjectsDeprecationsProvider as jest.Mock; mockedGetSavedObjectsDeprecationsProvider.mockReturnValue(deprecations); await soService.setup(createSetupDeps()); @@ -233,8 +234,10 @@ describe('SavedObjectsService', () => { await soService.setup(setupDeps); soService.start(createStartDeps()); expect(migratorInstanceMock.runMigrations).toHaveBeenCalledTimes(0); - ((setupDeps.elasticsearch - .esNodesCompatibility$ as any) as BehaviorSubject).next({ + ( + setupDeps.elasticsearch + .esNodesCompatibility$ as any as BehaviorSubject + ).next({ isCompatible: true, incompatibleNodes: [], warningNodes: [], @@ -311,9 +314,9 @@ describe('SavedObjectsService', () => { expect(coreStart.elasticsearch.client.asScoped).toHaveBeenCalledWith(req); - const [ - [, , , , , includedHiddenTypes], - ] = (SavedObjectsRepository.createRepository as jest.Mocked).mock.calls; + const [[, , , , , includedHiddenTypes]] = ( + SavedObjectsRepository.createRepository as jest.Mocked + ).mock.calls; expect(includedHiddenTypes).toEqual([]); }); @@ -329,9 +332,9 @@ describe('SavedObjectsService', () => { const req = httpServerMock.createKibanaRequest(); createScopedRepository(req, ['someHiddenType']); - const [ - [, , , , , includedHiddenTypes], - ] = (SavedObjectsRepository.createRepository as jest.Mocked).mock.calls; + const [[, , , , , includedHiddenTypes]] = ( + SavedObjectsRepository.createRepository as jest.Mocked + ).mock.calls; expect(includedHiddenTypes).toEqual(['someHiddenType']); }); @@ -348,9 +351,9 @@ describe('SavedObjectsService', () => { createInternalRepository(); - const [ - [, , , client, , includedHiddenTypes], - ] = (SavedObjectsRepository.createRepository as jest.Mocked).mock.calls; + const [[, , , client, , includedHiddenTypes]] = ( + SavedObjectsRepository.createRepository as jest.Mocked + ).mock.calls; expect(coreStart.elasticsearch.client.asInternalUser).toBe(client); expect(includedHiddenTypes).toEqual([]); @@ -365,9 +368,9 @@ describe('SavedObjectsService', () => { createInternalRepository(['someHiddenType']); - const [ - [, , , , , includedHiddenTypes], - ] = (SavedObjectsRepository.createRepository as jest.Mocked).mock.calls; + const [[, , , , , includedHiddenTypes]] = ( + SavedObjectsRepository.createRepository as jest.Mocked + ).mock.calls; expect(includedHiddenTypes).toEqual(['someHiddenType']); }); diff --git a/src/core/server/saved_objects/saved_objects_service.ts b/src/core/server/saved_objects/saved_objects_service.ts index fd0aa238db2a..ed19b08ce187 100644 --- a/src/core/server/saved_objects/saved_objects_service.ts +++ b/src/core/server/saved_objects/saved_objects_service.ts @@ -269,7 +269,8 @@ export interface SavedObjectsStartDeps { } export class SavedObjectsService - implements CoreService { + implements CoreService +{ private logger: Logger; private setupDeps?: SavedObjectsSetupDeps; diff --git a/src/core/server/saved_objects/serialization/serializer.ts b/src/core/server/saved_objects/serialization/serializer.ts index 9c91abcfe79c..5e27b3de2440 100644 --- a/src/core/server/saved_objects/serialization/serializer.ts +++ b/src/core/server/saved_objects/serialization/serializer.ts @@ -84,14 +84,8 @@ export class SavedObjectsSerializer { const { namespaceTreatment = 'strict' } = options; const { _id, _source, _seq_no, _primary_term } = doc; - const { - type, - namespaces, - originId, - migrationVersion, - references, - coreMigrationVersion, - } = _source; + const { type, namespaces, originId, migrationVersion, references, coreMigrationVersion } = + _source; const version = _seq_no != null || _primary_term != null diff --git a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts index 046bc67f13dc..ea177caf26c9 100644 --- a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts +++ b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts @@ -31,7 +31,7 @@ const UNSUPPORTED_TYPE = 'unsupported-type'; beforeEach(() => { mockGetSavedObjectFromSource.mockReset(); mockGetSavedObjectFromSource.mockImplementation( - (_registry, _type, id) => (`mock-obj-for-${id}` as unknown) as SavedObject + (_registry, _type, id) => `mock-obj-for-${id}` as unknown as SavedObject ); mockRawDocExistsInNamespace.mockReset(); mockRawDocExistsInNamespace.mockReturnValue(true); // return true by default diff --git a/src/core/server/saved_objects/service/lib/point_in_time_finder.ts b/src/core/server/saved_objects/service/lib/point_in_time_finder.ts index d11be250ad0a..9faf5e85085e 100644 --- a/src/core/server/saved_objects/service/lib/point_in_time_finder.ts +++ b/src/core/server/saved_objects/service/lib/point_in_time_finder.ts @@ -64,7 +64,8 @@ export interface ISavedObjectsPointInTimeFinder { * @internal */ export class PointInTimeFinder - implements ISavedObjectsPointInTimeFinder { + implements ISavedObjectsPointInTimeFinder +{ readonly #log: Logger; readonly #client: PointInTimeFinderClient; readonly #findOptions: SavedObjectsFindOptions; diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts index acbc4a6ee66d..9cdc58f02f5d 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -406,11 +406,17 @@ export class SavedObjectsRepository { const bulkGetDocs = expectedResults .filter(isRight) .filter(({ value }) => value.esRequestIndex !== undefined) - .map(({ value: { object: { type, id } } }) => ({ - _id: this._serializer.generateRawId(namespace, type, id), - _index: this.getIndexForType(type), - _source: ['type', 'namespaces'], - })); + .map( + ({ + value: { + object: { type, id }, + }, + }) => ({ + _id: this._serializer.generateRawId(namespace, type, id), + _index: this.getIndexForType(type), + _source: ['type', 'namespaces'], + }) + ); const bulkGetResponse = bulkGetDocs.length ? await this.client.mget( { @@ -433,94 +439,93 @@ export class SavedObjectsRepository { } let bulkRequestIndexCounter = 0; const bulkCreateParams: object[] = []; - const expectedBulkResults: Array< - Either, Record> - > = expectedResults.map((expectedBulkGetResult) => { - if (isLeft(expectedBulkGetResult)) { - return expectedBulkGetResult; - } + const expectedBulkResults: Array, Record>> = + expectedResults.map((expectedBulkGetResult) => { + if (isLeft(expectedBulkGetResult)) { + return expectedBulkGetResult; + } - let savedObjectNamespace: string | undefined; - let savedObjectNamespaces: string[] | undefined; - let versionProperties; - const { - esRequestIndex, - object: { initialNamespaces, version, ...object }, - method, - } = expectedBulkGetResult.value; - if (esRequestIndex !== undefined) { - const indexFound = bulkGetResponse?.statusCode !== 404; - const actualResult = indexFound ? bulkGetResponse?.body.docs[esRequestIndex] : undefined; - const docFound = indexFound && actualResult?.found === true; - if ( - docFound && - !this.rawDocExistsInNamespaces( - // @ts-expect-error MultiGetHit._source is optional - actualResult!, - initialNamespaces ?? [SavedObjectsUtils.namespaceIdToString(namespace)] - ) - ) { - const { id, type } = object; - return { - tag: 'Left', - value: { - id, - type, - error: { - ...errorContent(SavedObjectsErrorHelpers.createConflictError(type, id)), - metadata: { isNotOverwritable: true }, + let savedObjectNamespace: string | undefined; + let savedObjectNamespaces: string[] | undefined; + let versionProperties; + const { + esRequestIndex, + object: { initialNamespaces, version, ...object }, + method, + } = expectedBulkGetResult.value; + if (esRequestIndex !== undefined) { + const indexFound = bulkGetResponse?.statusCode !== 404; + const actualResult = indexFound ? bulkGetResponse?.body.docs[esRequestIndex] : undefined; + const docFound = indexFound && actualResult?.found === true; + if ( + docFound && + !this.rawDocExistsInNamespaces( + // @ts-expect-error MultiGetHit._source is optional + actualResult!, + initialNamespaces ?? [SavedObjectsUtils.namespaceIdToString(namespace)] + ) + ) { + const { id, type } = object; + return { + tag: 'Left', + value: { + id, + type, + error: { + ...errorContent(SavedObjectsErrorHelpers.createConflictError(type, id)), + metadata: { isNotOverwritable: true }, + }, }, - }, - }; - } - savedObjectNamespaces = - initialNamespaces || + }; + } + savedObjectNamespaces = + initialNamespaces || + // @ts-expect-error MultiGetHit._source is optional + getSavedObjectNamespaces(namespace, docFound ? actualResult : undefined); // @ts-expect-error MultiGetHit._source is optional - getSavedObjectNamespaces(namespace, docFound ? actualResult : undefined); - // @ts-expect-error MultiGetHit._source is optional - versionProperties = getExpectedVersionProperties(version, actualResult); - } else { - if (this._registry.isSingleNamespace(object.type)) { - savedObjectNamespace = initialNamespaces - ? normalizeNamespace(initialNamespaces[0]) - : namespace; - } else if (this._registry.isMultiNamespace(object.type)) { - savedObjectNamespaces = initialNamespaces || getSavedObjectNamespaces(namespace); + versionProperties = getExpectedVersionProperties(version, actualResult); + } else { + if (this._registry.isSingleNamespace(object.type)) { + savedObjectNamespace = initialNamespaces + ? normalizeNamespace(initialNamespaces[0]) + : namespace; + } else if (this._registry.isMultiNamespace(object.type)) { + savedObjectNamespaces = initialNamespaces || getSavedObjectNamespaces(namespace); + } + versionProperties = getExpectedVersionProperties(version); } - versionProperties = getExpectedVersionProperties(version); - } - const expectedResult = { - esRequestIndex: bulkRequestIndexCounter++, - requestedId: object.id, - rawMigratedDoc: this._serializer.savedObjectToRaw( - this._migrator.migrateDocument({ - id: object.id, - type: object.type, - attributes: object.attributes, - migrationVersion: object.migrationVersion, - ...(savedObjectNamespace && { namespace: savedObjectNamespace }), - ...(savedObjectNamespaces && { namespaces: savedObjectNamespaces }), - updated_at: time, - references: object.references || [], - originId: object.originId, - }) as SavedObjectSanitizedDoc - ), - }; + const expectedResult = { + esRequestIndex: bulkRequestIndexCounter++, + requestedId: object.id, + rawMigratedDoc: this._serializer.savedObjectToRaw( + this._migrator.migrateDocument({ + id: object.id, + type: object.type, + attributes: object.attributes, + migrationVersion: object.migrationVersion, + ...(savedObjectNamespace && { namespace: savedObjectNamespace }), + ...(savedObjectNamespaces && { namespaces: savedObjectNamespaces }), + updated_at: time, + references: object.references || [], + originId: object.originId, + }) as SavedObjectSanitizedDoc + ), + }; - bulkCreateParams.push( - { - [method]: { - _id: expectedResult.rawMigratedDoc._id, - _index: this.getIndexForType(object.type), - ...(overwrite && versionProperties), + bulkCreateParams.push( + { + [method]: { + _id: expectedResult.rawMigratedDoc._id, + _index: this.getIndexForType(object.type), + ...(overwrite && versionProperties), + }, }, - }, - expectedResult.rawMigratedDoc._source - ); + expectedResult.rawMigratedDoc._source + ); - return { tag: 'Right', value: expectedResult }; - }); + return { tag: 'Right', value: expectedResult }; + }); const bulkResponse = bulkCreateParams.length ? await this.client.bulk({ @@ -570,31 +575,30 @@ export class SavedObjectsRepository { const namespace = normalizeNamespace(options.namespace); let bulkGetRequestIndexCounter = 0; - const expectedBulkGetResults: Array< - Either, Record> - > = objects.map((object) => { - const { type, id } = object; + const expectedBulkGetResults: Array, Record>> = + objects.map((object) => { + const { type, id } = object; + + if (!this._allowedTypes.includes(type)) { + return { + tag: 'Left', + value: { + id, + type, + error: errorContent(SavedObjectsErrorHelpers.createUnsupportedTypeError(type)), + }, + }; + } - if (!this._allowedTypes.includes(type)) { return { - tag: 'Left', + tag: 'Right', value: { - id, type, - error: errorContent(SavedObjectsErrorHelpers.createUnsupportedTypeError(type)), + id, + esRequestIndex: bulkGetRequestIndexCounter++, }, }; - } - - return { - tag: 'Right', - value: { - type, - id, - esRequestIndex: bulkGetRequestIndexCounter++, - }, - }; - }); + }); const bulkGetDocs = expectedBulkGetResults.filter(isRight).map(({ value: { type, id } }) => ({ _id: this._serializer.generateRawId(namespace, type, id), @@ -931,7 +935,7 @@ export class SavedObjectsRepository { } return { - ...(body.aggregations ? { aggregations: (body.aggregations as unknown) as A } : {}), + ...(body.aggregations ? { aggregations: body.aggregations as unknown as A } : {}), page, per_page: perPage, total: body.hits.total, @@ -973,40 +977,39 @@ export class SavedObjectsRepository { } let bulkGetRequestIndexCounter = 0; - const expectedBulkGetResults: Array< - Either, Record> - > = objects.map((object) => { - const { type, id, fields, namespaces } = object; - - let error: DecoratedError | undefined; - if (!this._allowedTypes.includes(type)) { - error = SavedObjectsErrorHelpers.createUnsupportedTypeError(type); - } else { - try { - this.validateObjectNamespaces(type, id, namespaces); - } catch (e) { - error = e; + const expectedBulkGetResults: Array, Record>> = + objects.map((object) => { + const { type, id, fields, namespaces } = object; + + let error: DecoratedError | undefined; + if (!this._allowedTypes.includes(type)) { + error = SavedObjectsErrorHelpers.createUnsupportedTypeError(type); + } else { + try { + this.validateObjectNamespaces(type, id, namespaces); + } catch (e) { + error = e; + } + } + + if (error) { + return { + tag: 'Left', + value: { id, type, error: errorContent(error) }, + }; } - } - if (error) { return { - tag: 'Left', - value: { id, type, error: errorContent(error) }, + tag: 'Right', + value: { + type, + id, + fields, + namespaces, + esRequestIndex: bulkGetRequestIndexCounter++, + }, }; - } - - return { - tag: 'Right', - value: { - type, - id, - fields, - namespaces, - esRequestIndex: bulkGetRequestIndexCounter++, - }, - }; - }); + }); const getNamespaceId = (namespaces?: string[]) => namespaces !== undefined ? SavedObjectsUtils.namespaceStringToId(namespaces[0]) : namespace; @@ -1053,11 +1056,11 @@ export class SavedObjectsRepository { // @ts-expect-error MultiGetHit._source is optional if (!doc?.found || !this.rawDocExistsInNamespaces(doc, namespaces)) { - return ({ + return { id, type, error: errorContent(SavedObjectsErrorHelpers.createGenericNotFoundError(type, id)), - } as any) as SavedObject; + } as any as SavedObject; } // @ts-expect-error MultiGetHit._source is optional @@ -1100,7 +1103,7 @@ export class SavedObjectsRepository { const errorResult = result as InternalBulkResolveError; const { type, id, error } = errorResult; return { - saved_object: ({ type, id, error: errorContent(error) } as unknown) as SavedObject, + saved_object: { type, id, error: errorContent(error) } as unknown as SavedObject, outcome: 'exactMatch', }; } @@ -1352,59 +1355,58 @@ export class SavedObjectsRepository { const namespace = normalizeNamespace(options.namespace); let bulkGetRequestIndexCounter = 0; - const expectedBulkGetResults: Array< - Either, Record> - > = objects.map((object) => { - const { type, id } = object; + const expectedBulkGetResults: Array, Record>> = + objects.map((object) => { + const { type, id } = object; - if (!this._allowedTypes.includes(type)) { - return { - tag: 'Left', - value: { - id, - type, - error: errorContent(SavedObjectsErrorHelpers.createGenericNotFoundError(type, id)), - }, + if (!this._allowedTypes.includes(type)) { + return { + tag: 'Left', + value: { + id, + type, + error: errorContent(SavedObjectsErrorHelpers.createGenericNotFoundError(type, id)), + }, + }; + } + + const { attributes, references, version, namespace: objectNamespace } = object; + + if (objectNamespace === ALL_NAMESPACES_STRING) { + return { + tag: 'Left', + value: { + id, + type, + error: errorContent( + SavedObjectsErrorHelpers.createBadRequestError('"namespace" cannot be "*"') + ), + }, + }; + } + // `objectNamespace` is a namespace string, while `namespace` is a namespace ID. + // The object namespace string, if defined, will supersede the operation's namespace ID. + + const documentToSave = { + [type]: attributes, + updated_at: time, + ...(Array.isArray(references) && { references }), }; - } - const { attributes, references, version, namespace: objectNamespace } = object; + const requiresNamespacesCheck = this._registry.isMultiNamespace(object.type); - if (objectNamespace === ALL_NAMESPACES_STRING) { return { - tag: 'Left', + tag: 'Right', value: { - id, type, - error: errorContent( - SavedObjectsErrorHelpers.createBadRequestError('"namespace" cannot be "*"') - ), + id, + version, + documentToSave, + objectNamespace, + ...(requiresNamespacesCheck && { esRequestIndex: bulkGetRequestIndexCounter++ }), }, }; - } - // `objectNamespace` is a namespace string, while `namespace` is a namespace ID. - // The object namespace string, if defined, will supersede the operation's namespace ID. - - const documentToSave = { - [type]: attributes, - updated_at: time, - ...(Array.isArray(references) && { references }), - }; - - const requiresNamespacesCheck = this._registry.isMultiNamespace(object.type); - - return { - tag: 'Right', - value: { - type, - id, - version, - documentToSave, - objectNamespace, - ...(requiresNamespacesCheck && { esRequestIndex: bulkGetRequestIndexCounter++ }), - }, - }; - }); + }); const getNamespaceId = (objectNamespace?: string) => objectNamespace !== undefined @@ -1445,78 +1447,71 @@ export class SavedObjectsRepository { } let bulkUpdateRequestIndexCounter = 0; const bulkUpdateParams: object[] = []; - const expectedBulkUpdateResults: Array< - Either, Record> - > = expectedBulkGetResults.map((expectedBulkGetResult) => { - if (isLeft(expectedBulkGetResult)) { - return expectedBulkGetResult; - } + const expectedBulkUpdateResults: Array, Record>> = + expectedBulkGetResults.map((expectedBulkGetResult) => { + if (isLeft(expectedBulkGetResult)) { + return expectedBulkGetResult; + } - const { - esRequestIndex, - id, - type, - version, - documentToSave, - objectNamespace, - } = expectedBulkGetResult.value; - - let namespaces; - let versionProperties; - if (esRequestIndex !== undefined) { - const indexFound = bulkGetResponse?.statusCode !== 404; - const actualResult = indexFound ? bulkGetResponse?.body.docs[esRequestIndex] : undefined; - const docFound = indexFound && actualResult?.found === true; - if ( - !docFound || + const { esRequestIndex, id, type, version, documentToSave, objectNamespace } = + expectedBulkGetResult.value; + + let namespaces; + let versionProperties; + if (esRequestIndex !== undefined) { + const indexFound = bulkGetResponse?.statusCode !== 404; + const actualResult = indexFound ? bulkGetResponse?.body.docs[esRequestIndex] : undefined; + const docFound = indexFound && actualResult?.found === true; + if ( + !docFound || + // @ts-expect-error MultiGetHit is incorrectly missing _id, _source + !this.rawDocExistsInNamespace(actualResult, getNamespaceId(objectNamespace)) + ) { + return { + tag: 'Left', + value: { + id, + type, + error: errorContent(SavedObjectsErrorHelpers.createGenericNotFoundError(type, id)), + }, + }; + } // @ts-expect-error MultiGetHit is incorrectly missing _id, _source - !this.rawDocExistsInNamespace(actualResult, getNamespaceId(objectNamespace)) - ) { - return { - tag: 'Left', - value: { - id, - type, - error: errorContent(SavedObjectsErrorHelpers.createGenericNotFoundError(type, id)), - }, - }; - } - // @ts-expect-error MultiGetHit is incorrectly missing _id, _source - namespaces = actualResult!._source.namespaces ?? [ + namespaces = actualResult!._source.namespaces ?? [ + // @ts-expect-error MultiGetHit is incorrectly missing _id, _source + SavedObjectsUtils.namespaceIdToString(actualResult!._source.namespace), + ]; // @ts-expect-error MultiGetHit is incorrectly missing _id, _source - SavedObjectsUtils.namespaceIdToString(actualResult!._source.namespace), - ]; - // @ts-expect-error MultiGetHit is incorrectly missing _id, _source - versionProperties = getExpectedVersionProperties(version, actualResult!); - } else { - if (this._registry.isSingleNamespace(type)) { - // if `objectNamespace` is undefined, fall back to `options.namespace` - namespaces = [getNamespaceString(objectNamespace)]; + versionProperties = getExpectedVersionProperties(version, actualResult!); + } else { + if (this._registry.isSingleNamespace(type)) { + // if `objectNamespace` is undefined, fall back to `options.namespace` + namespaces = [getNamespaceString(objectNamespace)]; + } + versionProperties = getExpectedVersionProperties(version); } - versionProperties = getExpectedVersionProperties(version); - } - const expectedResult = { - type, - id, - namespaces, - esRequestIndex: bulkUpdateRequestIndexCounter++, - documentToSave: expectedBulkGetResult.value.documentToSave, - }; + const expectedResult = { + type, + id, + namespaces, + esRequestIndex: bulkUpdateRequestIndexCounter++, + documentToSave: expectedBulkGetResult.value.documentToSave, + }; - bulkUpdateParams.push( - { - update: { - _id: this._serializer.generateRawId(getNamespaceId(objectNamespace), type, id), - _index: this.getIndexForType(type), - ...versionProperties, + bulkUpdateParams.push( + { + update: { + _id: this._serializer.generateRawId(getNamespaceId(objectNamespace), type, id), + _index: this.getIndexForType(type), + ...versionProperties, + }, }, - }, - { doc: documentToSave } - ); + { doc: documentToSave } + ); - return { tag: 'Right', value: expectedResult }; - }); + return { tag: 'Right', value: expectedResult }; + }); const { refresh = DEFAULT_REFRESH_SETTING } = options; const bulkUpdateResponse = bulkUpdateParams.length diff --git a/src/core/server/saved_objects/service/lib/repository_create_repository.test.ts b/src/core/server/saved_objects/service/lib/repository_create_repository.test.ts index 9d9a2eb14b49..a87f24a1eae1 100644 --- a/src/core/server/saved_objects/service/lib/repository_create_repository.test.ts +++ b/src/core/server/saved_objects/service/lib/repository_create_repository.test.ts @@ -58,7 +58,8 @@ describe('SavedObjectsRepository#createRepository', () => { }); const migrator = mockKibanaMigrator.create({ types: typeRegistry.getAllTypes() }); - const RepositoryConstructor = (SavedObjectsRepository as unknown) as jest.Mock; + const RepositoryConstructor = + SavedObjectsRepository as unknown as jest.Mock; beforeEach(() => { logger = loggerMock.create(); @@ -68,7 +69,7 @@ describe('SavedObjectsRepository#createRepository', () => { it('should not allow a repository with an undefined type', () => { try { originalRepository.createRepository( - (migrator as unknown) as KibanaMigrator, + migrator as unknown as KibanaMigrator, typeRegistry, '.kibana-test', callAdminCluster, @@ -84,7 +85,7 @@ describe('SavedObjectsRepository#createRepository', () => { it('should create a repository without hidden types', () => { const repository = originalRepository.createRepository( - (migrator as unknown) as KibanaMigrator, + migrator as unknown as KibanaMigrator, typeRegistry, '.kibana-test', callAdminCluster, @@ -103,7 +104,7 @@ describe('SavedObjectsRepository#createRepository', () => { it('should create a repository with a unique list of hidden types', () => { const repository = originalRepository.createRepository( - (migrator as unknown) as KibanaMigrator, + migrator as unknown as KibanaMigrator, typeRegistry, '.kibana-test', callAdminCluster, 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 eacc9357d694..437e7408b945 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 @@ -598,9 +598,9 @@ describe('#getQueryParams', () => { const mppClauses = shouldClauses.slice(1); - expect( - mppClauses.map((clause: any) => Object.keys(clause.match_phrase_prefix)[0]) - ).toEqual(['saved.title', 'pending.title', 'saved.desc', 'pending.desc']); + expect(mppClauses.map((clause: any) => Object.keys(clause.match_phrase_prefix)[0])).toEqual( + ['saved.title', 'pending.title', 'saved.desc', 'pending.desc'] + ); }); it('uses all registered types when `type` is not provided', () => { @@ -615,9 +615,9 @@ describe('#getQueryParams', () => { const mppClauses = shouldClauses.slice(1); - expect( - mppClauses.map((clause: any) => Object.keys(clause.match_phrase_prefix)[0]) - ).toEqual(['pending.title', 'saved.title', 'shared.title', 'global.title']); + expect(mppClauses.map((clause: any) => Object.keys(clause.match_phrase_prefix)[0])).toEqual( + ['pending.title', 'saved.title', 'shared.title', 'global.title'] + ); }); it('removes the prefix search wildcard from the query', () => { @@ -644,9 +644,9 @@ describe('#getQueryParams', () => { const mppClauses = shouldClauses.slice(1); - expect( - mppClauses.map((clause: any) => Object.keys(clause.match_phrase_prefix)[0]) - ).toEqual(['saved.title', 'global.name']); + expect(mppClauses.map((clause: any) => Object.keys(clause.match_phrase_prefix)[0])).toEqual( + ['saved.title', 'global.name'] + ); }); it('supports boosting', () => { diff --git a/src/core/server/saved_objects/service/lib/utils.ts b/src/core/server/saved_objects/service/lib/utils.ts index 6942b3b37623..df79eba56d13 100644 --- a/src/core/server/saved_objects/service/lib/utils.ts +++ b/src/core/server/saved_objects/service/lib/utils.ts @@ -15,7 +15,8 @@ export const DEFAULT_NAMESPACE_STRING = 'default'; export const ALL_NAMESPACES_STRING = '*'; export const FIND_DEFAULT_PAGE = 1; export const FIND_DEFAULT_PER_PAGE = 20; -const UUID_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +const UUID_REGEX = + /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; /** * @public diff --git a/src/core/server/saved_objects/service/saved_objects_client.mock.ts b/src/core/server/saved_objects/service/saved_objects_client.mock.ts index 4f96c5c0d8ca..f87779c89a81 100644 --- a/src/core/server/saved_objects/service/saved_objects_client.mock.ts +++ b/src/core/server/saved_objects/service/saved_objects_client.mock.ts @@ -11,7 +11,7 @@ import { SavedObjectsErrorHelpers } from './lib/errors'; import { savedObjectsPointInTimeFinderMock } from './lib/point_in_time_finder.mock'; const create = () => { - const mock = ({ + const mock = { errors: SavedObjectsErrorHelpers, create: jest.fn(), bulkCreate: jest.fn(), @@ -30,7 +30,7 @@ const create = () => { removeReferencesTo: jest.fn(), collectMultiNamespaceReferences: jest.fn(), updateObjectsSpaces: jest.fn(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; mock.createPointInTimeFinder = savedObjectsPointInTimeFinderMock.create({ savedObjectsMock: mock, diff --git a/src/core/server/saved_objects/status.test.ts b/src/core/server/saved_objects/status.test.ts index 96bba0606110..c830383c6eb6 100644 --- a/src/core/server/saved_objects/status.test.ts +++ b/src/core/server/saved_objects/status.test.ts @@ -108,10 +108,7 @@ describe('calculateStatus$', () => { }); it('is degraded after migrations have ran', async () => { await expect( - calculateStatus$( - of([{ status: 'skipped' }]), - esStatus$ - ) + calculateStatus$(of([{ status: 'skipped' }]), esStatus$) .pipe(take(2)) .toPromise() ).resolves.toEqual({ diff --git a/src/core/server/saved_objects/types.ts b/src/core/server/saved_objects/types.ts index 2dbc402e4626..83f46c521a83 100644 --- a/src/core/server/saved_objects/types.ts +++ b/src/core/server/saved_objects/types.ts @@ -383,9 +383,10 @@ export interface SavedObjectsTypeManagementDefinition { * the object page, relative to the base path. `uiCapabilitiesPath` is the path to check in the * {@link Capabilities | uiCapabilities} to check if the user has permission to access the object. */ - getInAppUrl?: ( - savedObject: SavedObject - ) => { path: string; uiCapabilitiesPath: string }; + getInAppUrl?: (savedObject: SavedObject) => { + path: string; + uiCapabilitiesPath: string; + }; /** * An optional export transform function that can be used transform the objects of the registered type during * the export process. diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index f1b22fb99784..bd959e2cb5a7 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -3019,7 +3019,7 @@ export const validBodyOutput: readonly ["data", "stream"]; // Warnings were encountered during analysis: // // src/core/server/elasticsearch/client/types.ts:94:7 - (ae-forgotten-export) The symbol "Explanation" needs to be exported by the entry point index.d.ts -// src/core/server/http/router/response.ts:301:3 - (ae-forgotten-export) The symbol "KibanaResponse" needs to be exported by the entry point index.d.ts +// src/core/server/http/router/response.ts:302:3 - (ae-forgotten-export) The symbol "KibanaResponse" needs to be exported by the entry point index.d.ts // src/core/server/plugins/types.ts:377:3 - (ae-forgotten-export) The symbol "KibanaConfigType" needs to be exported by the entry point index.d.ts // src/core/server/plugins/types.ts:377:3 - (ae-forgotten-export) The symbol "SharedGlobalConfigKeys" needs to be exported by the entry point index.d.ts // src/core/server/plugins/types.ts:380:3 - (ae-forgotten-export) The symbol "SavedObjectsConfigType" needs to be exported by the entry point index.d.ts diff --git a/src/core/server/ui_settings/ui_settings_service.ts b/src/core/server/ui_settings/ui_settings_service.ts index 4018779c6fe7..ceb6c5aa9181 100644 --- a/src/core/server/ui_settings/ui_settings_service.ts +++ b/src/core/server/ui_settings/ui_settings_service.ts @@ -36,7 +36,8 @@ export interface SetupDeps { /** @internal */ export class UiSettingsService - implements CoreService { + implements CoreService +{ private readonly log: Logger; private readonly config$: Observable; private readonly uiSettingsDefaults = new Map(); diff --git a/src/core/types/elasticsearch/search.ts b/src/core/types/elasticsearch/search.ts index e8ce9f98501f..88d6cda3777d 100644 --- a/src/core/types/elasticsearch/search.ts +++ b/src/core/types/elasticsearch/search.ts @@ -27,13 +27,12 @@ type KeysOfSources = T extends [infer U, ...infer V] ? KeyOfSource : {}; -type CompositeKeysOf< - TAggregationContainer extends estypes.AggregationsAggregationContainer -> = TAggregationContainer extends { - composite: { sources: [...infer TSource] }; -} - ? KeysOfSources - : unknown; +type CompositeKeysOf = + TAggregationContainer extends { + composite: { sources: [...infer TSource] }; + } + ? KeysOfSources + : unknown; type Source = estypes.SearchSourceFilter | boolean | estypes.Fields; @@ -263,13 +262,12 @@ export type AggregateOf< [key in keyof TAggregationContainer['filters']['filters']]: { doc_count: number; } & SubAggregateOf; - } & - (TAggregationContainer extends { filters: { other_bucket_key: infer TOtherBucketKey } } - ? Record< - TOtherBucketKey & string, - { doc_count: number } & SubAggregateOf - > - : unknown) & + } & (TAggregationContainer extends { filters: { other_bucket_key: infer TOtherBucketKey } } + ? Record< + TOtherBucketKey & string, + { doc_count: number } & SubAggregateOf + > + : unknown) & (TAggregationContainer extends { filters: { other_bucket: true } } ? { _other: { doc_count: number } & SubAggregateOf } : unknown) diff --git a/src/dev/build/lib/integration_tests/download.test.ts b/src/dev/build/lib/integration_tests/download.test.ts index 23c7569c54c8..9003e678e98a 100644 --- a/src/dev/build/lib/integration_tests/download.test.ts +++ b/src/dev/build/lib/integration_tests/download.test.ts @@ -42,10 +42,12 @@ const log = new ToolingLog({ type Handler = (req: IncomingMessage, res: ServerResponse) => void; const FOO_SHA256 = '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae'; -const createSendHandler = (send: any): Handler => (req, res) => { - res.statusCode = 200; - res.end(send); -}; +const createSendHandler = + (send: any): Handler => + (req, res) => { + res.statusCode = 200; + res.end(send); + }; const sendErrorHandler: Handler = (req, res) => { res.statusCode = 500; res.end(); diff --git a/src/dev/build/tasks/patch_native_modules_task.ts b/src/dev/build/tasks/patch_native_modules_task.ts index be2571c029f9..5a2f179edecc 100644 --- a/src/dev/build/tasks/patch_native_modules_task.ts +++ b/src/dev/build/tasks/patch_native_modules_task.ts @@ -55,8 +55,7 @@ const packages: Package[] = [ // * gzip -c build/Release/re2.node > linux-arm64-83.gz // * upload to kibana-ci-proxy-cache bucket 'linux-arm64': { - url: - 'https://storage.googleapis.com/kibana-ci-proxy-cache/node-re2/uhop/node-re2/releases/download/1.16.0/linux-arm64-83.gz', + url: 'https://storage.googleapis.com/kibana-ci-proxy-cache/node-re2/uhop/node-re2/releases/download/1.16.0/linux-arm64-83.gz', sha256: '114505c60dbf57ad30556937ac5f49213c6676ad79d92706b96949d3a63f53b4', }, 'win32-x64': { diff --git a/src/dev/i18n/extractors/i18n_call.test.js b/src/dev/i18n/extractors/i18n_call.test.js index b20a06d40dee..89cd9fcbbd31 100644 --- a/src/dev/i18n/extractors/i18n_call.test.js +++ b/src/dev/i18n/extractors/i18n_call.test.js @@ -28,15 +28,15 @@ description 3\` }); 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)); + let callExpressionNode = [...traverseNodes(parse(i18nCallMessageSource).program.body)].find( + (node) => isCallExpression(node) + ); expect(extractI18nCallMessages(callExpressionNode)).toMatchSnapshot(); - callExpressionNode = [ - ...traverseNodes(parse(translateCallMessageSource).program.body), - ].find((node) => isCallExpression(node)); + callExpressionNode = [...traverseNodes(parse(translateCallMessageSource).program.body)].find( + (node) => isCallExpression(node) + ); expect(extractI18nCallMessages(callExpressionNode)).toMatchSnapshot(); diff --git a/src/dev/i18n/utils/utils.test.js b/src/dev/i18n/utils/utils.test.js index f737c9adb9b2..801d98194f49 100644 --- a/src/dev/i18n/utils/utils.test.js +++ b/src/dev/i18n/utils/utils.test.js @@ -68,9 +68,9 @@ describe('i18n utils', () => { }); test('should detect object property with defined key', () => { - const objectExpresssionNode = [ - ...traverseNodes(parse(objectPropertySource).program.body), - ].find((node) => isObjectExpression(node)); + const objectExpresssionNode = [...traverseNodes(parse(objectPropertySource).program.body)].find( + (node) => isObjectExpression(node) + ); const [objectExpresssionProperty] = objectExpresssionNode.properties; expect(isPropertyWithKey(objectExpresssionProperty, 'id')).toBe(true); diff --git a/src/dev/run_check_published_api_changes.ts b/src/dev/run_check_published_api_changes.ts index be2ca4343274..7c8105bc40c5 100644 --- a/src/dev/run_check_published_api_changes.ts +++ b/src/dev/run_check_published_api_changes.ts @@ -195,7 +195,7 @@ async function run(folder: string, { opts }: { opts: Options }): Promise { const extraFlags: string[] = []; - const opts = (getopts(process.argv.slice(2), { + const opts = getopts(process.argv.slice(2), { boolean: ['accept', 'docs', 'help'], string: ['filter'], default: { @@ -205,7 +205,7 @@ async function run(folder: string, { opts }: { opts: Options }): Promise 0) { for (const flag of extraFlags) { diff --git a/src/dev/run_find_plugins_with_circular_deps.ts b/src/dev/run_find_plugins_with_circular_deps.ts index 4ce71b24332c..f7974b464fca 100644 --- a/src/dev/run_find_plugins_with_circular_deps.ts +++ b/src/dev/run_find_plugins_with_circular_deps.ts @@ -40,7 +40,8 @@ run( const circularDependenciesFullPaths = parseCircular(depTree).filter((circularDeps) => { const first = circularDeps[0]; const last = circularDeps[circularDeps.length - 1]; - const matchRegex = /(?(src|x-pack)\/plugins|examples|x-pack\/examples)\/(?[^\/]*)\/.*/; + const matchRegex = + /(?(src|x-pack)\/plugins|examples|x-pack\/examples)\/(?[^\/]*)\/.*/; const firstMatch = first.match(matchRegex); const lastMatch = last.match(matchRegex); 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 e6724e93866e..b90efe9033da 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 @@ -353,7 +353,7 @@ describe('Field', () => { (component.instance() as Field).getImageAsBase64 = ({}: Blob) => Promise.resolve(''); it('should be able to change value and cancel', async () => { - (component.instance() as Field).onImageChange(([userValue] as unknown) as FileList); + (component.instance() as Field).onImageChange([userValue] as unknown as FileList); expect(handleChange).toBeCalled(); await wrapper.setProps({ unsavedChanges: { @@ -377,9 +377,9 @@ describe('Field', () => { const updated = wrapper.update(); findTestSubject(updated, `advancedSetting-changeImage-${setting.name}`).simulate('click'); const newUserValue = `${userValue}=`; - await (component.instance() as Field).onImageChange(([ + await (component.instance() as Field).onImageChange([ newUserValue, - ] as unknown) as FileList); + ] as unknown as FileList); expect(handleChange).toBeCalled(); }); diff --git a/src/plugins/advanced_settings/public/plugin.ts b/src/plugins/advanced_settings/public/plugin.ts index 50162526eb87..b7f1455f65df 100644 --- a/src/plugins/advanced_settings/public/plugin.ts +++ b/src/plugins/advanced_settings/public/plugin.ts @@ -19,7 +19,8 @@ const title = i18n.translate('advancedSettings.advancedSettingsLabel', { }); export class AdvancedSettingsPlugin - implements Plugin { + implements Plugin +{ public setup( core: CoreSetup, { management, home, usageCollection }: AdvancedSettingsPluginSetup 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 719bddc4080d..0b6dbe49d0e8 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 @@ -28,15 +28,15 @@ const isPending = (promise: Promise): Promise => getPromiseState(promise).then((state) => state === 'pending'); const setup = () => { - const xhr = ({} as unknown) as XMLHttpRequest; + const xhr = {} as unknown as XMLHttpRequest; const { promise, resolve, reject } = defer(); const stream = new Subject(); - const fetchStreaming = (jest.fn(() => ({ + const fetchStreaming = jest.fn(() => ({ xhr, promise, stream, - })) as unknown) as jest.SpyInstance & typeof fetchStreamingReal; + })) as unknown as jest.SpyInstance & typeof fetchStreamingReal; return { fetchStreaming, diff --git a/src/plugins/bfetch/public/plugin.ts b/src/plugins/bfetch/public/plugin.ts index f97a91a0e70d..3ad451c7713e 100644 --- a/src/plugins/bfetch/public/plugin.ts +++ b/src/plugins/bfetch/public/plugin.ts @@ -37,7 +37,8 @@ export class BfetchPublicPlugin BfetchPublicStart, BfetchPublicSetupDependencies, BfetchPublicStartDependencies - > { + > +{ private contract!: BfetchPublicContract; constructor(private readonly initializerContext: PluginInitializerContext) {} @@ -74,29 +75,33 @@ export class BfetchPublicPlugin public stop() {} - private fetchStreaming = ( - version: string, - basePath: string, - compressionDisabled$: Observable - ): BfetchPublicSetup['fetchStreaming'] => (params) => - fetchStreamingStatic({ - ...params, - url: `${basePath}/${removeLeadingSlash(params.url)}`, - headers: { - 'Content-Type': 'application/json', - 'kbn-version': version, - ...(params.headers || {}), - }, - compressionDisabled$, - }); + private fetchStreaming = + ( + version: string, + basePath: string, + compressionDisabled$: Observable + ): BfetchPublicSetup['fetchStreaming'] => + (params) => + fetchStreamingStatic({ + ...params, + url: `${basePath}/${removeLeadingSlash(params.url)}`, + headers: { + 'Content-Type': 'application/json', + 'kbn-version': version, + ...(params.headers || {}), + }, + compressionDisabled$, + }); - private batchedFunction = ( - fetchStreaming: BfetchPublicContract['fetchStreaming'], - compressionDisabled$: Observable - ): BfetchPublicContract['batchedFunction'] => (params) => - createStreamingBatchedFunction({ - ...params, - compressionDisabled$, - fetchStreaming: params.fetchStreaming || fetchStreaming, - }); + private batchedFunction = + ( + fetchStreaming: BfetchPublicContract['fetchStreaming'], + compressionDisabled$: Observable + ): BfetchPublicContract['batchedFunction'] => + (params) => + createStreamingBatchedFunction({ + ...params, + compressionDisabled$, + fetchStreaming: params.fetchStreaming || fetchStreaming, + }); } diff --git a/src/plugins/bfetch/public/streaming/from_streaming_xhr.test.ts b/src/plugins/bfetch/public/streaming/from_streaming_xhr.test.ts index fc414cee41b7..bc5bf28183a5 100644 --- a/src/plugins/bfetch/public/streaming/from_streaming_xhr.test.ts +++ b/src/plugins/bfetch/public/streaming/from_streaming_xhr.test.ts @@ -9,14 +9,14 @@ import { fromStreamingXhr } from './from_streaming_xhr'; const createXhr = (): XMLHttpRequest => - (({ + ({ abort: () => {}, onprogress: () => {}, onreadystatechange: () => {}, readyState: 0, responseText: '', status: 0, - } as unknown) as XMLHttpRequest); + } as unknown as XMLHttpRequest); test('returns observable', () => { const xhr = createXhr(); diff --git a/src/plugins/bfetch/public/streaming/split.ts b/src/plugins/bfetch/public/streaming/split.ts index 47e4b6e8608e..9a4439dd6ded 100644 --- a/src/plugins/bfetch/public/streaming/split.ts +++ b/src/plugins/bfetch/public/streaming/split.ts @@ -22,27 +22,27 @@ import { filter } from 'rxjs/operators'; * asdf -> fdf -> aaa -> dfsdf * */ -export const split = (delimiter: string = '\n') => ( - in$: Observable -): Observable => { - const out$ = new Subject(); - let startingText = ''; +export const split = + (delimiter: string = '\n') => + (in$: Observable): Observable => { + const out$ = new Subject(); + let startingText = ''; - in$.subscribe( - (chunk) => { - const messages = (startingText + chunk).split(delimiter); + in$.subscribe( + (chunk) => { + const messages = (startingText + chunk).split(delimiter); - // We don't want to send the last message here, since it may or - // may not be a partial message. - messages.slice(0, -1).forEach(out$.next.bind(out$)); - startingText = messages.length ? messages[messages.length - 1] : ''; - }, - out$.error.bind(out$), - () => { - out$.next(startingText); - out$.complete(); - } - ); + // We don't want to send the last message here, since it may or + // may not be a partial message. + messages.slice(0, -1).forEach(out$.next.bind(out$)); + startingText = messages.length ? messages[messages.length - 1] : ''; + }, + out$.error.bind(out$), + () => { + out$.next(startingText); + out$.complete(); + } + ); - return out$.pipe(filter(Boolean)); -}; + return out$.pipe(filter(Boolean)); + }; diff --git a/src/plugins/bfetch/server/plugin.ts b/src/plugins/bfetch/server/plugin.ts index ee6ec77e63d9..7b60be9a8fc7 100644 --- a/src/plugins/bfetch/server/plugin.ts +++ b/src/plugins/bfetch/server/plugin.ts @@ -108,7 +108,8 @@ export class BfetchServerPlugin BfetchServerStart, BfetchServerSetupDependencies, BfetchServerStartDependencies - > { + > +{ constructor(private readonly initializerContext: PluginInitializerContext) {} public setup(core: CoreSetup, plugins: BfetchServerSetupDependencies): BfetchServerSetup { @@ -145,79 +146,84 @@ export class BfetchServerPlugin return request.headers['x-chunk-encoding'] !== 'deflate'; } - private addStreamingResponseRoute = ({ - getStartServices, - router, - logger, - }: { - getStartServices: StartServicesAccessor; - router: ReturnType; - logger: Logger; - }): BfetchServerSetup['addStreamingResponseRoute'] => (path, handler) => { - router.post( - { - path: `/${removeLeadingSlash(path)}`, - validate: { - body: schema.any(), + private addStreamingResponseRoute = + ({ + getStartServices, + router, + logger, + }: { + getStartServices: StartServicesAccessor; + router: ReturnType; + logger: Logger; + }): BfetchServerSetup['addStreamingResponseRoute'] => + (path, handler) => { + router.post( + { + path: `/${removeLeadingSlash(path)}`, + validate: { + body: schema.any(), + }, }, - }, - async (context, request, response) => { + async (context, request, response) => { + const handlerInstance = handler(request); + const data = request.body; + const compressionDisabled = this.getCompressionDisabled(request); + return response.ok({ + headers: streamingHeaders, + body: createStream( + handlerInstance.getResponseStream(data), + logger, + compressionDisabled + ), + }); + } + ); + }; + + private createStreamingRequestHandler = + ({ + logger, + getStartServices, + }: { + logger: Logger; + getStartServices: StartServicesAccessor; + }): BfetchServerSetup['createStreamingRequestHandler'] => + (streamHandler) => + async (context, request, response) => { + const response$ = await streamHandler(context, request); + const compressionDisabled = this.getCompressionDisabled(request); + return response.ok({ + headers: streamingHeaders, + body: createStream(response$, logger, compressionDisabled), + }); + }; + + private addBatchProcessingRoute = + ( + addStreamingResponseRoute: BfetchServerSetup['addStreamingResponseRoute'] + ): BfetchServerSetup['addBatchProcessingRoute'] => + ( + path: string, + handler: ( + request: KibanaRequest + ) => BatchProcessingRouteParams + ) => { + addStreamingResponseRoute< + BatchRequestData, + BatchResponseItem + >(path, (request) => { const handlerInstance = handler(request); - const data = request.body; - const compressionDisabled = this.getCompressionDisabled(request); - return response.ok({ - headers: streamingHeaders, - body: createStream(handlerInstance.getResponseStream(data), logger, compressionDisabled), - }); - } - ); - }; - - private createStreamingRequestHandler = ({ - logger, - getStartServices, - }: { - logger: Logger; - getStartServices: StartServicesAccessor; - }): BfetchServerSetup['createStreamingRequestHandler'] => (streamHandler) => async ( - context, - request, - response - ) => { - const response$ = await streamHandler(context, request); - const compressionDisabled = this.getCompressionDisabled(request); - return response.ok({ - headers: streamingHeaders, - body: createStream(response$, logger, compressionDisabled), - }); - }; - - private addBatchProcessingRoute = ( - addStreamingResponseRoute: BfetchServerSetup['addStreamingResponseRoute'] - ): BfetchServerSetup['addBatchProcessingRoute'] => < - BatchItemData extends object, - BatchItemResult extends object, - E extends ErrorLike = ErrorLike - >( - path: string, - handler: (request: KibanaRequest) => BatchProcessingRouteParams - ) => { - addStreamingResponseRoute< - BatchRequestData, - BatchResponseItem - >(path, (request) => { - const handlerInstance = handler(request); - return { - getResponseStream: ({ batch }) => - map$(batch, async (batchItem, id) => { - try { - const result = await handlerInstance.onBatchItem(batchItem); - return { id, result }; - } catch (error) { - return { id, error: normalizeError(error) }; - } - }), - }; - }); - }; + return { + getResponseStream: ({ batch }) => + map$(batch, async (batchItem, id) => { + try { + const result = await handlerInstance.onBatchItem(batchItem); + return { id, result }; + } catch (error) { + return { id, error: normalizeError(error) }; + } + }), + }; + }); + }; } diff --git a/src/plugins/chart_expressions/expression_tagcloud/common/expression_functions/__snapshots__/tagcloud_function.test.ts.snap b/src/plugins/chart_expressions/expression_tagcloud/common/expression_functions/__snapshots__/tagcloud_function.test.ts.snap index da116bc50f37..37da83ef8ac9 100644 --- a/src/plugins/chart_expressions/expression_tagcloud/common/expression_functions/__snapshots__/tagcloud_function.test.ts.snap +++ b/src/plugins/chart_expressions/expression_tagcloud/common/expression_functions/__snapshots__/tagcloud_function.test.ts.snap @@ -71,10 +71,7 @@ Object { }, "minFontSize": 18, "orientation": "single", - "palette": Object { - "name": "default", - "type": "palette", - }, + "palette": "{palette}", "scale": "linear", "showLabel": true, }, @@ -142,10 +139,7 @@ Object { }, "minFontSize": 18, "orientation": "single", - "palette": Object { - "name": "default", - "type": "palette", - }, + "palette": "{palette}", "scale": "linear", "showLabel": true, }, diff --git a/src/plugins/chart_expressions/expression_tagcloud/common/expression_functions/tagcloud_function.ts b/src/plugins/chart_expressions/expression_tagcloud/common/expression_functions/tagcloud_function.ts index 2ce50e94aeda..1c499db96917 100644 --- a/src/plugins/chart_expressions/expression_tagcloud/common/expression_functions/tagcloud_function.ts +++ b/src/plugins/chart_expressions/expression_tagcloud/common/expression_functions/tagcloud_function.ts @@ -110,9 +110,9 @@ export const tagcloudFunction: ExpressionTagcloudFunction = () => { help: argHelp.showLabel, }, palette: { - types: ['string'], + types: ['palette', 'system_palette'], help: argHelp.palette, - default: 'default', + default: '{palette}', }, metric: { types: ['vis_dimension'], @@ -135,10 +135,7 @@ export const tagcloudFunction: ExpressionTagcloudFunction = () => { ...(args.bucket && { bucket: args.bucket, }), - palette: { - type: 'palette', - name: args.palette, - }, + palette: args.palette, }; if (handlers?.inspectorAdapters?.tables) { diff --git a/src/plugins/chart_expressions/expression_tagcloud/common/types/expression_functions.ts b/src/plugins/chart_expressions/expression_tagcloud/common/types/expression_functions.ts index 1ee0434e1603..091b3e861332 100644 --- a/src/plugins/chart_expressions/expression_tagcloud/common/types/expression_functions.ts +++ b/src/plugins/chart_expressions/expression_tagcloud/common/types/expression_functions.ts @@ -41,7 +41,7 @@ export interface TagcloudRendererConfig { } interface Arguments extends TagCloudVisConfig { - palette: string; + palette: PaletteOutput; } export type ExpressionTagcloudFunction = () => ExpressionFunctionDefinition< diff --git a/src/plugins/chart_expressions/expression_tagcloud/public/components/tagcloud_component.tsx b/src/plugins/chart_expressions/expression_tagcloud/public/components/tagcloud_component.tsx index b7d38c71f586..b0f9f3197a44 100644 --- a/src/plugins/chart_expressions/expression_tagcloud/public/components/tagcloud_component.tsx +++ b/src/plugins/chart_expressions/expression_tagcloud/public/components/tagcloud_component.tsx @@ -11,7 +11,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { throttle } from 'lodash'; import { EuiIconTip, EuiResizeObserver } from '@elastic/eui'; import { Chart, Settings, Wordcloud, RenderChangeListener } from '@elastic/charts'; -import type { PaletteRegistry } from '../../../../charts/public'; +import type { PaletteRegistry, PaletteOutput } from '../../../../charts/public'; import { Datatable, DatatableColumn, @@ -36,12 +36,12 @@ const calculateWeight = (value: number, x1: number, y1: number, x2: number, y2: const getColor = ( palettes: PaletteRegistry, - activePalette: string, + activePalette: PaletteOutput, text: string, values: string[], syncColors: boolean ) => { - return palettes?.get(activePalette).getCategoricalColor( + return palettes?.get(activePalette?.name)?.getCategoricalColor( [ { name: text, @@ -54,7 +54,8 @@ const getColor = ( totalSeries: values.length || 1, behindText: false, syncColors, - } + }, + activePalette?.params ?? { colors: [] } ); }; @@ -113,14 +114,14 @@ export const TagCloudChart = ({ tag === 'all' || visData.rows.length <= 1 ? 1 : calculateWeight(row[metricColumn], minValue, maxValue, 0, 1) || 0, - color: getColor(palettesRegistry, palette.name, tag, values, syncColors) || 'rgba(0,0,0,0)', + color: getColor(palettesRegistry, palette, tag, values, syncColors) || 'rgba(0,0,0,0)', }; }); }, [ bucket, bucketFormatter, metric.accessor, - palette.name, + palette, palettesRegistry, syncColors, visData.columns, diff --git a/src/plugins/chart_expressions/expression_tagcloud/public/format_service.ts b/src/plugins/chart_expressions/expression_tagcloud/public/format_service.ts index 541e46a84726..778170321bcc 100644 --- a/src/plugins/chart_expressions/expression_tagcloud/public/format_service.ts +++ b/src/plugins/chart_expressions/expression_tagcloud/public/format_service.ts @@ -17,6 +17,5 @@ import { createGetterSetter } from '../../../kibana_utils/public'; import { FieldFormatsStart } from '../../../field_formats/public'; -export const [getFormatService, setFormatService] = createGetterSetter( - 'fieldFormats' -); +export const [getFormatService, setFormatService] = + createGetterSetter('fieldFormats'); diff --git a/src/plugins/chart_expressions/expression_tagcloud/public/plugin.ts b/src/plugins/chart_expressions/expression_tagcloud/public/plugin.ts index 9ffb910bde21..5a8bcc8aa64b 100644 --- a/src/plugins/chart_expressions/expression_tagcloud/public/plugin.ts +++ b/src/plugins/chart_expressions/expression_tagcloud/public/plugin.ts @@ -34,7 +34,8 @@ export type ExpressionTagcloudPluginStart = void; export class ExpressionTagcloudPlugin implements - Plugin { + Plugin +{ public setup(core: CoreSetup, { expressions, charts }: SetupDeps): ExpressionTagcloudPluginSetup { const rendererDependencies: ExpressioTagcloudRendererDependencies = { palettes: charts.palettes, diff --git a/src/plugins/chart_expressions/expression_tagcloud/server/plugin.ts b/src/plugins/chart_expressions/expression_tagcloud/server/plugin.ts index 03dd05db25fa..11f0d03407fb 100644 --- a/src/plugins/chart_expressions/expression_tagcloud/server/plugin.ts +++ b/src/plugins/chart_expressions/expression_tagcloud/server/plugin.ts @@ -23,7 +23,8 @@ export type ExpressionTagcloudPluginStart = void; export class ExpressionTagcloudPlugin implements - Plugin { + Plugin +{ public setup(core: CoreSetup, { expressions }: SetupDeps): ExpressionTagcloudPluginSetup { expressions.registerFunction(tagcloudFunction); } diff --git a/src/plugins/charts/common/palette.ts b/src/plugins/charts/common/palette.ts index 78c6fcc81202..1faeb4df7788 100644 --- a/src/plugins/charts/common/palette.ts +++ b/src/plugins/charts/common/palette.ts @@ -35,11 +35,12 @@ export interface SystemPaletteArguments { name: string; } -export interface PaletteOutput { - type: 'palette'; +export interface PaletteOutput { + type: 'palette' | 'system_palette'; name: string; params?: T; } + export const defaultCustomColors = [ // This set of defaults originated in Canvas, which, at present, is the primary // consumer of this function. Changing this default requires a change in Canvas diff --git a/src/plugins/charts/public/services/active_cursor/active_cursor_utils.test.ts b/src/plugins/charts/public/services/active_cursor/active_cursor_utils.test.ts index 3230c1ec0f32..6bccc456edbb 100644 --- a/src/plugins/charts/public/services/active_cursor/active_cursor_utils.test.ts +++ b/src/plugins/charts/public/services/active_cursor/active_cursor_utils.test.ts @@ -34,7 +34,7 @@ describe('active_cursor_utils', () => { test('should extract accessors', () => { expect( parseSyncOptions({ - datatables: ([ + datatables: [ { columns: [ { @@ -45,7 +45,7 @@ describe('active_cursor_utils', () => { }, ], }, - ] as unknown) as Datatable[], + ] as unknown as Datatable[], }).accessors ).toMatchInlineSnapshot(` Array [ @@ -57,7 +57,7 @@ describe('active_cursor_utils', () => { test('should return isDateHistogram true in case all datatables is time based', () => { expect( parseSyncOptions({ - datatables: ([ + datatables: [ { columns: [ { @@ -84,7 +84,7 @@ describe('active_cursor_utils', () => { }, ], }, - ] as unknown) as Datatable[], + ] as unknown as Datatable[], }) ).toMatchInlineSnapshot(` Object { @@ -100,7 +100,7 @@ describe('active_cursor_utils', () => { test('should return isDateHistogram false in case of not all datatables is time based', () => { expect( parseSyncOptions({ - datatables: ([ + datatables: [ { columns: [ { @@ -124,7 +124,7 @@ describe('active_cursor_utils', () => { }, ], }, - ] as unknown) as Datatable[], + ] as unknown as Datatable[], }) ).toMatchInlineSnapshot(` Object { diff --git a/src/plugins/charts/public/services/active_cursor/use_active_cursor.test.ts b/src/plugins/charts/public/services/active_cursor/use_active_cursor.test.ts index 50e7c995a125..b60862373f99 100644 --- a/src/plugins/charts/public/services/active_cursor/use_active_cursor.test.ts +++ b/src/plugins/charts/public/services/active_cursor/use_active_cursor.test.ts @@ -111,7 +111,7 @@ describe.skip('useActiveCursor', () => { test('should trigger cursor pointer update (chart type: datatable - time based, event type: time)', async () => { await act( { - datatables: ([ + datatables: [ { columns: [ { @@ -125,7 +125,7 @@ describe.skip('useActiveCursor', () => { }, ], }, - ] as unknown) as Datatable[], + ] as unknown as Datatable[], }, [{ isDateHistogram: true }, { accessors: ['foo_index:foo_field'] }] ); diff --git a/src/plugins/charts/public/static/components/endzones.tsx b/src/plugins/charts/public/static/components/endzones.tsx index b2b6b3534c85..85a020e54eb3 100644 --- a/src/plugins/charts/public/static/components/endzones.tsx +++ b/src/plugins/charts/public/static/components/endzones.tsx @@ -156,32 +156,36 @@ const Prompt = () => ( ); -export const renderEndzoneTooltip = ( - xInterval?: number, - domainStart?: number, - domainEnd?: number, - formatter?: (v: any) => string, - renderValue = true -) => (headerData: TooltipValue): JSX.Element | string => { - const headerDataValue = headerData.value; - const formattedValue = formatter ? formatter(headerDataValue) : headerDataValue; - - if ( - (domainStart !== undefined && domainStart > headerDataValue) || - (domainEnd !== undefined && xInterval !== undefined && domainEnd - xInterval < headerDataValue) - ) { - return ( - <> - - {renderValue && ( - <> - -

{formattedValue}

- - )} - - ); - } +export const renderEndzoneTooltip = + ( + xInterval?: number, + domainStart?: number, + domainEnd?: number, + formatter?: (v: any) => string, + renderValue = true + ) => + (headerData: TooltipValue): JSX.Element | string => { + const headerDataValue = headerData.value; + const formattedValue = formatter ? formatter(headerDataValue) : headerDataValue; + + if ( + (domainStart !== undefined && domainStart > headerDataValue) || + (domainEnd !== undefined && + xInterval !== undefined && + domainEnd - xInterval < headerDataValue) + ) { + return ( + <> + + {renderValue && ( + <> + +

{formattedValue}

+ + )} + + ); + } - return renderValue ? formattedValue : null; -}; + return renderValue ? formattedValue : null; + }; diff --git a/src/plugins/charts/public/static/utils/transform_click_event.ts b/src/plugins/charts/public/static/utils/transform_click_event.ts index 844e2c3b301f..7fdd59f47988 100644 --- a/src/plugins/charts/public/static/utils/transform_click_event.ts +++ b/src/plugins/charts/public/static/utils/transform_click_event.ts @@ -112,27 +112,29 @@ function getSplitChartValue({ * @param yAccessor * @param splitAccessors */ -const columnReducer = ( - xAccessor: Accessor | AccessorFn | null, - yAccessor: Accessor | AccessorFn | null, - splitAccessors: AllSeriesAccessors, - splitChartAccessor?: Accessor | AccessorFn -) => ( - acc: Array<[index: number, id: string]>, - { id }: Datatable['columns'][number], - index: number -): Array<[index: number, id: string]> => { - if ( - (xAccessor !== null && validateAccessorId(id, xAccessor)) || - (yAccessor !== null && validateAccessorId(id, yAccessor)) || - (splitChartAccessor !== undefined && validateAccessorId(id, splitChartAccessor)) || - splitAccessors.some(([accessor]) => validateAccessorId(id, accessor)) - ) { - acc.push([index, id]); - } +const columnReducer = + ( + xAccessor: Accessor | AccessorFn | null, + yAccessor: Accessor | AccessorFn | null, + splitAccessors: AllSeriesAccessors, + splitChartAccessor?: Accessor | AccessorFn + ) => + ( + acc: Array<[index: number, id: string]>, + { id }: Datatable['columns'][number], + index: number + ): Array<[index: number, id: string]> => { + if ( + (xAccessor !== null && validateAccessorId(id, xAccessor)) || + (yAccessor !== null && validateAccessorId(id, yAccessor)) || + (splitChartAccessor !== undefined && validateAccessorId(id, splitChartAccessor)) || + splitAccessors.some(([accessor]) => validateAccessorId(id, accessor)) + ) { + acc.push([index, id]); + } - return acc; -}; + return acc; + }; /** * Finds matching row index for given accessors and geometry values @@ -142,23 +144,25 @@ const columnReducer = ( * @param yAccessor * @param splitAccessors */ -const rowFindPredicate = ( - geometry: GeometryValue | null, - xAccessor: Accessor | AccessorFn | null, - yAccessor: Accessor | AccessorFn | null, - splitAccessors: AllSeriesAccessors, - splitChartAccessor?: Accessor | AccessorFn, - splitChartValue?: string | number -) => (row: Datatable['rows'][number]): boolean => - (geometry === null || - (xAccessor !== null && - getAccessorValue(row, xAccessor) === getAccessorValue(geometry.datum, xAccessor) && - yAccessor !== null && - getAccessorValue(row, yAccessor) === getAccessorValue(geometry.datum, yAccessor) && - (splitChartAccessor === undefined || - (splitChartValue !== undefined && - getAccessorValue(row, splitChartAccessor) === splitChartValue)))) && - [...splitAccessors].every(([accessor, value]) => getAccessorValue(row, accessor) === value); +const rowFindPredicate = + ( + geometry: GeometryValue | null, + xAccessor: Accessor | AccessorFn | null, + yAccessor: Accessor | AccessorFn | null, + splitAccessors: AllSeriesAccessors, + splitChartAccessor?: Accessor | AccessorFn, + splitChartValue?: string | number + ) => + (row: Datatable['rows'][number]): boolean => + (geometry === null || + (xAccessor !== null && + getAccessorValue(row, xAccessor) === getAccessorValue(geometry.datum, xAccessor) && + yAccessor !== null && + getAccessorValue(row, yAccessor) === getAccessorValue(geometry.datum, yAccessor) && + (splitChartAccessor === undefined || + (splitChartValue !== undefined && + getAccessorValue(row, splitChartAccessor) === splitChartValue)))) && + [...splitAccessors].every(([accessor, value]) => getAccessorValue(row, accessor) === value); /** * Helper function to transform `@elastic/charts` click event into filter action event @@ -168,103 +172,106 @@ const rowFindPredicate = ( * @param splitSeriesAccessorFnMap needed when using `splitSeriesAccessors` as `AccessorFn` * @param negate */ -export const getFilterFromChartClickEventFn = ( - table: Datatable, - xAccessor: Accessor | AccessorFn, - splitSeriesAccessorFnMap?: Map, - splitChartAccessor?: Accessor | AccessorFn, - negate: boolean = false -) => (points: Array<[GeometryValue, XYChartSeriesIdentifier]>): ClickTriggerEvent => { - const data: ValueClickContext['data']['data'] = []; +export const getFilterFromChartClickEventFn = + ( + table: Datatable, + xAccessor: Accessor | AccessorFn, + splitSeriesAccessorFnMap?: Map, + splitChartAccessor?: Accessor | AccessorFn, + negate: boolean = false + ) => + (points: Array<[GeometryValue, XYChartSeriesIdentifier]>): ClickTriggerEvent => { + const data: ValueClickContext['data']['data'] = []; + + points.forEach((point) => { + const [geometry, { yAccessor, splitAccessors }] = point; + const splitChartValue = getSplitChartValue(point[1]); + const allSplitAccessors = getAllSplitAccessors(splitAccessors, splitSeriesAccessorFnMap); + const columns = table.columns.reduce>( + columnReducer(xAccessor, yAccessor, allSplitAccessors, splitChartAccessor), + [] + ); + const row = table.rows.findIndex( + rowFindPredicate( + geometry, + xAccessor, + yAccessor, + allSplitAccessors, + splitChartAccessor, + splitChartValue + ) + ); + const newData = columns.map(([column, id]) => ({ + table, + column, + row, + value: table.rows?.[row]?.[id] ?? null, + })); - points.forEach((point) => { - const [geometry, { yAccessor, splitAccessors }] = point; - const splitChartValue = getSplitChartValue(point[1]); + data.push(...newData); + }); + + return { + name: 'filterBucket', + data: { + negate, + data, + }, + }; + }; + +/** + * Helper function to get filter action event from series + */ +export const getFilterFromSeriesFn = + (table: Datatable) => + ( + { splitAccessors, ...rest }: XYChartSeriesIdentifier, + splitSeriesAccessorFnMap?: Map, + splitChartAccessor?: Accessor | AccessorFn, + negate = false + ): ClickTriggerEvent => { + const splitChartValue = getSplitChartValue(rest); const allSplitAccessors = getAllSplitAccessors(splitAccessors, splitSeriesAccessorFnMap); const columns = table.columns.reduce>( - columnReducer(xAccessor, yAccessor, allSplitAccessors, splitChartAccessor), + columnReducer(null, null, allSplitAccessors, splitChartAccessor), [] ); const row = table.rows.findIndex( - rowFindPredicate( - geometry, - xAccessor, - yAccessor, - allSplitAccessors, - splitChartAccessor, - splitChartValue - ) + rowFindPredicate(null, null, null, allSplitAccessors, splitChartAccessor, splitChartValue) ); - const newData = columns.map(([column, id]) => ({ + const data: ValueClickContext['data']['data'] = columns.map(([column, id]) => ({ table, column, row, value: table.rows?.[row]?.[id] ?? null, })); - data.push(...newData); - }); - - return { - name: 'filterBucket', - data: { - negate, - data, - }, - }; -}; - -/** - * Helper function to get filter action event from series - */ -export const getFilterFromSeriesFn = (table: Datatable) => ( - { splitAccessors, ...rest }: XYChartSeriesIdentifier, - splitSeriesAccessorFnMap?: Map, - splitChartAccessor?: Accessor | AccessorFn, - negate = false -): ClickTriggerEvent => { - const splitChartValue = getSplitChartValue(rest); - const allSplitAccessors = getAllSplitAccessors(splitAccessors, splitSeriesAccessorFnMap); - const columns = table.columns.reduce>( - columnReducer(null, null, allSplitAccessors, splitChartAccessor), - [] - ); - const row = table.rows.findIndex( - rowFindPredicate(null, null, null, allSplitAccessors, splitChartAccessor, splitChartValue) - ); - const data: ValueClickContext['data']['data'] = columns.map(([column, id]) => ({ - table, - column, - row, - value: table.rows?.[row]?.[id] ?? null, - })); - - return { - name: 'filterBucket', - data: { - negate, - data, - }, + return { + name: 'filterBucket', + data: { + negate, + data, + }, + }; }; -}; /** * Helper function to transform `@elastic/charts` brush event into brush action event */ -export const getBrushFromChartBrushEventFn = ( - table: Datatable, - xAccessor: Accessor | AccessorFn -) => ({ x: selectedRange }: XYBrushArea): BrushTriggerEvent => { - const [start, end] = selectedRange ?? [0, 0]; - const range: [number, number] = [start, end]; - const column = table.columns.findIndex(({ id }) => validateAccessorId(id, xAccessor)); +export const getBrushFromChartBrushEventFn = + (table: Datatable, xAccessor: Accessor | AccessorFn) => + ({ x: selectedRange }: XYBrushArea): BrushTriggerEvent => { + const [start, end] = selectedRange ?? [0, 0]; + const range: [number, number] = [start, end]; + const column = table.columns.findIndex(({ id }) => validateAccessorId(id, xAccessor)); - return { - data: { - table, - column, - range, - }, - name: 'brush', + return { + data: { + table, + column, + range, + }, + name: 'brush', + }; }; -}; diff --git a/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.test.tsx b/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.test.tsx index 1732dd9572b9..04b222257cd2 100644 --- a/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.test.tsx +++ b/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.test.tsx @@ -40,7 +40,7 @@ describe('Legacy (Ace) Console Editor Component Smoke Test', () => { - + diff --git a/src/plugins/console/public/application/contexts/services_context.mock.ts b/src/plugins/console/public/application/contexts/services_context.mock.ts index c4ac8ca25378..c19413bdd041 100644 --- a/src/plugins/console/public/application/contexts/services_context.mock.ts +++ b/src/plugins/console/public/application/contexts/services_context.mock.ts @@ -19,7 +19,7 @@ import { ContextValue } from './services_context'; export const serviceContextMock = { create: (): ContextValue => { - const storage = new StorageMock(({} as unknown) as Storage, 'test'); + const storage = new StorageMock({} as unknown as Storage, 'test'); const http = httpServiceMock.createSetupContract(); const api = createApi({ http }); const esHostService = createEsHostService({ api }); @@ -32,7 +32,7 @@ export const serviceContextMock = { settings: new SettingsMock(storage), history: new HistoryMock(storage), notifications: notificationServiceMock.createSetupContract(), - objectStorageClient: ({} as unknown) as ObjectStorageClient, + objectStorageClient: {} as unknown as ObjectStorageClient, }, docLinkVersion: 'NA', }; diff --git a/src/plugins/console/public/application/models/legacy_core_editor/create_readonly.ts b/src/plugins/console/public/application/models/legacy_core_editor/create_readonly.ts index dc63f0dcd480..2b87331d5f47 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/create_readonly.ts +++ b/src/plugins/console/public/application/models/legacy_core_editor/create_readonly.ts @@ -65,7 +65,7 @@ export function createReadOnlyAceEditor(element: HTMLElement): CustomAceEditor { (function setupSession(session) { session.setMode('ace/mode/text'); - ((session as unknown) as { setFoldStyle: (v: string) => void }).setFoldStyle('markbeginend'); + (session as unknown as { setFoldStyle: (v: string) => void }).setFoldStyle('markbeginend'); session.setTabSize(2); session.setUseWrapMode(true); })(output.getSession()); 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 0ee15f7a559a..ddcb02a0ad45 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 @@ -13,7 +13,7 @@ jest.mock('./mode/worker', () => { // @ts-ignore window.Worker = function () { this.postMessage = () => {}; - ((this as unknown) as { terminate: () => void }).terminate = () => {}; + (this as unknown as { terminate: () => void }).terminate = () => {}; }; // @ts-ignore 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 fa118532aa52..7a90dbe138f1 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 @@ -41,9 +41,7 @@ export class LegacyCoreEditor implements CoreEditor { const session = this.editor.getSession(); session.setMode(new InputMode.Mode()); - ((session as unknown) as { setFoldStyle: (style: string) => void }).setFoldStyle( - 'markbeginend' - ); + (session as unknown as { setFoldStyle: (style: string) => void }).setFoldStyle('markbeginend'); session.setTabSize(2); session.setUseWrapMode(true); @@ -74,7 +72,7 @@ export class LegacyCoreEditor implements CoreEditor { // torn down, e.g. by closing the History tab, and we don't need to do anything further. if (session.bgTokenizer) { // Wait until the bgTokenizer is done running before executing the callback. - if (((session.bgTokenizer as unknown) as { running: boolean }).running) { + if ((session.bgTokenizer as unknown as { running: boolean }).running) { setTimeout(check, checkInterval); } else { resolve(); @@ -225,8 +223,8 @@ export class LegacyCoreEditor implements CoreEditor { isCompleterActive() { return Boolean( - ((this.editor as unknown) as { completer: { activated: unknown } }).completer && - ((this.editor as unknown) as { completer: { activated: unknown } }).completer.activated + (this.editor as unknown as { completer: { activated: unknown } }).completer && + (this.editor as unknown as { completer: { activated: unknown } }).completer.activated ); } 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 692528fb8bce..330e86e17c16 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 @@ -63,7 +63,7 @@ export class AceTokensProvider implements TokensProvider { return null; } - const tokens = (this.session.getTokens(lineNumber - 1) as unknown) as TokenInfo[]; + const tokens = this.session.getTokens(lineNumber - 1) as unknown as TokenInfo[]; if (!tokens || !tokens.length) { // We are inside of the document but have no tokens for this line. Return an empty // array to represent this empty line. @@ -74,7 +74,7 @@ export class AceTokensProvider implements TokensProvider { } getTokenAt(pos: Position): Token | null { - const tokens = (this.session.getTokens(pos.lineNumber - 1) as unknown) as TokenInfo[]; + const tokens = this.session.getTokens(pos.lineNumber - 1) as unknown as TokenInfo[]; if (tokens) { return extractTokenFromAceTokenRow(pos.lineNumber, pos.column, tokens); } diff --git a/src/plugins/console/public/lib/utils/index.ts b/src/plugins/console/public/lib/utils/index.ts index 8b8974f4e2f0..fb0729befa60 100644 --- a/src/plugins/console/public/lib/utils/index.ts +++ b/src/plugins/console/public/lib/utils/index.ts @@ -50,7 +50,8 @@ export function formatRequestBodyDoc(data: string[], indent: boolean) { export function extractWarningMessages(warnings: string) { // pattern for valid warning header - const re = /\d{3} [0-9a-zA-Z!#$%&'*+-.^_`|~]+ \"((?:\t| |!|[\x23-\x5b]|[\x5d-\x7e]|[\x80-\xff]|\\\\|\\")*)\"(?: \"[^"]*\")?/; + 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) => { const match = re.exec(warning); diff --git a/src/plugins/console/server/lib/elasticsearch_proxy_config.ts b/src/plugins/console/server/lib/elasticsearch_proxy_config.ts index bad6942d0c9a..209caaabce26 100644 --- a/src/plugins/console/server/lib/elasticsearch_proxy_config.ts +++ b/src/plugins/console/server/lib/elasticsearch_proxy_config.ts @@ -28,7 +28,8 @@ const createAgent = (legacyConfig: ESConfigForProxy) => { agentOptions.rejectUnauthorized = true; // by default, NodeJS is checking the server identify - agentOptions.checkServerIdentity = (_.noop as unknown) as https.AgentOptions['checkServerIdentity']; + agentOptions.checkServerIdentity = + _.noop as unknown as https.AgentOptions['checkServerIdentity']; break; case 'full': agentOptions.rejectUnauthorized = true; 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 6a514483d14f..8ca5720d559c 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 @@ -102,93 +102,95 @@ function getProxyHeaders(req: KibanaRequest) { return headers; } -export const createHandler = ({ - log, - proxy: { readLegacyESConfig, pathFilters, proxyConfigCollection }, -}: RouteDependencies): RequestHandler => async (ctx, request, response) => { - const { body, query } = request; - const { path, method } = query; - - if (!pathFilters.some((re) => re.test(path))) { - return response.forbidden({ - body: `Error connecting to '${path}':\n\nUnable to send requests to that path.`, - headers: { - 'Content-Type': 'text/plain', - }, - }); - } - - const legacyConfig = await readLegacyESConfig(); - const { hosts } = legacyConfig; - let esIncomingMessage: IncomingMessage; - - for (let idx = 0; idx < hosts.length; ++idx) { - const host = hosts[idx]; - try { - const uri = toURL(host, path); - - // Because this can technically be provided by a settings-defined proxy config, we need to - // preserve these property names to maintain BWC. - const { timeout, agent, headers, rejectUnauthorized } = getRequestConfig( - request.headers, - legacyConfig, - proxyConfigCollection, - uri.toString() - ); - - const requestHeaders = { - ...headers, - ...getProxyHeaders(request), - }; - - esIncomingMessage = await proxyRequest({ - method: method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head', - headers: requestHeaders, - uri, - timeout, - payload: body, - rejectUnauthorized, - agent, +export const createHandler = + ({ + log, + proxy: { readLegacyESConfig, pathFilters, proxyConfigCollection }, + }: RouteDependencies): RequestHandler => + async (ctx, request, response) => { + const { body, query } = request; + const { path, method } = query; + + if (!pathFilters.some((re) => re.test(path))) { + return response.forbidden({ + body: `Error connecting to '${path}':\n\nUnable to send requests to that path.`, + headers: { + 'Content-Type': 'text/plain', + }, }); + } - break; - } catch (e) { - // If we reached here it means we hit a lower level network issue than just, for e.g., a 500. - // We try contacting another node in that case. - log.error(e); - if (idx === hosts.length - 1) { - log.warn(`Could not connect to any configured ES node [${hosts.join(', ')}]`); - return response.customError({ - statusCode: 502, - body: e, + const legacyConfig = await readLegacyESConfig(); + const { hosts } = legacyConfig; + let esIncomingMessage: IncomingMessage; + + for (let idx = 0; idx < hosts.length; ++idx) { + const host = hosts[idx]; + try { + const uri = toURL(host, path); + + // Because this can technically be provided by a settings-defined proxy config, we need to + // preserve these property names to maintain BWC. + const { timeout, agent, headers, rejectUnauthorized } = getRequestConfig( + request.headers, + legacyConfig, + proxyConfigCollection, + uri.toString() + ); + + const requestHeaders = { + ...headers, + ...getProxyHeaders(request), + }; + + esIncomingMessage = await proxyRequest({ + method: method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head', + headers: requestHeaders, + uri, + timeout, + payload: body, + rejectUnauthorized, + agent, }); + + break; + } catch (e) { + // If we reached here it means we hit a lower level network issue than just, for e.g., a 500. + // We try contacting another node in that case. + log.error(e); + if (idx === hosts.length - 1) { + log.warn(`Could not connect to any configured ES node [${hosts.join(', ')}]`); + return response.customError({ + statusCode: 502, + body: e, + }); + } + // Otherwise, try the next host... } - // Otherwise, try the next host... } - } - const { - statusCode, - statusMessage, - headers: { warning }, - } = esIncomingMessage!; + const { + statusCode, + statusMessage, + headers: { warning }, + } = esIncomingMessage!; + + if (method.toUpperCase() !== 'HEAD') { + return response.custom({ + statusCode: statusCode!, + body: esIncomingMessage!, + headers: { + warning: warning || '', + }, + }); + } - if (method.toUpperCase() !== 'HEAD') { return response.custom({ statusCode: statusCode!, - body: esIncomingMessage!, + body: `${statusCode} - ${statusMessage}`, headers: { warning: warning || '', + 'Content-Type': 'text/plain', }, }); - } - - return response.custom({ - statusCode: statusCode!, - body: `${statusCode} - ${statusMessage}`, - headers: { - warning: warning || '', - 'Content-Type': 'text/plain', - }, - }); -}; + }; diff --git a/src/plugins/dashboard/common/embeddable/dashboard_container_persistable_state.test.ts b/src/plugins/dashboard/common/embeddable/dashboard_container_persistable_state.test.ts index 20b2c12ab4b2..93a6bc6f6df4 100644 --- a/src/plugins/dashboard/common/embeddable/dashboard_container_persistable_state.test.ts +++ b/src/plugins/dashboard/common/embeddable/dashboard_container_persistable_state.test.ts @@ -63,9 +63,8 @@ describe('inject/extract by reference panel', () => { it('should extract the saved object panel', () => { const extract = createExtract(persistableStateService); - const { state: extractedState, references: extractedReferences } = extract( - unextractedDashboardState - ); + const { state: extractedState, references: extractedReferences } = + extract(unextractedDashboardState); expect(extractedState).toEqual(dashboardWithExtractedPanel); expect(extractedReferences[0]).toEqual(extractedSavedObjectPanelRef); diff --git a/src/plugins/dashboard/common/embeddable/embeddable_references.test.ts b/src/plugins/dashboard/common/embeddable/embeddable_references.test.ts index 5474c34136c9..d6418c3e1b40 100644 --- a/src/plugins/dashboard/common/embeddable/embeddable_references.test.ts +++ b/src/plugins/dashboard/common/embeddable/embeddable_references.test.ts @@ -23,7 +23,7 @@ const deps: InjectDeps & ExtractDeps = { test('inject/extract panel references', () => { embeddablePersistableStateService.extract.mockImplementationOnce((state) => { - const { HARDCODED_ID, ...restOfState } = (state as unknown) as Record; + const { HARDCODED_ID, ...restOfState } = state as unknown as Record; return { state: restOfState as EmbeddableStateWithType, references: [{ id: HARDCODED_ID as string, name: 'refName', type: 'type' }], diff --git a/src/plugins/dashboard/common/embeddable/embeddable_references.ts b/src/plugins/dashboard/common/embeddable/embeddable_references.ts index 59ea238434fc..09b05dbdcf16 100644 --- a/src/plugins/dashboard/common/embeddable/embeddable_references.ts +++ b/src/plugins/dashboard/common/embeddable/embeddable_references.ts @@ -51,13 +51,11 @@ export function extractPanelsReferences( for (const panel of panels) { const embeddable = convertSavedDashboardPanelToPanelState(panel); - const { - state: embeddableInputWithExtractedReferences, - references, - } = deps.embeddablePersistableStateService.extract({ - ...embeddable.explicitInput, - type: embeddable.type, - }); + const { state: embeddableInputWithExtractedReferences, references } = + deps.embeddablePersistableStateService.extract({ + ...embeddable.explicitInput, + type: embeddable.type, + }); embeddable.explicitInput = omit(embeddableInputWithExtractedReferences, 'type'); const newPanel = convertPanelStateToSavedDashboardPanel(embeddable, panel.version); diff --git a/src/plugins/dashboard/common/saved_dashboard_references.ts b/src/plugins/dashboard/common/saved_dashboard_references.ts index 9757415a7bc3..95c141b5d4e7 100644 --- a/src/plugins/dashboard/common/saved_dashboard_references.ts +++ b/src/plugins/dashboard/common/saved_dashboard_references.ts @@ -26,9 +26,7 @@ const isPre730Panel = (panel: Record): boolean => { return 'version' in panel ? Semver.gt('7.3.0', panel.version) : true; }; -function dashboardAttributesToState( - attributes: SavedObjectAttributes -): { +function dashboardAttributesToState(attributes: SavedObjectAttributes): { state: DashboardContainerStateWithType; panels: SavedDashboardPanel[]; } { @@ -85,7 +83,7 @@ export function extractReferences( return { attributes, references }; } - if (((panels as unknown) as Array>).some(isPre730Panel)) { + if ((panels as unknown as Array>).some(isPre730Panel)) { return pre730ExtractReferences({ attributes, references }, deps); } @@ -94,10 +92,8 @@ export function extractReferences( throw new Error(`"type" attribute is missing from panel "${missingTypeIndex}"`); } - const { - state: extractedState, - references: extractedReferences, - } = deps.embeddablePersistableStateService.extract(state); + const { state: extractedState, references: extractedReferences } = + deps.embeddablePersistableStateService.extract(state); const extractedPanels = panelStatesToPanels( (extractedState as DashboardContainerStateWithType).panels, diff --git a/src/plugins/dashboard/public/application/actions/export_csv_action.test.tsx b/src/plugins/dashboard/public/application/actions/export_csv_action.test.tsx index 2d12d6e79752..3d68f720d1eb 100644 --- a/src/plugins/dashboard/public/application/actions/export_csv_action.test.tsx +++ b/src/plugins/dashboard/public/application/actions/export_csv_action.test.tsx @@ -100,7 +100,7 @@ describe('Export CSV action', () => { test('Should download a compatible Embeddable', async () => { const action = new ExportCSVAction({ core: coreStart, data: dataMock }); - const result = ((await action.execute({ embeddable, asString: true })) as unknown) as + const result = (await action.execute({ embeddable, asString: true })) as unknown as | undefined | Record; expect(result).toEqual({ @@ -118,10 +118,10 @@ describe('Export CSV action', () => { { id: ' 404' }, embeddable.getRoot() as IContainer ); - const result = ((await action.execute({ + const result = (await action.execute({ embeddable: errorEmbeddable, asString: true, - })) as unknown) as undefined | Record; + })) as unknown as undefined | Record; expect(result).toBeUndefined(); }); }); diff --git a/src/plugins/dashboard/public/application/actions/export_csv_action.tsx b/src/plugins/dashboard/public/application/actions/export_csv_action.tsx index cf643fa7d271..cffff7525108 100644 --- a/src/plugins/dashboard/public/application/actions/export_csv_action.tsx +++ b/src/plugins/dashboard/public/application/actions/export_csv_action.tsx @@ -106,7 +106,7 @@ export class ExportCSVAction implements Action { // useful for testing if (context.asString) { - return (content as unknown) as Promise; + return content as unknown as Promise; } if (content) { diff --git a/src/plugins/dashboard/public/application/actions/library_notification_action.test.tsx b/src/plugins/dashboard/public/application/actions/library_notification_action.test.tsx index 3d001913f4c7..95e12918bb8e 100644 --- a/src/plugins/dashboard/public/application/actions/library_notification_action.test.tsx +++ b/src/plugins/dashboard/public/application/actions/library_notification_action.test.tsx @@ -44,10 +44,10 @@ let unlinkAction: UnlinkFromLibraryAction; beforeEach(async () => { coreStart = coreMock.createStart(); - unlinkAction = ({ + unlinkAction = { getDisplayName: () => 'unlink from dat library', execute: jest.fn(), - } as unknown) as UnlinkFromLibraryAction; + } as unknown as UnlinkFromLibraryAction; const containerOptions = { ExitFullScreenButton: () => null, diff --git a/src/plugins/dashboard/public/application/actions/library_notification_popover.test.tsx b/src/plugins/dashboard/public/application/actions/library_notification_popover.test.tsx index 3204a0b38fc8..fab640694cb6 100644 --- a/src/plugins/dashboard/public/application/actions/library_notification_popover.test.tsx +++ b/src/plugins/dashboard/public/application/actions/library_notification_popover.test.tsx @@ -73,10 +73,10 @@ describe('LibraryNotificationPopover', () => { } defaultProps = { - unlinkAction: ({ + unlinkAction: { execute: jest.fn(), getDisplayName: () => 'test unlink', - } as unknown) as LibraryNotificationProps['unlinkAction'], + } as unknown as LibraryNotificationProps['unlinkAction'], displayName: 'test display', context: { embeddable: contactCardEmbeddable }, icon: 'testIcon', 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 fcca31c2a50e..09195f149185 100644 --- a/src/plugins/dashboard/public/application/actions/replace_panel_flyout.tsx +++ b/src/plugins/dashboard/public/application/actions/replace_panel_flyout.tsx @@ -53,9 +53,8 @@ export class ReplacePanelFlyout extends React.Component { public onReplacePanel = async (savedObjectId: string, type: string, name: string) => { const { panelToRemove, container } = this.props; - const { w, h, x, y } = (container.getInput().panels[ - panelToRemove.id - ] as DashboardPanelState).gridData; + const { w, h, x, y } = (container.getInput().panels[panelToRemove.id] as DashboardPanelState) + .gridData; const { id } = await container.addNewEmbeddable(type, { savedObjectId, diff --git a/src/plugins/dashboard/public/application/dashboard_app.tsx b/src/plugins/dashboard/public/application/dashboard_app.tsx index 638b1c83e9dc..dcaf541619d6 100644 --- a/src/plugins/dashboard/public/application/dashboard_app.tsx +++ b/src/plugins/dashboard/public/application/dashboard_app.tsx @@ -34,14 +34,8 @@ export function DashboardApp({ redirectTo, history, }: DashboardAppProps) { - const { - core, - chrome, - embeddable, - onAppLeave, - uiSettings, - data, - } = useKibana().services; + const { core, chrome, embeddable, onAppLeave, uiSettings, data } = + useKibana().services; const kbnUrlStateStorage = useMemo( () => diff --git a/src/plugins/dashboard/public/application/dashboard_router.tsx b/src/plugins/dashboard/public/application/dashboard_router.tsx index 7c538c0f3bf9..cf9152076b84 100644 --- a/src/plugins/dashboard/public/application/dashboard_router.tsx +++ b/src/plugins/dashboard/public/application/dashboard_router.tsx @@ -114,8 +114,8 @@ export async function mountApp({ savedObjectsClient: coreStart.savedObjects.client, savedDashboards: dashboardStart.getSavedDashboardLoader(), savedObjectsTagging: savedObjectsTaggingOss?.getTaggingApi(), - allowByValueEmbeddables: initializerContext.config.get() - .allowByValueEmbeddables, + allowByValueEmbeddables: + initializerContext.config.get().allowByValueEmbeddables, dashboardCapabilities: { hideWriteControls: dashboardConfig.getHideWriteControls(), show: Boolean(coreStart.application.capabilities.dashboard.show), diff --git a/src/plugins/dashboard/public/application/embeddable/dashboard_container_by_value_renderer.tsx b/src/plugins/dashboard/public/application/embeddable/dashboard_container_by_value_renderer.tsx index a4d96b557ac9..4384dc06cee9 100644 --- a/src/plugins/dashboard/public/application/embeddable/dashboard_container_by_value_renderer.tsx +++ b/src/plugins/dashboard/public/application/embeddable/dashboard_container_by_value_renderer.tsx @@ -17,10 +17,13 @@ interface Props { // TODO: add other props as needed } -export const createDashboardContainerByValueRenderer = ({ - factory, -}: { - factory: DashboardContainerFactory; -}): React.FC => (props: Props) => ( - -); +export const createDashboardContainerByValueRenderer = + ({ factory }: { factory: DashboardContainerFactory }): React.FC => + (props: Props) => + ( + + ); diff --git a/src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx b/src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx index 2e984ccfa5ba..19fa1ea1de44 100644 --- a/src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx +++ b/src/plugins/dashboard/public/application/embeddable/dashboard_container_factory.tsx @@ -31,7 +31,8 @@ export type DashboardContainerFactory = EmbeddableFactory< >; export class DashboardContainerFactoryDefinition implements - EmbeddableFactoryDefinition { + EmbeddableFactoryDefinition +{ public readonly isContainerType = true; public readonly type = DASHBOARD_CONTAINER_TYPE; 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 690d1b177cdb..439770569131 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 @@ -33,9 +33,10 @@ const presentationUtil = getStubPluginServices(); const ExitFullScreenButton = () =>
EXIT
; -function getProps( - props?: Partial -): { props: DashboardViewportProps; options: DashboardContainerServices } { +function getProps(props?: Partial): { + props: DashboardViewportProps; + options: DashboardContainerServices; +} { const { setup, doStart } = embeddablePluginMock.createInstance(); setup.registerEmbeddableFactory( CONTACT_CARD_EMBEDDABLE, diff --git a/src/plugins/dashboard/public/application/embeddable/viewport/dashboard_viewport.tsx b/src/plugins/dashboard/public/application/embeddable/viewport/dashboard_viewport.tsx index cbe10438e578..2963d38e0f26 100644 --- a/src/plugins/dashboard/public/application/embeddable/viewport/dashboard_viewport.tsx +++ b/src/plugins/dashboard/public/application/embeddable/viewport/dashboard_viewport.tsx @@ -35,13 +35,8 @@ export class DashboardViewport extends React.Component { - const { - isFullScreenMode, - useMargins, - title, - description, - isEmbeddedExternally, - } = this.props.container.getInput(); + const { isFullScreenMode, useMargins, title, description, isEmbeddedExternally } = + this.props.container.getInput(); if (this.mounted) { this.setState({ isFullScreenMode, @@ -90,14 +80,8 @@ export class DashboardViewport extends React.Component
{ const coreStart = coreMock.createStart(); - const containerOptions = ({ + const containerOptions = { notifications: services.core.notifications, savedObjectMetaData: {} as unknown, ExitFullScreenButton: () => null, @@ -94,7 +94,7 @@ const setupEmbeddableFactory = ( inspector: {} as unknown, uiActions: {} as unknown, http: coreStart.http, - } as unknown) as DashboardContainerServices; + } as unknown as DashboardContainerServices; const dashboardContainer = new DashboardContainer( { ...getSampleDashboardInput(), id }, @@ -103,9 +103,9 @@ const setupEmbeddableFactory = ( const deferEmbeddableCreate = defer(); services.embeddable.getEmbeddableFactory = jest.fn().mockImplementation( () => - (({ + ({ create: () => deferEmbeddableCreate.promise, - } as unknown) as EmbeddableFactory) + } as unknown as EmbeddableFactory) ); const dashboardDestroySpy = jest.spyOn(dashboardContainer, 'destroy'); @@ -230,7 +230,7 @@ describe('Dashboard initial state', () => { savedDashboards.get = jest.fn().mockImplementation((id?: string) => Promise.resolve( getSavedDashboardMock({ - getFilters: () => [({ meta: { test: 'filterMeTimbers' } } as unknown) as Filter], + getFilters: () => [{ meta: { test: 'filterMeTimbers' } } as unknown as Filter], timeRestore: true, timeFrom: 'now-13d', timeTo: 'now', @@ -253,16 +253,16 @@ describe('Dashboard initial state', () => { to: 'now', }); expect(services.data.query.filterManager.setAppFilters).toHaveBeenCalledWith([ - ({ meta: { test: 'filterMeTimbers' } } as unknown) as Filter, + { meta: { test: 'filterMeTimbers' } } as unknown as Filter, ]); }); it('Combines session state and URL state into initial state', async () => { - const dashboardSessionStorage = ({ + const dashboardSessionStorage = { getState: jest .fn() .mockReturnValue({ viewMode: ViewMode.EDIT, description: 'this should be overwritten' }), - } as unknown) as DashboardSessionStorage; + } as unknown as DashboardSessionStorage; const kbnUrlStateStorage = createKbnUrlStateStorage(); kbnUrlStateStorage.set('_a', { description: 'with this' }); const { renderHookResult, embeddableFactoryResult } = renderDashboardAppStateHook({ diff --git a/src/plugins/dashboard/public/application/lib/convert_dashboard_state.ts b/src/plugins/dashboard/public/application/lib/convert_dashboard_state.ts index 524b9f3db6d6..ef961d5783ac 100644 --- a/src/plugins/dashboard/public/application/lib/convert_dashboard_state.ts +++ b/src/plugins/dashboard/public/application/lib/convert_dashboard_state.ts @@ -91,16 +91,8 @@ export const stateToDashboardContainerInput = ({ const { filterManager, timefilter: timefilterService } = queryService; const { timefilter } = timefilterService; - const { - expandedPanelId, - fullScreenMode, - description, - options, - viewMode, - panels, - query, - title, - } = dashboardState; + const { expandedPanelId, fullScreenMode, description, options, viewMode, panels, query, title } = + dashboardState; return { refreshConfig: timefilter.getRefreshInterval(), diff --git a/src/plugins/dashboard/public/application/lib/diff_dashboard_state.ts b/src/plugins/dashboard/public/application/lib/diff_dashboard_state.ts index 8f0c8acf8102..e718c98cb362 100644 --- a/src/plugins/dashboard/public/application/lib/diff_dashboard_state.ts +++ b/src/plugins/dashboard/public/application/lib/diff_dashboard_state.ts @@ -27,8 +27,8 @@ export const diffDashboardContainerInput = ( newInput: DashboardContainerInput ) => { return commonDiffFilters( - (originalInput as unknown) as DashboardDiffCommonFilters, - (newInput as unknown) as DashboardDiffCommonFilters, + originalInput as unknown as DashboardDiffCommonFilters, + newInput as unknown as DashboardDiffCommonFilters, ['searchSessionId', 'lastReloadRequestTime', 'executionContext'] ); }; @@ -38,8 +38,8 @@ export const diffDashboardState = ( newState: DashboardState ): Partial => { const common = commonDiffFilters( - (original as unknown) as DashboardDiffCommonFilters, - (newState as unknown) as DashboardDiffCommonFilters, + original as unknown as DashboardDiffCommonFilters, + newState as unknown as DashboardDiffCommonFilters, ['viewMode', 'panels', 'options', 'savedQuery', 'expandedPanelId'], true ); @@ -55,8 +55,8 @@ const optionsAreEqual = (optionsA: DashboardOptions, optionsB: DashboardOptions) const optionKeys = [...Object.keys(optionsA), ...Object.keys(optionsB)]; for (const key of optionKeys) { if ( - Boolean(((optionsA as unknown) as { [key: string]: boolean })[key]) !== - Boolean(((optionsB as unknown) as { [key: string]: boolean })[key]) + Boolean((optionsA as unknown as { [key: string]: boolean })[key]) !== + Boolean((optionsB as unknown as { [key: string]: boolean })[key]) ) { return false; } @@ -78,8 +78,8 @@ const panelsAreEqual = (panelsA: DashboardPanelMap, panelsB: DashboardPanelMap): if ( Object.keys( commonDiff( - (panelsA[id] as unknown) as DashboardDiffCommon, - (panelsB[id] as unknown) as DashboardDiffCommon, + panelsA[id] as unknown as DashboardDiffCommon, + panelsB[id] as unknown as DashboardDiffCommon, ['panelRefName'] ) ).length > 0 diff --git a/src/plugins/dashboard/public/application/lib/migrate_app_state.test.ts b/src/plugins/dashboard/public/application/lib/migrate_app_state.test.ts index f3470de76bad..3ddcb1265e0b 100644 --- a/src/plugins/dashboard/public/application/lib/migrate_app_state.test.ts +++ b/src/plugins/dashboard/public/application/lib/migrate_app_state.test.ts @@ -29,7 +29,7 @@ test('migrate app state from 6.0', async () => { migrateAppState(appState as any, '8.0'); expect(appState.uiState).toBeUndefined(); - const newPanel = (appState.panels[0] as unknown) as SavedDashboardPanel; + const newPanel = appState.panels[0] as unknown as SavedDashboardPanel; expect(newPanel.gridData.w).toBe(24); expect(newPanel.gridData.h).toBe(15); @@ -62,7 +62,7 @@ test('migrate sort from 6.1', async () => { migrateAppState(appState as any, TARGET_VERSION); expect(appState.uiState).toBeUndefined(); - const newPanel = (appState.panels[0] as unknown) as SavedDashboardPanel; + const newPanel = appState.panels[0] as unknown as SavedDashboardPanel; expect(newPanel.gridData.w).toBe(24); expect(newPanel.gridData.h).toBe(15); expect((newPanel as any).sort).toBeUndefined(); @@ -89,7 +89,7 @@ test('migrates 6.0 even when uiState does not exist', async () => { migrateAppState(appState as any, '8.0'); expect((appState as any).uiState).toBeUndefined(); - const newPanel = (appState.panels[0] as unknown) as SavedDashboardPanel; + const newPanel = appState.panels[0] as unknown as SavedDashboardPanel; expect(newPanel.gridData.w).toBe(24); expect(newPanel.gridData.h).toBe(15); expect((newPanel as any).sort).toBeUndefined(); @@ -119,7 +119,7 @@ test('6.2 migration adjusts w & h without margins', async () => { migrateAppState(appState as any, '8.0'); expect((appState as any).uiState).toBeUndefined(); - const newPanel = (appState.panels[0] as unknown) as SavedDashboardPanel; + const newPanel = appState.panels[0] as unknown as SavedDashboardPanel; expect(newPanel.gridData.w).toBe(28); expect(newPanel.gridData.h).toBe(15); expect(newPanel.gridData.x).toBe(8); @@ -151,7 +151,7 @@ test('6.2 migration adjusts w & h with margins', async () => { migrateAppState(appState as any, '8.0'); expect((appState as any).uiState).toBeUndefined(); - const newPanel = (appState.panels[0] as unknown) as SavedDashboardPanel; + const newPanel = appState.panels[0] as unknown as SavedDashboardPanel; expect(newPanel.gridData.w).toBe(28); expect(newPanel.gridData.h).toBe(12); expect(newPanel.gridData.x).toBe(8); 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 06290205d65d..03e436aea78f 100644 --- a/src/plugins/dashboard/public/application/lib/migrate_app_state.ts +++ b/src/plugins/dashboard/public/application/lib/migrate_app_state.ts @@ -41,14 +41,16 @@ export function migrateAppState( ); } - const panelNeedsMigration = (appState.panels as Array< - | SavedDashboardPanelTo60 - | SavedDashboardPanel610 - | SavedDashboardPanel620 - | SavedDashboardPanel630 - | SavedDashboardPanel640To720 - | SavedDashboardPanel730ToLatest - >).some((panel) => { + const panelNeedsMigration = ( + appState.panels as Array< + | SavedDashboardPanelTo60 + | SavedDashboardPanel610 + | SavedDashboardPanel620 + | SavedDashboardPanel630 + | SavedDashboardPanel640To720 + | SavedDashboardPanel730ToLatest + > + ).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/sync_dashboard_container_input.ts b/src/plugins/dashboard/public/application/lib/sync_dashboard_container_input.ts index 21010158dc46..6d06863d0217 100644 --- a/src/plugins/dashboard/public/application/lib/sync_dashboard_container_input.ts +++ b/src/plugins/dashboard/public/application/lib/sync_dashboard_container_input.ts @@ -44,12 +44,8 @@ type SyncDashboardContainerProps = SyncDashboardContainerCommon & ApplyContainer export const syncDashboardContainerInput = ( syncDashboardContainerProps: SyncDashboardContainerProps ) => { - const { - history, - dashboardContainer, - $onDashboardStateChange, - $triggerDashboardRefresh, - } = syncDashboardContainerProps; + const { history, dashboardContainer, $onDashboardStateChange, $triggerDashboardRefresh } = + syncDashboardContainerProps; const subscriptions = new Subscription(); subscriptions.add( dashboardContainer diff --git a/src/plugins/dashboard/public/application/listing/dashboard_listing.tsx b/src/plugins/dashboard/public/application/listing/dashboard_listing.tsx index 7f72c77009cb..39d6e5fcd088 100644 --- a/src/plugins/dashboard/public/application/listing/dashboard_listing.tsx +++ b/src/plugins/dashboard/public/application/listing/dashboard_listing.tsx @@ -163,12 +163,8 @@ export const DashboardListing = ({ : []; }, [savedObjectsTagging]); - const { - getEntityName, - getTableCaption, - getTableListTitle, - getEntityNamePlural, - } = dashboardListingTable; + const { getEntityName, getTableCaption, getTableListTitle, getEntityNamePlural } = + dashboardListingTable; return ( { return `/app/${appId}${options?.path}`; }), -} as unknown) as ApplicationStart; +} as unknown as ApplicationStart; const history = createHashHistory(); const kbnUrlStateStorage = createKbnUrlStateStorage({ diff --git a/src/plugins/dashboard/public/application/test_helpers/make_default_services.ts b/src/plugins/dashboard/public/application/test_helpers/make_default_services.ts index 41da74dbba77..424ab44f1d67 100644 --- a/src/plugins/dashboard/public/application/test_helpers/make_default_services.ts +++ b/src/plugins/dashboard/public/application/test_helpers/make_default_services.ts @@ -48,13 +48,13 @@ export function makeDefaultServices(): DashboardAppServices { .fn() .mockImplementation((id?: string) => Promise.resolve(getSavedDashboardMock({ id }))); - const dashboardSessionStorage = ({ + const dashboardSessionStorage = { getDashboardIdsWithUnsavedChanges: jest .fn() .mockResolvedValue(['dashboardUnsavedOne', 'dashboardUnsavedTwo']), getState: jest.fn().mockReturnValue(undefined), setState: jest.fn(), - } as unknown) as DashboardSessionStorage; + } as unknown as DashboardSessionStorage; dashboardSessionStorage.clearState = jest.fn(); const defaultCapabilities: DashboardAppCapabilities = { diff --git a/src/plugins/dashboard/public/application/top_nav/editor_menu.tsx b/src/plugins/dashboard/public/application/top_nav/editor_menu.tsx index 74d725bb4d10..0ddd0902b719 100644 --- a/src/plugins/dashboard/public/application/top_nav/editor_menu.tsx +++ b/src/plugins/dashboard/public/application/top_nav/editor_menu.tsx @@ -39,13 +39,8 @@ interface FactoryGroup { } export const EditorMenu = ({ dashboardContainer, createNewVisType }: Props) => { - const { - core, - embeddable, - visualizations, - usageCollection, - uiSettings, - } = useKibana().services; + const { core, embeddable, visualizations, usageCollection, uiSettings } = + useKibana().services; const IS_DARK_THEME = uiSettings.get('theme:darkMode'); diff --git a/src/plugins/dashboard/public/application/top_nav/show_share_modal.tsx b/src/plugins/dashboard/public/application/top_nav/show_share_modal.tsx index b9c77dec87b6..879afd4b9d30 100644 --- a/src/plugins/dashboard/public/application/top_nav/show_share_modal.tsx +++ b/src/plugins/dashboard/public/application/top_nav/show_share_modal.tsx @@ -38,7 +38,7 @@ interface ShowShareModalProps { export const showPublicUrlSwitch = (anonymousUserCapabilities: Capabilities) => { if (!anonymousUserCapabilities.dashboard) return false; - const dashboard = (anonymousUserCapabilities.dashboard as unknown) as DashboardAppCapabilities; + const dashboard = anonymousUserCapabilities.dashboard as unknown as DashboardAppCapabilities; return !!dashboard.show; }; diff --git a/src/plugins/dashboard/public/plugin.tsx b/src/plugins/dashboard/public/plugin.tsx index 1973fd4dbe39..a8a60dae5078 100644 --- a/src/plugins/dashboard/public/plugin.tsx +++ b/src/plugins/dashboard/public/plugin.tsx @@ -146,7 +146,8 @@ export interface DashboardStart { export class DashboardPlugin implements - Plugin { + Plugin +{ constructor(private initializerContext: PluginInitializerContext) {} private appStateUpdater = new BehaviorSubject(() => ({})); @@ -164,7 +165,8 @@ export class DashboardPlugin core: CoreSetup, { share, embeddable, home, urlForwarding, data, usageCollection }: DashboardSetupDependencies ): DashboardSetup { - this.dashboardFeatureFlagConfig = this.initializerContext.config.get(); + this.dashboardFeatureFlagConfig = + this.initializerContext.config.get(); const startServices = core.getStartServices(); if (share) { @@ -418,9 +420,8 @@ export class DashboardPlugin return { getSavedDashboardLoader: () => savedDashboardLoader, getDashboardContainerByValueRenderer: () => { - const dashboardContainerFactory = plugins.embeddable.getEmbeddableFactory( - DASHBOARD_CONTAINER_TYPE - ); + const dashboardContainerFactory = + plugins.embeddable.getEmbeddableFactory(DASHBOARD_CONTAINER_TYPE); if (!dashboardContainerFactory) { throw new Error(`${DASHBOARD_CONTAINER_TYPE} Embeddable Factory not found`); diff --git a/src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts b/src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts index 7c056e04c1cd..b81cf57bbc96 100644 --- a/src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts +++ b/src/plugins/dashboard/public/saved_dashboards/saved_dashboard.ts @@ -127,5 +127,5 @@ export function createSavedDashboardClass( // Unfortunately this throws a typescript error without the casting. I think it's due to the // convoluted way SavedObjects are created. - return (SavedDashboard as unknown) as new (id: string) => DashboardSavedObject; + return SavedDashboard as unknown as new (id: string) => DashboardSavedObject; } diff --git a/src/plugins/dashboard/server/plugin.ts b/src/plugins/dashboard/server/plugin.ts index 6c1eea29f529..898c1745efcc 100644 --- a/src/plugins/dashboard/server/plugin.ts +++ b/src/plugins/dashboard/server/plugin.ts @@ -30,7 +30,8 @@ interface SetupDeps { } export class DashboardPlugin - implements Plugin { + implements Plugin +{ private readonly logger: Logger; constructor(initializerContext: PluginInitializerContext) { diff --git a/src/plugins/dashboard/server/saved_objects/dashboard_migrations.ts b/src/plugins/dashboard/server/saved_objects/dashboard_migrations.ts index 7848a2e46487..e0cd410ce5e8 100644 --- a/src/plugins/dashboard/server/saved_objects/dashboard_migrations.ts +++ b/src/plugins/dashboard/server/saved_objects/dashboard_migrations.ts @@ -134,7 +134,7 @@ function createExtractPanelReferencesMigration( const injectedAttributes = injectReferences( { - attributes: (doc.attributes as unknown) as SavedObjectAttributes, + attributes: doc.attributes as unknown as SavedObjectAttributes, references, }, { embeddablePersistableStateService: deps.embeddable } @@ -159,56 +159,59 @@ type ValueOrReferenceInput = SavedObjectEmbeddableInput & { }; // Runs the embeddable migrations on each panel -const migrateByValuePanels = ( - migrate: MigrateFunction, - version: string -): SavedObjectMigrationFn => (doc: any) => { - const { attributes } = doc; - // Skip if panelsJSON is missing otherwise this will cause saved object import to fail when - // importing objects without panelsJSON. At development time of this, there is no guarantee each saved - // object has panelsJSON in all previous versions of kibana. - if (typeof attributes?.panelsJSON !== 'string') { - return doc; - } - const panels = JSON.parse(attributes.panelsJSON) as SavedDashboardPanel[]; - // Same here, prevent failing saved object import if ever panels aren't an array. - if (!Array.isArray(panels)) { - return doc; - } - const newPanels: SavedDashboardPanel[] = []; - panels.forEach((panel) => { - // Convert each panel into a state that can be passed to EmbeddablesSetup.migrate - const originalPanelState = convertSavedDashboardPanelToPanelState(panel); - - // saved vis is used to store by value input for Visualize. This should eventually be renamed to `attributes` to align with Lens and Maps - if (originalPanelState.explicitInput.attributes || originalPanelState.explicitInput.savedVis) { - // If this panel is by value, migrate the state using embeddable migrations - const migratedInput = migrate({ - ...originalPanelState.explicitInput, - type: originalPanelState.type, - }); - // Convert the embeddable state back into the panel shape - newPanels.push( - convertPanelStateToSavedDashboardPanel( - { - ...originalPanelState, - explicitInput: { ...migratedInput, id: migratedInput.id as string }, - }, - version - ) - ); - } else { - newPanels.push(panel); +const migrateByValuePanels = + (migrate: MigrateFunction, version: string): SavedObjectMigrationFn => + (doc: any) => { + const { attributes } = doc; + // Skip if panelsJSON is missing otherwise this will cause saved object import to fail when + // importing objects without panelsJSON. At development time of this, there is no guarantee each saved + // object has panelsJSON in all previous versions of kibana. + if (typeof attributes?.panelsJSON !== 'string') { + return doc; } - }); - return { - ...doc, - attributes: { - ...attributes, - panelsJSON: JSON.stringify(newPanels), - }, + const panels = JSON.parse(attributes.panelsJSON) as SavedDashboardPanel[]; + // Same here, prevent failing saved object import if ever panels aren't an array. + if (!Array.isArray(panels)) { + return doc; + } + const newPanels: SavedDashboardPanel[] = []; + panels.forEach((panel) => { + // Convert each panel into a state that can be passed to EmbeddablesSetup.migrate + const originalPanelState = + convertSavedDashboardPanelToPanelState(panel); + + // saved vis is used to store by value input for Visualize. This should eventually be renamed to `attributes` to align with Lens and Maps + if ( + originalPanelState.explicitInput.attributes || + originalPanelState.explicitInput.savedVis + ) { + // If this panel is by value, migrate the state using embeddable migrations + const migratedInput = migrate({ + ...originalPanelState.explicitInput, + type: originalPanelState.type, + }); + // Convert the embeddable state back into the panel shape + newPanels.push( + convertPanelStateToSavedDashboardPanel( + { + ...originalPanelState, + explicitInput: { ...migratedInput, id: migratedInput.id as string }, + }, + version + ) + ); + } else { + newPanels.push(panel); + } + }); + return { + ...doc, + attributes: { + ...attributes, + panelsJSON: JSON.stringify(newPanels), + }, + }; }; -}; export interface DashboardSavedObjectTypeMigrationsDeps { embeddable: EmbeddableSetup; diff --git a/src/plugins/dashboard/server/saved_objects/migrate_match_all_query.test.ts b/src/plugins/dashboard/server/saved_objects/migrate_match_all_query.test.ts index 645c518439dd..bf8d8fb22584 100644 --- a/src/plugins/dashboard/server/saved_objects/migrate_match_all_query.test.ts +++ b/src/plugins/dashboard/server/saved_objects/migrate_match_all_query.test.ts @@ -9,7 +9,7 @@ import { migrateMatchAllQuery } from './migrate_match_all_query'; import { SavedObjectMigrationContext, SavedObjectMigrationFn } from 'kibana/server'; -const savedObjectMigrationContext = (null as unknown) as SavedObjectMigrationContext; +const savedObjectMigrationContext = null as unknown as SavedObjectMigrationContext; describe('migrate match_all query', () => { test('should migrate obsolete match_all query', () => { diff --git a/src/plugins/dashboard/server/saved_objects/replace_index_pattern_reference.test.ts b/src/plugins/dashboard/server/saved_objects/replace_index_pattern_reference.test.ts index 01207fb4e340..41dbcbe05d44 100644 --- a/src/plugins/dashboard/server/saved_objects/replace_index_pattern_reference.test.ts +++ b/src/plugins/dashboard/server/saved_objects/replace_index_pattern_reference.test.ts @@ -10,7 +10,7 @@ import type { SavedObjectMigrationContext, SavedObjectMigrationFn } from 'kibana import { replaceIndexPatternReference } from './replace_index_pattern_reference'; describe('replaceIndexPatternReference', () => { - const savedObjectMigrationContext = (null as unknown) as SavedObjectMigrationContext; + const savedObjectMigrationContext = null as unknown as SavedObjectMigrationContext; test('should replace index_pattern to index-pattern', () => { const migratedDoc = replaceIndexPatternReference( diff --git a/src/plugins/dashboard/server/usage/dashboard_telemetry.test.ts b/src/plugins/dashboard/server/usage/dashboard_telemetry.test.ts index 60f1f7eb0955..974d80f9c0f4 100644 --- a/src/plugins/dashboard/server/usage/dashboard_telemetry.test.ts +++ b/src/plugins/dashboard/server/usage/dashboard_telemetry.test.ts @@ -14,42 +14,42 @@ import { collectByValueLensInfo, } from './dashboard_telemetry'; -const visualizationType1ByValue = ({ +const visualizationType1ByValue = { embeddableConfig: { savedVis: { type: 'type1', }, }, type: 'visualization', -} as unknown) as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel730ToLatest; -const visualizationType2ByValue = ({ +const visualizationType2ByValue = { embeddableConfig: { savedVis: { type: 'type2', }, }, type: 'visualization', -} as unknown) as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel730ToLatest; const visualizationType2ByReference = { ...visualizationType2ByValue, id: '11111', }; -const lensTypeAByValue = ({ +const lensTypeAByValue = { type: 'lens', embeddableConfig: { attributes: { visualizationType: 'a', }, }, -} as unknown) as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel730ToLatest; const lensTypeAByReference = { ...lensTypeAByValue, id: '22222', }; -const lensXYSeriesA = ({ +const lensXYSeriesA = { type: 'lens', embeddableConfig: { attributes: { @@ -61,9 +61,9 @@ const lensXYSeriesA = ({ }, }, }, -} as unknown) as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel730ToLatest; -const lensXYSeriesB = ({ +const lensXYSeriesB = { type: 'lens', embeddableConfig: { attributes: { @@ -91,7 +91,7 @@ const lensXYSeriesB = ({ }, }, }, -} as unknown) as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel730ToLatest; describe('dashboard telemetry', () => { it('collects information about dashboard panels', () => { @@ -126,10 +126,10 @@ describe('dashboard telemetry', () => { }); it('handles misshapen visualization panels without errors', () => { - const badVisualizationPanel = ({ + const badVisualizationPanel = { embeddableConfig: {}, type: 'visualization', - } as unknown) as SavedDashboardPanel730ToLatest; + } as unknown as SavedDashboardPanel730ToLatest; const panels = [badVisualizationPanel, visualizationType1ByValue]; @@ -164,12 +164,12 @@ describe('dashboard telemetry', () => { }); it('handles misshapen lens panels', () => { - const badPanel = ({ + const badPanel = { type: 'lens', embeddableConfig: { oops: 'no visualization type', }, - } as unknown) as SavedDashboardPanel730ToLatest; + } as unknown as SavedDashboardPanel730ToLatest; const panels = [badPanel, lensTypeAByValue]; diff --git a/src/plugins/dashboard/server/usage/dashboard_telemetry.ts b/src/plugins/dashboard/server/usage/dashboard_telemetry.ts index fb1ddff469f5..8d6ebeab08a9 100644 --- a/src/plugins/dashboard/server/usage/dashboard_telemetry.ts +++ b/src/plugins/dashboard/server/usage/dashboard_telemetry.ts @@ -173,9 +173,9 @@ export async function collectDashboardTelemetry( embeddablePersistableStateService: embeddableService, }); - const panels = (JSON.parse( + const panels = JSON.parse( attributes.panelsJSON as string - ) as unknown) as SavedDashboardPanel730ToLatest[]; + ) as unknown as SavedDashboardPanel730ToLatest[]; collectForPanels(panels, collectorData); collectEmbeddableData(panels, collectorData, embeddableService); diff --git a/src/plugins/dashboard/server/usage/find_by_value_embeddables.test.ts b/src/plugins/dashboard/server/usage/find_by_value_embeddables.test.ts index 303d48edc212..8a3cdd71539f 100644 --- a/src/plugins/dashboard/server/usage/find_by_value_embeddables.test.ts +++ b/src/plugins/dashboard/server/usage/find_by_value_embeddables.test.ts @@ -9,23 +9,23 @@ import { SavedDashboardPanel730ToLatest } from '../../common'; import { findByValueEmbeddables } from './find_by_value_embeddables'; -const visualizationByValue = ({ +const visualizationByValue = { embeddableConfig: { value: 'visualization-by-value', }, type: 'visualization', -} as unknown) as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel730ToLatest; -const mapByValue = ({ +const mapByValue = { embeddableConfig: { value: 'map-by-value', }, type: 'map', -} as unknown) as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel730ToLatest; -const embeddableByRef = ({ +const embeddableByRef = { panelRefName: 'panel_ref_1', -} as unknown) as SavedDashboardPanel730ToLatest; +} as unknown as SavedDashboardPanel730ToLatest; describe('findByValueEmbeddables', () => { it('finds the by value embeddables for the given type', async () => { diff --git a/src/plugins/dashboard/server/usage/find_by_value_embeddables.ts b/src/plugins/dashboard/server/usage/find_by_value_embeddables.ts index 27bbe79a009f..c3c32fbcd6a6 100644 --- a/src/plugins/dashboard/server/usage/find_by_value_embeddables.ts +++ b/src/plugins/dashboard/server/usage/find_by_value_embeddables.ts @@ -20,9 +20,9 @@ export const findByValueEmbeddables = async ( return dashboards.saved_objects .map((dashboard) => { try { - return (JSON.parse( + return JSON.parse( dashboard.attributes.panelsJSON as string - ) as unknown) as SavedDashboardPanel730ToLatest[]; + ) as unknown as SavedDashboardPanel730ToLatest[]; } catch (exception) { return []; } diff --git a/src/plugins/data/common/data_views/data_views/index_pattern.test.ts b/src/plugins/data/common/data_views/data_views/index_pattern.test.ts index a12d4897fe11..5fd1d0d051ac 100644 --- a/src/plugins/data/common/data_views/data_views/index_pattern.test.ts +++ b/src/plugins/data/common/data_views/data_views/index_pattern.test.ts @@ -289,17 +289,17 @@ describe('IndexPattern', () => { describe('toSpec', () => { test('should match snapshot', () => { - const formatter = ({ + const formatter = { toJSON: () => ({ id: 'number', params: { pattern: '$0,0.[00]' } }), - } as unknown) as FieldFormat; + } as unknown as FieldFormat; indexPattern.getFormatterForField = () => formatter; expect(indexPattern.toSpec()).toMatchSnapshot(); }); test('can restore from spec', async () => { - const formatter = ({ + const formatter = { toJSON: () => ({ id: 'number', params: { pattern: '$0,0.[00]' } }), - } as unknown) as FieldFormat; + } as unknown as FieldFormat; indexPattern.getFormatterForField = () => formatter; const spec = indexPattern.toSpec(); const restoredPattern = new IndexPattern({ diff --git a/src/plugins/data/common/data_views/data_views/index_patterns.test.ts b/src/plugins/data/common/data_views/data_views/index_patterns.test.ts index 420970b8c5d2..cdc7ca3b9dce 100644 --- a/src/plugins/data/common/data_views/data_views/index_patterns.test.ts +++ b/src/plugins/data/common/data_views/data_views/index_patterns.test.ts @@ -86,11 +86,11 @@ describe('IndexPatterns', () => { }); indexPatterns = new DataViewsService({ - uiSettings: ({ + uiSettings: { get: () => Promise.resolve(false), getAll: () => {}, - } as any) as UiSettingsCommon, - savedObjectsClient: (savedObjectsClient as unknown) as SavedObjectsClientCommon, + } as any as UiSettingsCommon, + savedObjectsClient: savedObjectsClient as unknown as SavedObjectsClientCommon, apiClient: createFieldsFetcher(), fieldFormats, onNotification: () => {}, @@ -234,9 +234,9 @@ describe('IndexPatterns', () => { const title = 'kibana-*'; indexPatterns.createSavedObject = jest.fn(() => - Promise.resolve(({ + Promise.resolve({ id: 'id', - } as unknown) as DataView) + } as unknown as DataView) ); indexPatterns.setDefault = jest.fn(); await indexPatterns.createAndSave({ title }); diff --git a/src/plugins/data/common/data_views/field.stub.ts b/src/plugins/data/common/data_views/field.stub.ts index bafd3fc2fc35..03bb0dee33db 100644 --- a/src/plugins/data/common/data_views/field.stub.ts +++ b/src/plugins/data/common/data_views/field.stub.ts @@ -404,6 +404,6 @@ export const stubLogstashFieldSpecMap: Record = { }, }; -export const stubLogstashFields: IndexPatternField[] = Object.values( - stubLogstashFieldSpecMap -).map((spec) => createIndexPatternFieldStub({ spec })); +export const stubLogstashFields: IndexPatternField[] = Object.values(stubLogstashFieldSpecMap).map( + (spec) => createIndexPatternFieldStub({ spec }) +); diff --git a/src/plugins/data/common/data_views/fields/index_pattern_field.test.ts b/src/plugins/data/common/data_views/fields/index_pattern_field.test.ts index 18d331b4e135..906cb0ad1bad 100644 --- a/src/plugins/data/common/data_views/fields/index_pattern_field.test.ts +++ b/src/plugins/data/common/data_views/fields/index_pattern_field.test.ts @@ -38,10 +38,10 @@ describe('Field', function () { scripted: true, subType: { multi: { parent: 'parent' }, nested: { path: 'path' } }, displayName: 'displayName', - indexPattern: ({ + indexPattern: { fieldFormatMap: { name: {}, _source: {}, _score: {}, _id: {} }, - } as unknown) as IndexPattern, - $$spec: ({} as unknown) as FieldSpec, + } as unknown as IndexPattern, + $$spec: {} as unknown as FieldSpec, conflictDescriptions: { a: ['b', 'c'], d: ['e'] }, runtimeField: { type: 'keyword' as RuntimeField['type'], @@ -153,14 +153,14 @@ describe('Field', function () { it('spec snapshot', () => { const field = new IndexPatternField(fieldValues); const getFormatterForField = () => - (({ + ({ toJSON: () => ({ id: 'number', params: { pattern: '$0,0.[00]', }, }), - } as unknown) as FieldFormat); + } as unknown as FieldFormat); expect(field.toSpec({ getFormatterForField })).toMatchSnapshot(); }); }); diff --git a/src/plugins/data/common/es_query/get_es_query_config.test.ts b/src/plugins/data/common/es_query/get_es_query_config.test.ts index 5513f2649265..984d964ea9b3 100644 --- a/src/plugins/data/common/es_query/get_es_query_config.test.ts +++ b/src/plugins/data/common/es_query/get_es_query_config.test.ts @@ -11,7 +11,7 @@ import { getEsQueryConfig } from './get_es_query_config'; import { IUiSettingsClient } from 'kibana/public'; import { UI_SETTINGS } from '..'; -const config = ({ +const config = { get(item: string) { return get(config, item); }, @@ -27,7 +27,7 @@ const config = ({ 'dateFormat:tz': { dateFormatTZ: 'Browser', }, -} as unknown) as IUiSettingsClient; +} as unknown as IUiSettingsClient; describe('getEsQueryConfig', () => { test('should return the parameters of an Elasticsearch query config requested', () => { diff --git a/src/plugins/data/common/query/timefilter/get_time.test.ts b/src/plugins/data/common/query/timefilter/get_time.test.ts index 70f6f418cc73..fc35eeed48e6 100644 --- a/src/plugins/data/common/query/timefilter/get_time.test.ts +++ b/src/plugins/data/common/query/timefilter/get_time.test.ts @@ -18,7 +18,7 @@ describe('get_time', () => { const clock = sinon.useFakeTimers(moment.utc([2000, 1, 1, 0, 0, 0, 0]).valueOf()); const filter = getTime( - ({ + { id: 'test', title: 'test', timeFieldName: 'date', @@ -32,7 +32,7 @@ describe('get_time', () => { filterable: true, }, ], - } as unknown) as IIndexPattern, + } as unknown as IIndexPattern, { from: 'now-60y', to: 'now' } ) as RangeFilter; expect(filter.range.date).toEqual({ @@ -47,7 +47,7 @@ describe('get_time', () => { const clock = sinon.useFakeTimers(moment.utc([2000, 1, 1, 0, 0, 0, 0]).valueOf()); const filter = getTime( - ({ + { id: 'test', title: 'test', timeFieldName: 'date', @@ -69,7 +69,7 @@ describe('get_time', () => { filterable: true, }, ], - } as unknown) as IIndexPattern, + } as unknown as IIndexPattern, { from: 'now-60y', to: 'now' }, { fieldName: 'myCustomDate' } ) as RangeFilter; @@ -84,7 +84,7 @@ describe('get_time', () => { describe('getRelativeTime', () => { test('do not coerce relative time to absolute time when given flag', () => { const filter = getRelativeTime( - ({ + { id: 'test', title: 'test', timeFieldName: 'date', @@ -106,7 +106,7 @@ describe('get_time', () => { filterable: true, }, ], - } as unknown) as IIndexPattern, + } as unknown as IIndexPattern, { from: 'now-60y', to: 'now' }, { fieldName: 'myCustomDate' } ) as RangeFilter; @@ -120,7 +120,7 @@ describe('get_time', () => { test('do not coerce relative time to absolute time when given flag - with mixed from and to times', () => { const clock = sinon.useFakeTimers(moment.utc().valueOf()); const filter = getRelativeTime( - ({ + { id: 'test', title: 'test', timeFieldName: 'date', @@ -142,7 +142,7 @@ describe('get_time', () => { filterable: true, }, ], - } as unknown) as IIndexPattern, + } as unknown as IIndexPattern, { from: '2020-09-01T08:30:00.000Z', to: 'now', diff --git a/src/plugins/data/common/search/aggs/agg_config.test.ts b/src/plugins/data/common/search/aggs/agg_config.test.ts index 2cb875eb9c04..93903ee0c321 100644 --- a/src/plugins/data/common/search/aggs/agg_config.test.ts +++ b/src/plugins/data/common/search/aggs/agg_config.test.ts @@ -52,10 +52,10 @@ describe('AggConfig', () => { indexPattern = { id: '1234', title: 'logstash-*', - fields: ({ + fields: { getByName: (name: string) => fields.find((f) => f.name === name), filter: () => fields, - } as unknown) as IndexPattern['fields'], + } as unknown as IndexPattern['fields'], getFormatterForField: (field: IndexPatternField) => ({ toJSON: () => ({}), }), @@ -247,7 +247,7 @@ describe('AggConfig', () => { it('fails when the list is not defined', () => { expect(() => { - AggConfig.nextId((undefined as unknown) as IAggConfig[]); + AggConfig.nextId(undefined as unknown as IAggConfig[]); }).toThrowError(); }); }); @@ -847,7 +847,7 @@ describe('AggConfig', () => { }); it('empty label if the type is not defined', () => { - aggConfig.type = (undefined as unknown) as AggType; + aggConfig.type = undefined as unknown as AggType; const label = aggConfig.makeLabel(); expect(label).toBe(''); }); diff --git a/src/plugins/data/common/search/aggs/agg_configs.test.ts b/src/plugins/data/common/search/aggs/agg_configs.test.ts index 59b306c2df0b..104cd3b2815b 100644 --- a/src/plugins/data/common/search/aggs/agg_configs.test.ts +++ b/src/plugins/data/common/search/aggs/agg_configs.test.ts @@ -627,9 +627,7 @@ describe('AggConfigs', () => { }, }, }; - const mergedResponse = ac.postFlightTransform( - (response as unknown) as IEsSearchResponse - ); + const mergedResponse = ac.postFlightTransform(response as unknown as IEsSearchResponse); expect(mergedResponse.rawResponse).toEqual({ aggregations: { '1': { @@ -724,9 +722,7 @@ describe('AggConfigs', () => { }, }, }; - const mergedResponse = ac.postFlightTransform( - (response as unknown) as IEsSearchResponse - ); + const mergedResponse = ac.postFlightTransform(response as unknown as IEsSearchResponse); expect(mergedResponse.rawResponse).toEqual({ aggregations: { '1': { diff --git a/src/plugins/data/common/search/aggs/agg_configs.ts b/src/plugins/data/common/search/aggs/agg_configs.ts index 08a7022ee894..cb9ac56b99cd 100644 --- a/src/plugins/data/common/search/aggs/agg_configs.ts +++ b/src/plugins/data/common/search/aggs/agg_configs.ts @@ -358,9 +358,9 @@ export class AggConfigs { } getTimeShiftInterval(): moment.Duration | undefined { - const splitAgg = (this.getAll().filter( - (agg) => agg.type.type === AggGroupNames.Buckets - ) as IBucketAggConfig[]).find((agg) => agg.type.splitForTimeShift(agg, this)); + const splitAgg = ( + this.getAll().filter((agg) => agg.type.type === AggGroupNames.Buckets) as IBucketAggConfig[] + ).find((agg) => agg.type.splitForTimeShift(agg, this)); return splitAgg?.type.getTimeShiftInterval(splitAgg); } diff --git a/src/plugins/data/common/search/aggs/agg_type.test.ts b/src/plugins/data/common/search/aggs/agg_type.test.ts index 01f38697e4db..cdcf096a95f6 100644 --- a/src/plugins/data/common/search/aggs/agg_type.test.ts +++ b/src/plugins/data/common/search/aggs/agg_type.test.ts @@ -13,7 +13,7 @@ describe('AggType Class', () => { describe('constructor', () => { test("requires a valid config object as it's first param", () => { expect(() => { - const aggConfig: AggTypeConfig = (undefined as unknown) as AggTypeConfig; + const aggConfig: AggTypeConfig = undefined as unknown as AggTypeConfig; new AggType(aggConfig); }).toThrowError(); }); @@ -136,7 +136,7 @@ describe('AggType Class', () => { describe('getSerializedFormat', () => { test('returns the default serialized field format if it exists', () => { - const aggConfig = ({ + const aggConfig = { params: { field: { format: { @@ -147,7 +147,7 @@ describe('AggType Class', () => { aggConfigs: { indexPattern: { getFormatterForField: () => ({ toJSON: () => ({ id: 'format' }) }) }, }, - } as unknown) as IAggConfig; + } as unknown as IAggConfig; const aggType = new AggType({ name: 'name', expressionName: 'aggName', @@ -161,9 +161,9 @@ describe('AggType Class', () => { }); test('returns an empty object if a field param does not exist', () => { - const aggConfig = ({ + const aggConfig = { params: {}, - } as unknown) as IAggConfig; + } as unknown as IAggConfig; const aggType = new AggType({ name: 'name', expressionName: 'aggName', @@ -173,7 +173,7 @@ describe('AggType Class', () => { }); test('uses a custom getSerializedFormat function if defined', () => { - const aggConfig = ({ + const aggConfig = { params: { field: { format: { @@ -181,7 +181,7 @@ describe('AggType Class', () => { }, }, }, - } as unknown) as IAggConfig; + } as unknown as IAggConfig; const getSerializedFormat = jest.fn().mockReturnValue({ id: 'hello' }); const aggType = new AggType({ name: 'name', diff --git a/src/plugins/data/common/search/aggs/buckets/_terms_other_bucket_helper.test.ts b/src/plugins/data/common/search/aggs/buckets/_terms_other_bucket_helper.test.ts index 9d61178405b5..215d3ce13f55 100644 --- a/src/plugins/data/common/search/aggs/buckets/_terms_other_bucket_helper.test.ts +++ b/src/plugins/data/common/search/aggs/buckets/_terms_other_bucket_helper.test.ts @@ -42,7 +42,7 @@ const indexPattern = { ], } as IndexPattern; -indexPattern.fields.getByName = (name) => (({ name } as unknown) as IndexPatternField); +indexPattern.fields.getByName = (name) => ({ name } as unknown as IndexPatternField); const singleTerm = { aggs: [ diff --git a/src/plugins/data/common/search/aggs/buckets/terms.test.ts b/src/plugins/data/common/search/aggs/buckets/terms.test.ts index 6345e29b6fbe..50aa4eb2b035 100644 --- a/src/plugins/data/common/search/aggs/buckets/terms.test.ts +++ b/src/plugins/data/common/search/aggs/buckets/terms.test.ts @@ -55,7 +55,7 @@ describe('Terms Agg', () => { ], } as IndexPattern; - indexPattern.fields.getByName = (name) => (({ name } as unknown) as IndexPatternField); + indexPattern.fields.getByName = (name) => ({ name } as unknown as IndexPatternField); indexPattern.fields.filter = () => indexPattern.fields; return new AggConfigs( @@ -257,7 +257,7 @@ describe('Terms Agg', () => { ], } as IndexPattern; - indexPattern.fields.getByName = (name) => (({ name } as unknown) as IndexPatternField); + indexPattern.fields.getByName = (name) => ({ name } as unknown as IndexPatternField); indexPattern.fields.filter = () => indexPattern.fields; const aggConfigs = new AggConfigs( diff --git a/src/plugins/data/common/search/aggs/metrics/lib/make_nested_label.test.ts b/src/plugins/data/common/search/aggs/metrics/lib/make_nested_label.test.ts index c8468d8c35ae..d5ee3e513ec5 100644 --- a/src/plugins/data/common/search/aggs/metrics/lib/make_nested_label.test.ts +++ b/src/plugins/data/common/search/aggs/metrics/lib/make_nested_label.test.ts @@ -11,7 +11,7 @@ import { IMetricAggConfig } from '../metric_agg_type'; describe('metric agg make_nested_label', () => { const generateAggConfig = (metricLabel: string): IMetricAggConfig => { - return ({ + return { params: { customMetric: { makeLabel: () => { @@ -22,7 +22,7 @@ describe('metric agg make_nested_label', () => { getParam(this: IMetricAggConfig, key: string) { return this.params[key]; }, - } as unknown) as IMetricAggConfig; + } as unknown as IMetricAggConfig; }; it('should return a metric label with prefix', () => { diff --git a/src/plugins/data/common/search/aggs/metrics/lib/parent_pipeline_agg_helper.ts b/src/plugins/data/common/search/aggs/metrics/lib/parent_pipeline_agg_helper.ts index ac2beaf57425..478b8309272e 100644 --- a/src/plugins/data/common/search/aggs/metrics/lib/parent_pipeline_agg_helper.ts +++ b/src/plugins/data/common/search/aggs/metrics/lib/parent_pipeline_agg_helper.ts @@ -50,9 +50,8 @@ export const parentPipelineAggHelper = { metricAgg.id = termsAgg.id + '-metric'; return metricAgg; }, - modifyAggConfigOnSearchRequestStart: forwardModifyAggConfigOnSearchRequestStart( - 'customMetric' - ), + modifyAggConfigOnSearchRequestStart: + forwardModifyAggConfigOnSearchRequestStart('customMetric'), write: noop, }, { diff --git a/src/plugins/data/common/search/aggs/metrics/lib/sibling_pipeline_agg_helper.ts b/src/plugins/data/common/search/aggs/metrics/lib/sibling_pipeline_agg_helper.ts index 2564fcb7a002..da110c1abb7e 100644 --- a/src/plugins/data/common/search/aggs/metrics/lib/sibling_pipeline_agg_helper.ts +++ b/src/plugins/data/common/search/aggs/metrics/lib/sibling_pipeline_agg_helper.ts @@ -53,9 +53,8 @@ export const siblingPipelineAggHelper = { orderAgg.id = agg.id + '-bucket'; return orderAgg; }, - modifyAggConfigOnSearchRequestStart: forwardModifyAggConfigOnSearchRequestStart( - 'customBucket' - ), + modifyAggConfigOnSearchRequestStart: + forwardModifyAggConfigOnSearchRequestStart('customBucket'), write: () => {}, }, { @@ -68,9 +67,8 @@ export const siblingPipelineAggHelper = { orderAgg.id = agg.id + '-metric'; return orderAgg; }, - modifyAggConfigOnSearchRequestStart: forwardModifyAggConfigOnSearchRequestStart( - 'customMetric' - ), + modifyAggConfigOnSearchRequestStart: + forwardModifyAggConfigOnSearchRequestStart('customMetric'), write: (agg: IMetricAggConfig, output: Record) => siblingPipelineAggWriter(agg, output), }, diff --git a/src/plugins/data/common/search/aggs/param_types/field.test.ts b/src/plugins/data/common/search/aggs/param_types/field.test.ts index 561b1020f27f..d54e9c5b4eba 100644 --- a/src/plugins/data/common/search/aggs/param_types/field.test.ts +++ b/src/plugins/data/common/search/aggs/param_types/field.test.ts @@ -35,9 +35,9 @@ describe('Field', () => { ], }; - const agg = ({ + const agg = { getIndexPattern: jest.fn(() => indexPattern), - } as unknown) as IAggConfig; + } as unknown as IAggConfig; describe('constructor', () => { it('it is an instance of BaseParamType', () => { diff --git a/src/plugins/data/common/search/aggs/types.ts b/src/plugins/data/common/search/aggs/types.ts index 7a87a83b7b00..fec02a5ae23f 100644 --- a/src/plugins/data/common/search/aggs/types.ts +++ b/src/plugins/data/common/search/aggs/types.ts @@ -141,9 +141,8 @@ export interface AggExpressionType { } /** @internal */ -export type AggExpressionFunctionArgs< - Name extends keyof AggParamsMapping -> = AggParamsMapping[Name] & Pick; +export type AggExpressionFunctionArgs = + AggParamsMapping[Name] & Pick; /** * A global list of the param interfaces for each agg type. diff --git a/src/plugins/data/common/search/aggs/utils/get_date_histogram_meta.ts b/src/plugins/data/common/search/aggs/utils/get_date_histogram_meta.ts index 87086edd56e7..aa6e460b9c4d 100644 --- a/src/plugins/data/common/search/aggs/utils/get_date_histogram_meta.ts +++ b/src/plugins/data/common/search/aggs/utils/get_date_histogram_meta.ts @@ -25,7 +25,7 @@ export const getDateHistogramMetaDataByDatatableColumn = ( ) => { if (column.meta.source !== 'esaggs') return; if (column.meta.sourceParams?.type !== BUCKET_TYPES.DATE_HISTOGRAM) return; - const params = (column.meta.sourceParams.params as unknown) as AggParamsDateHistogram; + const params = column.meta.sourceParams.params as unknown as AggParamsDateHistogram; let interval: string | undefined; if (params.used_interval && params.used_interval !== 'auto') { diff --git a/src/plugins/data/common/search/aggs/utils/get_number_histogram_interval.ts b/src/plugins/data/common/search/aggs/utils/get_number_histogram_interval.ts index e1c0cf2d69c6..067f87bd8481 100644 --- a/src/plugins/data/common/search/aggs/utils/get_number_histogram_interval.ts +++ b/src/plugins/data/common/search/aggs/utils/get_number_histogram_interval.ts @@ -19,7 +19,7 @@ import { BUCKET_TYPES } from '../buckets/bucket_agg_types'; export const getNumberHistogramIntervalByDatatableColumn = (column: DatatableColumn) => { if (column.meta.source !== 'esaggs') return; if (column.meta.sourceParams?.type !== BUCKET_TYPES.HISTOGRAM) return; - const params = (column.meta.sourceParams.params as unknown) as AggParamsHistogram; + const params = column.meta.sourceParams.params as unknown as AggParamsHistogram; if (!params.used_interval || typeof params.used_interval === 'string') { return undefined; diff --git a/src/plugins/data/common/search/aggs/utils/infer_time_zone.test.ts b/src/plugins/data/common/search/aggs/utils/infer_time_zone.test.ts index 91f69f3bfb14..f1cfc3f0e81e 100644 --- a/src/plugins/data/common/search/aggs/utils/infer_time_zone.test.ts +++ b/src/plugins/data/common/search/aggs/utils/infer_time_zone.test.ts @@ -34,7 +34,7 @@ describe('inferTimeZone', () => { expect( inferTimeZone( { field: 'mydatefield' }, - ({ + { typeMeta: { aggs: { date_histogram: { @@ -44,7 +44,7 @@ describe('inferTimeZone', () => { }, }, }, - } as unknown) as IndexPattern, + } as unknown as IndexPattern, () => false, jest.fn() ) @@ -59,7 +59,7 @@ describe('inferTimeZone', () => { name: 'mydatefield', } as IndexPatternField, }, - ({ + { typeMeta: { aggs: { date_histogram: { @@ -69,7 +69,7 @@ describe('inferTimeZone', () => { }, }, }, - } as unknown) as IndexPattern, + } as unknown as IndexPattern, () => false, jest.fn() ) diff --git a/src/plugins/data/common/search/aggs/utils/time_splits.ts b/src/plugins/data/common/search/aggs/utils/time_splits.ts index ddc94119686a..99ea9fcefc17 100644 --- a/src/plugins/data/common/search/aggs/utils/time_splits.ts +++ b/src/plugins/data/common/search/aggs/utils/time_splits.ts @@ -213,9 +213,9 @@ export function mergeTimeShifts( } const baseSubAggregate = target[key] as estypes.AggregationsAggregate; // only supported bucket formats in agg configs are array of buckets and record of buckets for filters - const baseBuckets = ('buckets' in baseSubAggregate - ? baseSubAggregate.buckets - : undefined) as GenericBucket[] | Record | undefined; + const baseBuckets = ( + 'buckets' in baseSubAggregate ? baseSubAggregate.buckets : undefined + ) as GenericBucket[] | Record | undefined; // merge if (isArray(buckets) && isArray(baseBuckets)) { const baseBucketMap: Record = {}; @@ -259,8 +259,9 @@ export function mergeTimeShifts( if (shouldSplit) { // multiple time shifts caused a filters agg in the tree we have to merge if (hasMultipleTimeShifts && cursor.time_offset_split) { - const timeShiftedBuckets = (cursor.time_offset_split as estypes.AggregationsFiltersAggregate) - .buckets as Record; + const timeShiftedBuckets = ( + cursor.time_offset_split as estypes.AggregationsFiltersAggregate + ).buckets as Record; const subTree = {}; Object.entries(timeShifts).forEach(([key, shift]) => { mergeAggLevel( diff --git a/src/plugins/data/common/search/expressions/esaggs/request_handler.test.ts b/src/plugins/data/common/search/expressions/esaggs/request_handler.test.ts index 56f6c9da6d84..a44613cb98b5 100644 --- a/src/plugins/data/common/search/expressions/esaggs/request_handler.test.ts +++ b/src/plugins/data/common/search/expressions/esaggs/request_handler.test.ts @@ -37,17 +37,17 @@ describe('esaggs expression function - public', () => { ); mockParams = { - abortSignal: (jest.fn() as unknown) as jest.Mocked, - aggs: ({ + abortSignal: jest.fn() as unknown as jest.Mocked, + aggs: { aggs: [{ type: { name: 'terms', postFlightRequest: jest.fn().mockResolvedValue({}) } }], setTimeRange: jest.fn(), toDsl: jest.fn().mockReturnValue({ aggs: {} }), onSearchRequestStart: jest.fn(), setTimeFields: jest.fn(), setForceNow: jest.fn(), - } as unknown) as jest.Mocked, + } as unknown as jest.Mocked, filters: undefined, - indexPattern: ({ id: 'logstash-*' } as unknown) as jest.Mocked, + indexPattern: { id: 'logstash-*' } as unknown as jest.Mocked, inspectorAdapters: {}, partialRows: false, query: undefined, diff --git a/src/plugins/data/common/search/expressions/exists_filter.ts b/src/plugins/data/common/search/expressions/exists_filter.ts index 3edb65996646..b7c11daa3837 100644 --- a/src/plugins/data/common/search/expressions/exists_filter.ts +++ b/src/plugins/data/common/search/expressions/exists_filter.ts @@ -52,7 +52,7 @@ export const existsFilterFunction: ExpressionFunctionExistsFilter = { return { type: 'kibana_filter', ...buildFilter( - ({} as any) as IndexPattern, + {} as any as IndexPattern, args.field.spec, FILTERS.EXISTS, args.negate || false, diff --git a/src/plugins/data/common/search/expressions/geo_bounding_box.ts b/src/plugins/data/common/search/expressions/geo_bounding_box.ts index bed7eef72188..b763b741acd5 100644 --- a/src/plugins/data/common/search/expressions/geo_bounding_box.ts +++ b/src/plugins/data/common/search/expressions/geo_bounding_box.ts @@ -196,12 +196,12 @@ export const geoBoundingBoxFunction: ExpressionFunctionGeoBoundingBox = { if (isGeoPoints(args)) { return { - ...((chain(args) + ...(chain(args) .pick(['topLeft', 'bottomRight', 'topRight', 'bottomLeft']) .omitBy(isNil) .mapKeys((value, key) => snakeCase(key)) .mapValues(({ value }) => value) - .value() as unknown) as GeoPoints), + .value() as unknown as GeoPoints), type: 'geo_bounding_box', }; } diff --git a/src/plugins/data/common/search/expressions/phrase_filter.ts b/src/plugins/data/common/search/expressions/phrase_filter.ts index 6714edef5500..ec241752df0d 100644 --- a/src/plugins/data/common/search/expressions/phrase_filter.ts +++ b/src/plugins/data/common/search/expressions/phrase_filter.ts @@ -62,7 +62,7 @@ export const phraseFilterFunction: ExpressionFunctionPhraseFilter = { return { type: 'kibana_filter', ...buildFilter( - ({} as any) as IndexPattern, + {} as any as IndexPattern, args.field.spec, FILTERS.PHRASE, args.negate || false, @@ -76,7 +76,7 @@ export const phraseFilterFunction: ExpressionFunctionPhraseFilter = { return { type: 'kibana_filter', ...buildFilter( - ({} as any) as IndexPattern, + {} as any as IndexPattern, args.field.spec, FILTERS.PHRASES, args.negate || false, diff --git a/src/plugins/data/common/search/expressions/range_filter.ts b/src/plugins/data/common/search/expressions/range_filter.ts index bac50f200027..f2b4b23c018f 100644 --- a/src/plugins/data/common/search/expressions/range_filter.ts +++ b/src/plugins/data/common/search/expressions/range_filter.ts @@ -61,7 +61,7 @@ export const rangeFilterFunction: ExpressionFunctionRangeFilter = { return { type: 'kibana_filter', ...buildFilter( - ({} as any) as IndexPattern, + {} as any as IndexPattern, args.field.spec, FILTERS.RANGE, args.negate || false, diff --git a/src/plugins/data/common/search/search_source/create_search_source.test.ts b/src/plugins/data/common/search/search_source/create_search_source.test.ts index 9ac9dc93a807..9ad2e5c40697 100644 --- a/src/plugins/data/common/search/search_source/create_search_source.test.ts +++ b/src/plugins/data/common/search/search_source/create_search_source.test.ts @@ -25,9 +25,9 @@ describe('createSearchSource', () => { onResponse: (req, res) => res, }; - indexPatternContractMock = ({ + indexPatternContractMock = { get: jest.fn().mockReturnValue(Promise.resolve(indexPatternMock)), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; createSearchSource = createSearchSourceFactory(indexPatternContractMock, dependencies); }); diff --git a/src/plugins/data/common/search/search_source/create_search_source.ts b/src/plugins/data/common/search/search_source/create_search_source.ts index 80547ca2e71f..c6c8bb4d26f9 100644 --- a/src/plugins/data/common/search/search_source/create_search_source.ts +++ b/src/plugins/data/common/search/search_source/create_search_source.ts @@ -28,25 +28,24 @@ import { SearchSourceFields } from './types'; * * * @public */ -export const createSearchSource = ( - indexPatterns: IndexPatternsContract, - searchSourceDependencies: SearchSourceDependencies -) => async (searchSourceFields: SearchSourceFields = {}) => { - const fields = { ...searchSourceFields }; +export const createSearchSource = + (indexPatterns: IndexPatternsContract, searchSourceDependencies: SearchSourceDependencies) => + async (searchSourceFields: SearchSourceFields = {}) => { + const fields = { ...searchSourceFields }; - // hydrating index pattern - if (fields.index && typeof fields.index === 'string') { - fields.index = await indexPatterns.get(searchSourceFields.index as any); - } + // hydrating index pattern + if (fields.index && typeof fields.index === 'string') { + fields.index = await indexPatterns.get(searchSourceFields.index as any); + } - const searchSource = new SearchSource(fields, searchSourceDependencies); + const searchSource = new SearchSource(fields, searchSourceDependencies); - // todo: move to migration script .. create issue - const query = searchSource.getOwnField('query'); + // todo: move to migration script .. create issue + const query = searchSource.getOwnField('query'); - if (typeof query !== 'undefined') { - searchSource.setField('query', migrateLegacyQuery(query)); - } + if (typeof query !== 'undefined') { + searchSource.setField('query', migrateLegacyQuery(query)); + } - return searchSource; -}; + return searchSource; + }; diff --git a/src/plugins/data/common/search/search_source/extract_references.ts b/src/plugins/data/common/search/search_source/extract_references.ts index f099443ef760..c7f6c53d0f5f 100644 --- a/src/plugins/data/common/search/search_source/extract_references.ts +++ b/src/plugins/data/common/search/search_source/extract_references.ts @@ -18,7 +18,7 @@ export const extractReferences = ( let searchSourceFields: SearchSourceFields & { indexRefName?: string } = { ...state }; const references: SavedObjectReference[] = []; if (searchSourceFields.index) { - const indexId = searchSourceFields.index.id || ((searchSourceFields.index as any) as string); + const indexId = searchSourceFields.index.id || (searchSourceFields.index as any as string); const refName = 'kibanaSavedObjectMeta.searchSourceJSON.index'; references.push({ name: refName, diff --git a/src/plugins/data/common/search/search_source/search_source.test.ts b/src/plugins/data/common/search/search_source/search_source.test.ts index cb7f2904ead2..04b3526ea34a 100644 --- a/src/plugins/data/common/search/search_source/search_source.test.ts +++ b/src/plugins/data/common/search/search_source/search_source.test.ts @@ -26,21 +26,21 @@ const getComputedFields = () => ({ const mockSource = { excludes: ['foo-*'] }; const mockSource2 = { excludes: ['bar-*'] }; -const indexPattern = ({ +const indexPattern = { title: 'foo', fields: [{ name: 'foo-bar' }, { name: 'field1' }, { name: 'field2' }, { name: '_id' }], getComputedFields, getSourceFiltering: () => mockSource, -} as unknown) as IndexPattern; +} as unknown as IndexPattern; -const indexPattern2 = ({ +const indexPattern2 = { title: 'foo', getComputedFields, getSourceFiltering: () => mockSource2, -} as unknown) as IndexPattern; +} as unknown as IndexPattern; const fields3 = [{ name: 'foo-bar' }, { name: 'field1' }, { name: 'field2' }]; -const indexPattern3 = ({ +const indexPattern3 = { title: 'foo', fields: { getByName: (name: string) => { @@ -52,7 +52,7 @@ const indexPattern3 = ({ }, getComputedFields, getSourceFiltering: () => mockSource, -} as unknown) as IndexPattern; +} as unknown as IndexPattern; const runtimeFieldDef = { type: 'keyword', @@ -140,7 +140,7 @@ describe('SearchSource', () => { describe('computed fields handling', () => { test('still provides computed fields when no fields are specified', async () => { const runtimeFields = { runtime_field: runtimeFieldDef }; - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: ['hello'], @@ -148,7 +148,7 @@ describe('SearchSource', () => { docvalueFields: ['@timestamp'], runtimeFields, }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); const request = searchSource.getSearchRequestBody(); expect(request.stored_fields).toEqual(['hello']); @@ -158,14 +158,14 @@ describe('SearchSource', () => { }); test('never includes docvalue_fields', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: {}, docvalueFields: ['@timestamp'], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', ['@timestamp']); searchSource.setField('fieldsFromSource', ['foo']); @@ -174,14 +174,14 @@ describe('SearchSource', () => { }); test('overrides computed docvalue fields with ones that are provided', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: {}, docvalueFields: ['hello'], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); // @ts-expect-error TS won't like using this field name, but technically it's possible. searchSource.setField('docvalue_fields', ['world']); @@ -191,14 +191,14 @@ describe('SearchSource', () => { }); test('allows explicitly provided docvalue fields to override fields API when fetching fieldsFromSource', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: {}, docvalueFields: [{ field: 'a', format: 'date_time' }], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); // @ts-expect-error TS won't like using this field name, but technically it's possible. searchSource.setField('docvalue_fields', [{ field: 'b', format: 'date_time' }]); searchSource.setField('fields', ['c']); @@ -216,7 +216,7 @@ describe('SearchSource', () => { indexPatternFields.getByType = (type) => { return []; }; - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, fields: indexPatternFields, getComputedFields: () => ({ @@ -224,7 +224,7 @@ describe('SearchSource', () => { scriptFields: {}, docvalueFields: [{ field: 'hello', format: 'date_time' }], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', [{ field: 'hello', format: 'strict_date_time' }]); const request = searchSource.getSearchRequestBody(); @@ -233,14 +233,14 @@ describe('SearchSource', () => { }); test('injects a date format for computed docvalue fields if none is provided', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: {}, docvalueFields: [{ field: 'hello', format: 'date_time' }], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', ['hello']); const request = searchSource.getSearchRequestBody(); @@ -249,7 +249,7 @@ describe('SearchSource', () => { }); test('injects a date format for computed docvalue fields while merging other properties', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, fields: { getByType: () => { @@ -261,7 +261,7 @@ describe('SearchSource', () => { scriptFields: {}, docvalueFields: [{ field: 'hello', format: 'date_time', a: 'test', b: 'test' }], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', [{ field: 'hello', a: 'a', c: 'c' }]); const request = searchSource.getSearchRequestBody(); @@ -272,14 +272,14 @@ describe('SearchSource', () => { }); test('merges provided script fields with computed fields', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: { hello: {} }, docvalueFields: [], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); // @ts-expect-error TS won't like using this field name, but technically it's possible. searchSource.setField('script_fields', { world: {} }); @@ -292,14 +292,14 @@ describe('SearchSource', () => { }); test(`requests any fields that aren't script_fields from stored_fields`, async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: { hello: {} }, docvalueFields: [], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', ['hello', 'a', { field: 'c' }]); const request = searchSource.getSearchRequestBody(); @@ -308,14 +308,14 @@ describe('SearchSource', () => { }); test('ignores objects without a `field` property when setting stored_fields', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: { hello: {} }, docvalueFields: [], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', ['hello', 'a', { foo: 'c' }]); const request = searchSource.getSearchRequestBody(); @@ -324,14 +324,14 @@ describe('SearchSource', () => { }); test(`requests any fields that aren't script_fields from stored_fields with fieldsFromSource`, async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: { hello: {} }, docvalueFields: [], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fieldsFromSource', ['hello', 'a']); const request = searchSource.getSearchRequestBody(); @@ -427,14 +427,14 @@ describe('SearchSource', () => { describe('source filters handling', () => { test('excludes docvalue fields based on source filtering', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: {}, docvalueFields: ['@timestamp', 'exclude-me'], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); // @ts-expect-error Typings for excludes filters need to be fixed. searchSource.setField('source', { excludes: ['exclude-*'] }); @@ -443,28 +443,28 @@ describe('SearchSource', () => { }); test('defaults to source filters from index pattern', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: {}, docvalueFields: ['@timestamp', 'foo-bar', 'foo-baz'], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); const request = searchSource.getSearchRequestBody(); expect(request.fields).toEqual(['@timestamp']); }); test('filters script fields to only include specified fields', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: { hello: {}, world: {} }, docvalueFields: [], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', ['hello']); const request = searchSource.getSearchRequestBody(); @@ -472,14 +472,14 @@ describe('SearchSource', () => { }); test('request all fields except the ones specified with source filters', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: [], docvalueFields: [], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', [ 'hello', 'foo-bar', @@ -493,14 +493,14 @@ describe('SearchSource', () => { }); test('request all fields from index pattern except the ones specified with source filters', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: [], docvalueFields: [], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', ['*']); const request = searchSource.getSearchRequestBody(); @@ -508,14 +508,14 @@ describe('SearchSource', () => { }); test('request all fields from index pattern except the ones specified with source filters with unmapped_fields option', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: [], docvalueFields: [], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', [{ field: '*', include_unmapped: 'true' }]); const request = searchSource.getSearchRequestBody(); @@ -523,14 +523,14 @@ describe('SearchSource', () => { }); test('excludes metafields from the request', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: [], docvalueFields: [], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', [{ field: '*', include_unmapped: 'true' }]); const request = searchSource.getSearchRequestBody(); @@ -545,14 +545,14 @@ describe('SearchSource', () => { }); test('returns all scripted fields when one fields entry is *', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: { hello: {}, world: {} }, docvalueFields: [], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', ['timestamp', '*']); const request = searchSource.getSearchRequestBody(); @@ -562,14 +562,14 @@ describe('SearchSource', () => { describe('handling for when specific fields are provided', () => { test('fieldsFromSource will request any fields outside of script_fields from _source & stored fields', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], scriptFields: { hello: {}, world: {} }, docvalueFields: ['@timestamp'], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fieldsFromSource', [ 'hello', 'world', @@ -586,14 +586,14 @@ describe('SearchSource', () => { }); test('filters request when a specific list of fields is provided', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: ['*'], scriptFields: { hello: {}, world: {} }, docvalueFields: ['@timestamp', 'date'], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', ['hello', '@timestamp', 'foo-a', 'bar']); const request = searchSource.getSearchRequestBody(); @@ -604,7 +604,7 @@ describe('SearchSource', () => { test('filters request when a specific list of fields is provided with fieldsFromSource', async () => { const runtimeFields = { runtime_field: runtimeFieldDef, runtime_field_b: runtimeFieldDef }; - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: ['*'], @@ -612,7 +612,7 @@ describe('SearchSource', () => { docvalueFields: ['@timestamp', 'date'], runtimeFields, }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fieldsFromSource', [ 'hello', '@timestamp', @@ -632,14 +632,14 @@ describe('SearchSource', () => { }); test('filters request when a specific list of fields is provided with fieldsFromSource or fields', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: ['*'], scriptFields: { hello: {}, world: {} }, docvalueFields: ['@timestamp', 'date', 'time'], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', ['hello', '@timestamp', 'foo-a', 'bar']); searchSource.setField('fieldsFromSource', ['foo-b', 'date', 'baz']); @@ -655,7 +655,7 @@ describe('SearchSource', () => { describe('handling date fields', () => { test('adds date format to any date field', async () => { - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], @@ -666,7 +666,7 @@ describe('SearchSource', () => { getByType: () => [{ name: '@timestamp', esTypes: ['date_nanos'] }], }, getSourceFiltering: () => ({ excludes: [] }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', ['*']); const request = searchSource.getSearchRequestBody(); @@ -685,7 +685,7 @@ describe('SearchSource', () => { { name: 'custom_date', esTypes: ['date'] }, ]; }; - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getComputedFields: () => ({ storedFields: [], @@ -694,7 +694,7 @@ describe('SearchSource', () => { }), fields: indexPatternFields, getSourceFiltering: () => ({ excludes: ['custom_date'] }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); searchSource.setField('fields', ['*']); const request = searchSource.getSearchRequestBody(); @@ -867,7 +867,7 @@ describe('SearchSource', () => { searchSource.setField('docvalue_fields', ['prop1']); searchSource.setField('source', ['geometry']); searchSource.setField('fieldsFromSource', ['geometry', 'prop1']); - searchSource.setField('index', ({ + searchSource.setField('index', { ...indexPattern, getSourceFiltering: () => ({ excludes: [] }), getComputedFields: () => ({ @@ -875,7 +875,7 @@ describe('SearchSource', () => { scriptFields: {}, docvalueFields: [], }), - } as unknown) as IndexPattern); + } as unknown as IndexPattern); const request = searchSource.getSearchRequestBody(); expect(request.stored_fields).toEqual(['geometry', 'prop1']); expect(request.docvalue_fields).toEqual(['prop1']); @@ -1082,12 +1082,12 @@ describe('SearchSource', () => { describe('inspector', () => { let requestResponder: RequestResponder; beforeEach(() => { - requestResponder = ({ + requestResponder = { stats: jest.fn(), ok: jest.fn(), error: jest.fn(), json: jest.fn(), - } as unknown) as RequestResponder; + } as unknown as RequestResponder; }); test('calls inspector if provided', async () => { diff --git a/src/plugins/data/common/search/search_source/search_source_service.test.ts b/src/plugins/data/common/search/search_source/search_source_service.test.ts index 69ffef3f9ccd..dc63b96d5258 100644 --- a/src/plugins/data/common/search/search_source/search_source_service.test.ts +++ b/src/plugins/data/common/search/search_source/search_source_service.test.ts @@ -24,7 +24,7 @@ describe('SearchSource service', () => { describe('start()', () => { test('exposes proper contract', () => { const start = new SearchSourceService().start( - (jest.fn() as unknown) as jest.Mocked, + jest.fn() as unknown as jest.Mocked, dependencies ); diff --git a/src/plugins/data/common/search/tabify/tabify.test.ts b/src/plugins/data/common/search/tabify/tabify.test.ts index 329d1597268d..6cdf9a3547d4 100644 --- a/src/plugins/data/common/search/tabify/tabify.test.ts +++ b/src/plugins/data/common/search/tabify/tabify.test.ts @@ -20,7 +20,7 @@ describe('tabifyAggResponse Integration', () => { name: '@timestamp', }; - const indexPattern = ({ + const indexPattern = { id: '1234', title: 'logstash-*', fields: { @@ -30,12 +30,12 @@ describe('tabifyAggResponse Integration', () => { getFormatterForField: () => ({ toJSON: () => '{}', }), - } as unknown) as IndexPattern; + } as unknown as IndexPattern; return new AggConfigs(indexPattern, aggs, { typesRegistry }); }; - const mockAggConfig = (agg: any): IAggConfig => (agg as unknown) as IAggConfig; + const mockAggConfig = (agg: any): IAggConfig => agg as unknown as IAggConfig; test('transforms a simple response properly', () => { const aggConfigs = createAggConfigs([{ type: 'count' } as any]); diff --git a/src/plugins/data/public/actions/filters/create_filters_from_range_select.test.ts b/src/plugins/data/public/actions/filters/create_filters_from_range_select.test.ts index 6d0ba0d9e440..acfad53d0a9d 100644 --- a/src/plugins/data/public/actions/filters/create_filters_from_range_select.test.ts +++ b/src/plugins/data/public/actions/filters/create_filters_from_range_select.test.ts @@ -55,10 +55,10 @@ describe('brushEvent', () => { beforeEach(() => { const dataStart = dataPluginMock.createStartContract(); setSearchService(dataStart.search); - setIndexPatterns(({ + setIndexPatterns({ ...dataStart.indexPatterns, get: async () => indexPattern, - } as unknown) as IndexPatternsContract); + } as unknown as IndexPatternsContract); baseEvent = { column: 0, diff --git a/src/plugins/data/public/actions/filters/create_filters_from_value_click.test.ts b/src/plugins/data/public/actions/filters/create_filters_from_value_click.test.ts index b2e7b959ca79..2632666cf85d 100644 --- a/src/plugins/data/public/actions/filters/create_filters_from_value_click.test.ts +++ b/src/plugins/data/public/actions/filters/create_filters_from_value_click.test.ts @@ -61,7 +61,7 @@ describe('createFiltersFromValueClick', () => { const dataStart = dataPluginMock.createStartContract(); setSearchService(dataStart.search); - setIndexPatterns(({ + setIndexPatterns({ ...dataStart.indexPatterns, get: async () => ({ id: 'logstash-*', @@ -71,7 +71,7 @@ describe('createFiltersFromValueClick', () => { }, getFormatterForField: () => new BytesFormat({}, (() => {}) as FieldFormatsGetConfigFn), }), - } as unknown) as IndexPatternsContract); + } as unknown as IndexPatternsContract); }); test('ignores event when value for rows is not provided', async () => { diff --git a/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts b/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts index c1c44f1f5554..24d9cdbfa6b3 100644 --- a/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts +++ b/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts @@ -10,10 +10,10 @@ import { setupGetConjunctionSuggestions } from './conjunction'; import { QuerySuggestionGetFnArgs, KueryNode } from '../../../../../../../src/plugins/data/public'; import { coreMock } from '../../../../../../../src/core/public/mocks'; -const mockKueryNode = (kueryNode: Partial) => (kueryNode as unknown) as KueryNode; +const mockKueryNode = (kueryNode: Partial) => kueryNode as unknown as KueryNode; describe('Kuery conjunction suggestions', () => { - const querySuggestionsArgs = (null as unknown) as QuerySuggestionGetFnArgs; + const querySuggestionsArgs = null as unknown as QuerySuggestionGetFnArgs; let getSuggestions: ReturnType; beforeEach(() => { diff --git a/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/field.test.ts b/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/field.test.ts index 84ed4315ee16..088edd3a7aca 100644 --- a/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/field.test.ts +++ b/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/field.test.ts @@ -16,16 +16,16 @@ import { } from '../../../../../../../src/plugins/data/public'; import { coreMock } from '../../../../../../../src/core/public/mocks'; -const mockKueryNode = (kueryNode: Partial) => (kueryNode as unknown) as KueryNode; +const mockKueryNode = (kueryNode: Partial) => kueryNode as unknown as KueryNode; describe('Kuery field suggestions', () => { let querySuggestionsArgs: QuerySuggestionGetFnArgs; let getSuggestions: ReturnType; beforeEach(() => { - querySuggestionsArgs = ({ + querySuggestionsArgs = { indexPatterns: [indexPatternResponse], - } as unknown) as QuerySuggestionGetFnArgs; + } as unknown as QuerySuggestionGetFnArgs; getSuggestions = setupGetFieldSuggestions(coreMock.createSetup()); }); diff --git a/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/index.ts b/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/index.ts index d76c71182b8f..c40f1dd92534 100644 --- a/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/index.ts +++ b/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/index.ts @@ -62,8 +62,8 @@ export const setupKqlQuerySuggestionProvider = ( selectionEnd )}`; - return Promise.all( - getSuggestionsByType(cursoredQuery, querySuggestionsArgs) - ).then((suggestionsByType) => dedup(flatten(suggestionsByType))); + return Promise.all(getSuggestionsByType(cursoredQuery, querySuggestionsArgs)).then( + (suggestionsByType) => dedup(flatten(suggestionsByType)) + ); }; }; diff --git a/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/operator.test.ts b/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/operator.test.ts index 4debbc0843d5..ab1d79eb522c 100644 --- a/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/operator.test.ts +++ b/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/operator.test.ts @@ -12,16 +12,16 @@ import { setupGetOperatorSuggestions } from './operator'; import { QuerySuggestionGetFnArgs, KueryNode } from '../../../../../../../src/plugins/data/public'; import { coreMock } from '../../../../../../../src/core/public/mocks'; -const mockKueryNode = (kueryNode: Partial) => (kueryNode as unknown) as KueryNode; +const mockKueryNode = (kueryNode: Partial) => kueryNode as unknown as KueryNode; describe('Kuery operator suggestions', () => { let getSuggestions: ReturnType; let querySuggestionsArgs: QuerySuggestionGetFnArgs; beforeEach(() => { - querySuggestionsArgs = ({ + querySuggestionsArgs = { indexPatterns: [indexPatternResponse], - } as unknown) as QuerySuggestionGetFnArgs; + } as unknown as QuerySuggestionGetFnArgs; getSuggestions = setupGetOperatorSuggestions(coreMock.createSetup()); }); diff --git a/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/value.test.ts b/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/value.test.ts index c434d9a8ef36..27031209c42a 100644 --- a/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/value.test.ts +++ b/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/value.test.ts @@ -11,7 +11,7 @@ import indexPatternResponse from './__fixtures__/index_pattern_response.json'; import { coreMock } from '../../../../../../../src/core/public/mocks'; import { QuerySuggestionGetFnArgs, KueryNode } from '../../../../../../../src/plugins/data/public'; -const mockKueryNode = (kueryNode: Partial) => (kueryNode as unknown) as KueryNode; +const mockKueryNode = (kueryNode: Partial) => kueryNode as unknown as KueryNode; describe('Kuery value suggestions', () => { let getSuggestions: ReturnType; @@ -42,9 +42,9 @@ describe('Kuery value suggestions', () => { }, }); getSuggestions = setupGetValueSuggestions(coreSetup); - querySuggestionsArgs = ({ + querySuggestionsArgs = { indexPatterns: [indexPatternResponse], - } as unknown) as QuerySuggestionGetFnArgs; + } as unknown as QuerySuggestionGetFnArgs; jest.clearAllMocks(); }); diff --git a/src/plugins/data/public/autocomplete/providers/value_suggestion_provider.test.ts b/src/plugins/data/public/autocomplete/providers/value_suggestion_provider.test.ts index d01064b4651f..7ecd371e39db 100644 --- a/src/plugins/data/public/autocomplete/providers/value_suggestion_provider.test.ts +++ b/src/plugins/data/public/autocomplete/providers/value_suggestion_provider.test.ts @@ -24,7 +24,7 @@ describe('FieldSuggestions', () => { http = { fetch: jest.fn().mockResolvedValue([]) }; getValueSuggestions = setupValueSuggestionProvider({ http, uiSettings } as CoreSetup, { - timefilter: ({ + timefilter: { timefilter: { createFilter: () => { return { @@ -38,7 +38,7 @@ describe('FieldSuggestions', () => { }; }, }, - } as unknown) as TimefilterSetup, + } as unknown as TimefilterSetup, }); }); diff --git a/src/plugins/data/public/data_views/data_views/on_unsupported_time_pattern.tsx b/src/plugins/data/public/data_views/data_views/on_unsupported_time_pattern.tsx index 06086ca49477..5f25dd827b58 100644 --- a/src/plugins/data/public/data_views/data_views/on_unsupported_time_pattern.tsx +++ b/src/plugins/data/public/data_views/data_views/on_unsupported_time_pattern.tsx @@ -13,52 +13,54 @@ import React from 'react'; import { CoreStart } from 'kibana/public'; import { toMountPoint } from '../../../../kibana_react/public'; -export const onUnsupportedTimePattern = ( - toasts: CoreStart['notifications']['toasts'], - navigateToApp: CoreStart['application']['navigateToApp'] -) => ({ id, title, index }: { id: string; title: string; index: string }) => { - const warningTitle = i18n.translate('data.indexPatterns.warningTitle', { - defaultMessage: 'Support for time interval index patterns removed', - }); +export const onUnsupportedTimePattern = + ( + toasts: CoreStart['notifications']['toasts'], + navigateToApp: CoreStart['application']['navigateToApp'] + ) => + ({ id, title, index }: { id: string; title: string; index: string }) => { + const warningTitle = i18n.translate('data.indexPatterns.warningTitle', { + defaultMessage: 'Support for time interval index patterns removed', + }); - const warningText = i18n.translate('data.indexPatterns.warningText', { - defaultMessage: - 'Currently querying all indices matching {index}. {title} should be migrated to a wildcard-based index pattern.', - values: { title, index }, - }); + const warningText = i18n.translate('data.indexPatterns.warningText', { + defaultMessage: + 'Currently querying all indices matching {index}. {title} should be migrated to a wildcard-based index pattern.', + values: { title, index }, + }); - // kbnUrl was added to this service in #35262 before it was de-angularized, and merged in a PR - // directly against the 7.x branch. Index patterns were de-angularized in #39247, and in order - // to preserve the functionality from #35262 we need to get the injector here just for kbnUrl. - // This has all been removed as of 8.0. + // kbnUrl was added to this service in #35262 before it was de-angularized, and merged in a PR + // directly against the 7.x branch. Index patterns were de-angularized in #39247, and in order + // to preserve the functionality from #35262 we need to get the injector here just for kbnUrl. + // This has all been removed as of 8.0. - // 2019-12-01 The usage of kbnUrl had to be removed due to the transition to NP. - // It's now temporarily replaced by a simple replace of the single argument used by all URLs. - // Once kbnUrl is migrated to NP, this can be updated. + // 2019-12-01 The usage of kbnUrl had to be removed due to the transition to NP. + // It's now temporarily replaced by a simple replace of the single argument used by all URLs. + // Once kbnUrl is migrated to NP, this can be updated. - toasts.addWarning({ - title: warningTitle, - text: toMountPoint( -
-

{warningText}

- - - - navigateToApp('management', { - path: `/kibana/index_patterns/index_pattern/${id! || ''}`, - }) - } - > - - - - -
- ), - }); -}; + toasts.addWarning({ + title: warningTitle, + text: toMountPoint( +
+

{warningText}

+ + + + navigateToApp('management', { + path: `/kibana/index_patterns/index_pattern/${id! || ''}`, + }) + } + > + + + + +
+ ), + }); + }; diff --git a/src/plugins/data/public/data_views/data_views/redirect_no_index_pattern.tsx b/src/plugins/data/public/data_views/data_views/redirect_no_index_pattern.tsx index 86978efafdc5..88e18060c4d1 100644 --- a/src/plugins/data/public/data_views/data_views/redirect_no_index_pattern.tsx +++ b/src/plugins/data/public/data_views/data_views/redirect_no_index_pattern.tsx @@ -14,45 +14,50 @@ import { toMountPoint } from '../../../../kibana_react/public'; let bannerId: string; -export const onRedirectNoIndexPattern = ( - capabilities: CoreStart['application']['capabilities'], - navigateToApp: CoreStart['application']['navigateToApp'], - overlays: CoreStart['overlays'] -) => () => { - const canManageIndexPatterns = capabilities.management.kibana.indexPatterns; - const redirectTarget = canManageIndexPatterns ? '/management/kibana/indexPatterns' : '/home'; - let timeoutId: NodeJS.Timeout | undefined; - - if (timeoutId) { - clearTimeout(timeoutId); - } - - const bannerMessage = i18n.translate('data.indexPatterns.ensureDefaultIndexPattern.bannerLabel', { - defaultMessage: - 'To visualize and explore data in Kibana, you must create an index pattern to retrieve data from Elasticsearch.', - }); - - // Avoid being hostile to new users who don't have an index pattern setup yet - // give them a friendly info message instead of a terse error message - bannerId = overlays.banners.replace( - bannerId, - toMountPoint() - ); - - // hide the message after the user has had a chance to acknowledge it -- so it doesn't permanently stick around - timeoutId = setTimeout(() => { - overlays.banners.remove(bannerId); - timeoutId = undefined; - }, 15000); - - if (redirectTarget === '/home') { - navigateToApp('home'); - } else { - navigateToApp('management', { - path: `/kibana/indexPatterns?bannerMessage=${bannerMessage}`, - }); - } - - // return never-resolving promise to stop resolving and wait for the url change - return new Promise(() => {}); -}; +export const onRedirectNoIndexPattern = + ( + capabilities: CoreStart['application']['capabilities'], + navigateToApp: CoreStart['application']['navigateToApp'], + overlays: CoreStart['overlays'] + ) => + () => { + const canManageIndexPatterns = capabilities.management.kibana.indexPatterns; + const redirectTarget = canManageIndexPatterns ? '/management/kibana/indexPatterns' : '/home'; + let timeoutId: NodeJS.Timeout | undefined; + + if (timeoutId) { + clearTimeout(timeoutId); + } + + const bannerMessage = i18n.translate( + 'data.indexPatterns.ensureDefaultIndexPattern.bannerLabel', + { + defaultMessage: + 'To visualize and explore data in Kibana, you must create an index pattern to retrieve data from Elasticsearch.', + } + ); + + // Avoid being hostile to new users who don't have an index pattern setup yet + // give them a friendly info message instead of a terse error message + bannerId = overlays.banners.replace( + bannerId, + toMountPoint() + ); + + // hide the message after the user has had a chance to acknowledge it -- so it doesn't permanently stick around + timeoutId = setTimeout(() => { + overlays.banners.remove(bannerId); + timeoutId = undefined; + }, 15000); + + if (redirectTarget === '/home') { + navigateToApp('home'); + } else { + navigateToApp('management', { + path: `/kibana/indexPatterns?bannerMessage=${bannerMessage}`, + }); + } + + // return never-resolving promise to stop resolving and wait for the url change + return new Promise(() => {}); + }; diff --git a/src/plugins/data/public/mocks.ts b/src/plugins/data/public/mocks.ts index 40882fa1134e..53600a1f4446 100644 --- a/src/plugins/data/public/mocks.ts +++ b/src/plugins/data/public/mocks.ts @@ -38,7 +38,7 @@ const createSetupContract = (): Setup => { const createStartContract = (): Start => { const queryStartMock = queryServiceMock.createStartContract(); - const dataViews = ({ + const dataViews = { find: jest.fn((search) => [{ id: search, title: search }]), createField: jest.fn(() => {}), createFieldList: jest.fn(() => []), @@ -50,7 +50,7 @@ const createStartContract = (): Start => { }), get: jest.fn().mockReturnValue(Promise.resolve({})), clearCache: jest.fn(), - } as unknown) as DataViewsContract; + } as unknown as DataViewsContract; return { actions: { diff --git a/src/plugins/data/public/plugin.ts b/src/plugins/data/public/plugin.ts index 7af8d8eed31c..c8e63e5d43f0 100644 --- a/src/plugins/data/public/plugin.ts +++ b/src/plugins/data/public/plugin.ts @@ -59,7 +59,8 @@ export class DataPublicPlugin DataPublicPluginStart, DataSetupDependencies, DataStartDependencies - > { + > +{ private readonly autocomplete: AutocompleteService; private readonly searchService: SearchService; private readonly queryService: QueryService; diff --git a/src/plugins/data/public/query/filter_manager/filter_manager.mock.ts b/src/plugins/data/public/query/filter_manager/filter_manager.mock.ts index b3d4e876efdd..ac1f4b7f3c1b 100644 --- a/src/plugins/data/public/query/filter_manager/filter_manager.mock.ts +++ b/src/plugins/data/public/query/filter_manager/filter_manager.mock.ts @@ -10,7 +10,7 @@ import { Observable } from 'rxjs'; import { FilterManager } from './filter_manager'; export const createFilterManagerMock = () => { - const filterManager = ({ + const filterManager = { mergeIncomingFilters: jest.fn(), handleStateUpdate: jest.fn(), getFilters: jest.fn(), @@ -25,7 +25,7 @@ export const createFilterManagerMock = () => { setAppFilters: jest.fn(), removeFilter: jest.fn(), removeAll: jest.fn(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; return filterManager; }; 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 0be44f3f7b5a..81be7efe4b58 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 @@ -72,11 +72,13 @@ export function generateFilters( index: string ): Filter[] { values = Array.isArray(values) ? _.uniq(values) : [values]; - const fieldObj = (_.isObject(field) - ? field - : { - name: field, - }) as IFieldType; + const fieldObj = ( + _.isObject(field) + ? field + : { + name: field, + } + ) as IFieldType; const fieldName = fieldObj.name; const newFilters: Filter[] = []; const appFilters = filterManager.getAppFilters(); diff --git a/src/plugins/data/public/query/saved_query/saved_query_service.ts b/src/plugins/data/public/query/saved_query/saved_query_service.ts index 21a34e0f136a..89a357a66d37 100644 --- a/src/plugins/data/public/query/saved_query/saved_query_service.ts +++ b/src/plugins/data/public/query/saved_query/saved_query_service.ts @@ -105,10 +105,8 @@ export const createSavedQueryService = ( }; const getSavedQuery = async (id: string): Promise => { - const { - saved_object: savedObject, - outcome, - } = await savedObjectsClient.resolve('query', id); + const { saved_object: savedObject, outcome } = + await savedObjectsClient.resolve('query', id); if (outcome === 'conflict') { throw new Error(`Multiple saved queries found with ID: ${id} (legacy URL alias conflict)`); } else if (savedObject.error) { diff --git a/src/plugins/data/public/search/expressions/esaggs.test.ts b/src/plugins/data/public/search/expressions/esaggs.test.ts index fa9e2755e529..8acbb8006e95 100644 --- a/src/plugins/data/public/search/expressions/esaggs.test.ts +++ b/src/plugins/data/public/search/expressions/esaggs.test.ts @@ -55,7 +55,7 @@ describe('esaggs expression function - public', () => { beforeEach(() => { jest.clearAllMocks(); mockHandlers = { - abortSignal: (jest.fn() as unknown) as jest.Mocked, + abortSignal: jest.fn() as unknown as jest.Mocked, getSearchContext: jest.fn(), getSearchSessionId: jest.fn().mockReturnValue('abc123'), getExecutionContext: jest.fn(), @@ -64,13 +64,13 @@ describe('esaggs expression function - public', () => { types: {}, }; startDependencies = { - aggs: ({ + aggs: { createAggConfigs: jest.fn().mockReturnValue({ foo: 'bar' }), - } as unknown) as jest.Mocked, - indexPatterns: ({ + } as unknown as jest.Mocked, + indexPatterns: { create: jest.fn().mockResolvedValue({}), - } as unknown) as jest.Mocked, - searchSource: ({} as unknown) as jest.Mocked, + } as unknown as jest.Mocked, + searchSource: {} as unknown as jest.Mocked, }; getStartDependencies = jest.fn().mockResolvedValue(startDependencies); definition = getFunctionDefinition({ getStartDependencies }); diff --git a/src/plugins/data/public/search/expressions/esdsl.ts b/src/plugins/data/public/search/expressions/esdsl.ts index c03226542ef7..8d65f6e4ee68 100644 --- a/src/plugins/data/public/search/expressions/esdsl.ts +++ b/src/plugins/data/public/search/expressions/esdsl.ts @@ -34,7 +34,7 @@ export function getEsdsl({ getStartDependencies: async () => { const [core, , { search }] = await getStartServices(); return { - uiSettingsClient: (core.uiSettings as any) as UiSettingsCommon, + uiSettingsClient: core.uiSettings as any as UiSettingsCommon, search: search.search, }; }, diff --git a/src/plugins/data/public/search/expressions/kibana_context.ts b/src/plugins/data/public/search/expressions/kibana_context.ts index cb6e5369eb34..a2d97dbc6b5d 100644 --- a/src/plugins/data/public/search/expressions/kibana_context.ts +++ b/src/plugins/data/public/search/expressions/kibana_context.ts @@ -33,7 +33,7 @@ export function getKibanaContext({ return getKibanaContextFn(async () => { const [core] = await getStartServices(); return { - savedObjectsClient: (core.savedObjects.client as unknown) as SavedObjectsClientCommon, + savedObjectsClient: core.savedObjects.client as unknown as SavedObjectsClientCommon, }; }); } diff --git a/src/plugins/data/public/search/search_service.test.ts b/src/plugins/data/public/search/search_service.test.ts index debee42d8bf3..5bf4c21d4857 100644 --- a/src/plugins/data/public/search/search_service.test.ts +++ b/src/plugins/data/public/search/search_service.test.ts @@ -31,11 +31,11 @@ describe('Search service', () => { describe('setup()', () => { it('exposes proper contract', async () => { const bfetch = bfetchPluginMock.createSetupContract(); - const setup = searchService.setup(mockCoreSetup, ({ + const setup = searchService.setup(mockCoreSetup, { packageInfo: { version: '8' }, bfetch, expressions: { registerFunction: jest.fn(), registerType: jest.fn() }, - } as unknown) as SearchServiceSetupDependencies); + } as unknown as SearchServiceSetupDependencies); expect(setup).toHaveProperty('aggs'); expect(setup).toHaveProperty('usageCollector'); expect(setup).toHaveProperty('sessionsClient'); diff --git a/src/plugins/data/public/search/session/search_session_state.ts b/src/plugins/data/public/search/session/search_session_state.ts index bf9036d361a8..73c75d046da9 100644 --- a/src/plugins/data/public/search/session/search_session_state.ts +++ b/src/plugins/data/public/search/session/search_session_state.ts @@ -152,12 +152,14 @@ export interface SessionPureTransitions< } export const sessionPureTransitions: SessionPureTransitions = { - start: (state) => ({ appName }) => ({ - ...createSessionDefaultState(), - sessionId: uuid.v4(), - startTime: new Date(), - appName, - }), + start: + (state) => + ({ appName }) => ({ + ...createSessionDefaultState(), + sessionId: uuid.v4(), + startTime: new Date(), + appName, + }), restore: (state) => (sessionId: string) => ({ ...createSessionDefaultState(), sessionId, diff --git a/src/plugins/data/public/search/session/session_service.ts b/src/plugins/data/public/search/session/session_service.ts index 32cd620a2adb..874fad67c4df 100644 --- a/src/plugins/data/public/search/session/session_service.ts +++ b/src/plugins/data/public/search/session/session_service.ts @@ -108,13 +108,10 @@ export class SessionService { private readonly nowProvider: NowProviderInternalContract, { freezeState = true }: { freezeState: boolean } = { freezeState: true } ) { - const { - stateContainer, - sessionState$, - sessionMeta$, - } = createSessionStateContainer({ - freeze: freezeState, - }); + const { stateContainer, sessionState$, sessionMeta$ } = + createSessionStateContainer({ + freeze: freezeState, + }); this.state$ = sessionState$; this.state = stateContainer; this.sessionMeta$ = sessionMeta$; @@ -332,8 +329,8 @@ export class SessionService { const searchSessionSavedObject = await this.sessionsClient.create({ name: formattedName, appId: currentSessionApp, - restoreState: (restoreState as unknown) as Record, - initialState: (initialState as unknown) as Record, + restoreState: restoreState as unknown as Record, + initialState: initialState as unknown as Record, urlGeneratorId, sessionId, }); diff --git a/src/plugins/data/public/services.ts b/src/plugins/data/public/services.ts index bcc23e13a1ec..c1a0ae1ac1b5 100644 --- a/src/plugins/data/public/services.ts +++ b/src/plugins/data/public/services.ts @@ -11,20 +11,16 @@ import { createGetterSetter } from '../../kibana_utils/public'; import { IndexPatternsContract } from './data_views'; import { DataPublicPluginStart } from './types'; -export const [getNotifications, setNotifications] = createGetterSetter( - 'Notifications' -); +export const [getNotifications, setNotifications] = + createGetterSetter('Notifications'); -export const [getUiSettings, setUiSettings] = createGetterSetter( - 'UiSettings' -); +export const [getUiSettings, setUiSettings] = + createGetterSetter('UiSettings'); export const [getOverlays, setOverlays] = createGetterSetter('Overlays'); -export const [getIndexPatterns, setIndexPatterns] = createGetterSetter( - 'IndexPatterns' -); +export const [getIndexPatterns, setIndexPatterns] = + createGetterSetter('IndexPatterns'); -export const [getSearchService, setSearchService] = createGetterSetter< - DataPublicPluginStart['search'] ->('Search'); +export const [getSearchService, setSearchService] = + createGetterSetter('Search'); 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 83e7c0a9cf4f..95bfdb0680d9 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 @@ -61,10 +61,8 @@ export function SavedQueryManagementComponent({ requestGotCancelled = true; }; - const { - total: savedQueryCount, - queries: savedQueryItems, - } = await savedQueryService.findSavedQueries('', perPage, activePage + 1); + const { total: savedQueryCount, queries: savedQueryItems } = + await savedQueryService.findSavedQueries('', perPage, activePage + 1); if (requestGotCancelled) return; @@ -77,9 +75,10 @@ export function SavedQueryManagementComponent({ } }, [isOpen, activePage, savedQueryService]); - const handleTogglePopover = useCallback(() => setIsOpen((currentState) => !currentState), [ - setIsOpen, - ]); + const handleTogglePopover = useCallback( + () => setIsOpen((currentState) => !currentState), + [setIsOpen] + ); const handleClosePopover = useCallback(() => setIsOpen(false), []); diff --git a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_open_modal_button.test.mocks.tsx b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_open_modal_button.test.mocks.tsx index 5f3de555d167..44996497cc0c 100644 --- a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_open_modal_button.test.mocks.tsx +++ b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_open_modal_button.test.mocks.tsx @@ -11,6 +11,6 @@ import { OverlayStart } from 'kibana/public'; export const openModal = jest.fn(); -setOverlays(({ +setOverlays({ openModal, -} as unknown) as OverlayStart); +} as unknown as OverlayStart); diff --git a/src/plugins/data/server/autocomplete/terms_agg.test.ts b/src/plugins/data/server/autocomplete/terms_agg.test.ts index 96a75fd3b2fd..dcaa5390f3fe 100644 --- a/src/plugins/data/server/autocomplete/terms_agg.test.ts +++ b/src/plugins/data/server/autocomplete/terms_agg.test.ts @@ -17,11 +17,11 @@ import { duration } from 'moment'; let savedObjectsClientMock: jest.Mocked; let esClientMock: DeeplyMockedKeys; -const configMock = ({ +const configMock = { autocomplete: { valueSuggestions: { timeout: duration(4513), terminateAfter: duration(98430) }, }, -} as unknown) as ConfigSchema; +} as unknown as ConfigSchema; // @ts-expect-error not full interface const mockResponse = { diff --git a/src/plugins/data/server/autocomplete/terms_enum.test.ts b/src/plugins/data/server/autocomplete/terms_enum.test.ts index 0e00e2dfe6b4..444ba4e89c58 100644 --- a/src/plugins/data/server/autocomplete/terms_enum.test.ts +++ b/src/plugins/data/server/autocomplete/terms_enum.test.ts @@ -31,7 +31,7 @@ describe('_terms_enum suggestions', () => { savedObjectsClientMock = requestHandlerContext.savedObjects.client; esClientMock = requestHandlerContext.elasticsearch.client.asCurrentUser; esClientMock.termsEnum.mockResolvedValue( - (mockResponse as unknown) as ApiResponse + mockResponse as unknown as ApiResponse ); }); diff --git a/src/plugins/data/server/config_deprecations.test.ts b/src/plugins/data/server/config_deprecations.test.ts index 6d3f8d9d6f22..365c3b749f6c 100644 --- a/src/plugins/data/server/config_deprecations.test.ts +++ b/src/plugins/data/server/config_deprecations.test.ts @@ -21,7 +21,9 @@ const applyConfigDeprecations = (settings: Record = {}) => { deprecation, path: '', })), - () => ({ message }) => deprecationMessages.push(message) + () => + ({ message }) => + deprecationMessages.push(message) ); return { messages: deprecationMessages, diff --git a/src/plugins/data/server/data_views/deprecations/scripted_fields.ts b/src/plugins/data/server/data_views/deprecations/scripted_fields.ts index 0dedfeb72028..65cb96219680 100644 --- a/src/plugins/data/server/data_views/deprecations/scripted_fields.ts +++ b/src/plugins/data/server/data_views/deprecations/scripted_fields.ts @@ -21,13 +21,12 @@ export const createScriptedFieldsDeprecationsConfig: ( core: CoreSetup ) => RegisterDeprecationsConfig = (core: CoreSetup) => ({ getDeprecations: async (context: GetDeprecationsContext): Promise => { - const finder = context.savedObjectsClient.createPointInTimeFinder( - { + const finder = + context.savedObjectsClient.createPointInTimeFinder({ type: 'index-pattern', perPage: 1000, fields: ['title', 'fields'], - } - ); + }); const indexPatternsWithScriptedFields: IndexPatternAttributesWithFields[] = []; for await (const response of finder.find()) { diff --git a/src/plugins/data/server/data_views/fetcher/index_patterns_fetcher.test.ts b/src/plugins/data/server/data_views/fetcher/index_patterns_fetcher.test.ts index ffdd47e5cdf4..4bd21fb3a182 100644 --- a/src/plugins/data/server/data_views/fetcher/index_patterns_fetcher.test.ts +++ b/src/plugins/data/server/data_views/fetcher/index_patterns_fetcher.test.ts @@ -25,9 +25,9 @@ describe('Index Pattern Fetcher - server', () => { }; const patternList = ['a', 'b', 'c']; beforeEach(() => { - esClient = ({ + esClient = { count: jest.fn().mockResolvedValueOnce(emptyResponse).mockResolvedValue(response), - } as unknown) as ElasticsearchClient; + } as unknown as ElasticsearchClient; indexPatterns = new IndexPatternsFetcher(esClient); }); @@ -37,9 +37,9 @@ describe('Index Pattern Fetcher - server', () => { }); it('Returns all patterns when all match indices', async () => { - esClient = ({ + esClient = { count: jest.fn().mockResolvedValue(response), - } as unknown) as ElasticsearchClient; + } as unknown as ElasticsearchClient; indexPatterns = new IndexPatternsFetcher(esClient); const result = await indexPatterns.validatePatternListActive(patternList); expect(result).toEqual(patternList); @@ -57,14 +57,14 @@ describe('Index Pattern Fetcher - server', () => { } } - esClient = ({ + esClient = { count: jest .fn() .mockResolvedValueOnce(response) .mockRejectedValue( new ServerError('index_not_found_exception', 404, indexNotFoundException) ), - } as unknown) as ElasticsearchClient; + } as unknown as ElasticsearchClient; indexPatterns = new IndexPatternsFetcher(esClient); const result = await indexPatterns.validatePatternListActive(patternList); expect(result).toEqual([patternList[0]]); diff --git a/src/plugins/data/server/data_views/index_patterns_service.ts b/src/plugins/data/server/data_views/index_patterns_service.ts index a6bed19a1e7e..d55adea2ae01 100644 --- a/src/plugins/data/server/data_views/index_patterns_service.ts +++ b/src/plugins/data/server/data_views/index_patterns_service.ts @@ -48,39 +48,41 @@ export interface IndexPatternsServiceStartDeps { logger: Logger; } -export const indexPatternsServiceFactory = ({ - logger, - uiSettings, - fieldFormats, -}: { - logger: Logger; - uiSettings: UiSettingsServiceStart; - fieldFormats: FieldFormatsStart; -}) => async ( - savedObjectsClient: SavedObjectsClientContract, - elasticsearchClient: ElasticsearchClient -) => { - const uiSettingsClient = uiSettings.asScopedToClient(savedObjectsClient); - const formats = await fieldFormats.fieldFormatServiceFactory(uiSettingsClient); +export const indexPatternsServiceFactory = + ({ + logger, + uiSettings, + fieldFormats, + }: { + logger: Logger; + uiSettings: UiSettingsServiceStart; + fieldFormats: FieldFormatsStart; + }) => + async ( + savedObjectsClient: SavedObjectsClientContract, + elasticsearchClient: ElasticsearchClient + ) => { + const uiSettingsClient = uiSettings.asScopedToClient(savedObjectsClient); + const formats = await fieldFormats.fieldFormatServiceFactory(uiSettingsClient); - return new IndexPatternsCommonService({ - uiSettings: new UiSettingsServerToCommon(uiSettingsClient), - savedObjectsClient: new SavedObjectsClientServerToCommon(savedObjectsClient), - apiClient: new IndexPatternsApiServer(elasticsearchClient, savedObjectsClient), - fieldFormats: formats, - onError: (error) => { - logger.error(error); - }, - onNotification: ({ title, text }) => { - logger.warn(`${title}${text ? ` : ${text}` : ''}`); - }, - onUnsupportedTimePattern: ({ index, title }) => { - logger.warn( - `Currently querying all indices matching ${index}. ${title} should be migrated to a wildcard-based index pattern.` - ); - }, - }); -}; + return new IndexPatternsCommonService({ + uiSettings: new UiSettingsServerToCommon(uiSettingsClient), + savedObjectsClient: new SavedObjectsClientServerToCommon(savedObjectsClient), + apiClient: new IndexPatternsApiServer(elasticsearchClient, savedObjectsClient), + fieldFormats: formats, + onError: (error) => { + logger.error(error); + }, + onNotification: ({ title, text }) => { + logger.warn(`${title}${text ? ` : ${text}` : ''}`); + }, + onUnsupportedTimePattern: ({ index, title }) => { + logger.warn( + `Currently querying all indices matching ${index}. ${title} should be migrated to a wildcard-based index pattern.` + ); + }, + }); + }; export class IndexPatternsServiceProvider implements Plugin { public setup( diff --git a/src/plugins/data/server/data_views/register_index_pattern_usage_collection.test.ts b/src/plugins/data/server/data_views/register_index_pattern_usage_collection.test.ts index c43431e10731..2c826185757d 100644 --- a/src/plugins/data/server/data_views/register_index_pattern_usage_collection.test.ts +++ b/src/plugins/data/server/data_views/register_index_pattern_usage_collection.test.ts @@ -26,13 +26,13 @@ const runtimeFieldA = { runtimeField: { script: { source: scriptA } } }; const runtimeFieldB = { runtimeField: { script: { source: scriptB } } }; const runtimeFieldC = { runtimeField: { script: { source: scriptC } } }; -const indexPatterns = ({ +const indexPatterns = { getIds: async () => [1, 2, 3], get: jest.fn().mockResolvedValue({ getScriptedFields: () => [], fields: [], }), -} as any) as IndexPatternsCommonService; +} as any as IndexPatternsCommonService; describe('index pattern usage collection', () => { it('minMaxAvgLoC calculates min, max, and average ', () => { diff --git a/src/plugins/data/server/data_views/routes/scripted_fields/update_scripted_field.ts b/src/plugins/data/server/data_views/routes/scripted_fields/update_scripted_field.ts index dd2484ef59e1..bf10a3ee6389 100644 --- a/src/plugins/data/server/data_views/routes/scripted_fields/update_scripted_field.ts +++ b/src/plugins/data/server/data_views/routes/scripted_fields/update_scripted_field.ts @@ -66,7 +66,7 @@ export const registerUpdateScriptedFieldRoute = ( ); const id = req.params.id; const name = req.params.name; - const field = ({ ...req.body.field, name } as unknown) as FieldSpec; + const field = { ...req.body.field, name } as unknown as FieldSpec; const indexPattern = await indexPatternsService.get(id); let fieldObject = indexPattern.fields.getByName(field.name); diff --git a/src/plugins/data/server/data_views/routes/util/handle_errors.ts b/src/plugins/data/server/data_views/routes/util/handle_errors.ts index 8e88a70a5650..f49e6394fd00 100644 --- a/src/plugins/data/server/data_views/routes/util/handle_errors.ts +++ b/src/plugins/data/server/data_views/routes/util/handle_errors.ts @@ -29,32 +29,36 @@ interface ErrorWithData { * } * ``` */ -export const handleErrors = < - P, - Q, - B, - Context extends RequestHandlerContext, - Method extends RouteMethod ->( - handler: RequestHandler -): RequestHandler => async (context, request, response) => { - try { - return await handler(context, request, response); - } catch (error) { - if (error instanceof Error) { - const body: ErrorResponseBody = { - message: error.message, - }; +export const handleErrors = + ( + handler: RequestHandler + ): RequestHandler => + async (context, request, response) => { + try { + return await handler(context, request, response); + } catch (error) { + if (error instanceof Error) { + const body: ErrorResponseBody = { + message: error.message, + }; - if (typeof (error as ErrorWithData).data === 'object') { - body.attributes = (error as ErrorWithData).data; - } + if (typeof (error as ErrorWithData).data === 'object') { + body.attributes = (error as ErrorWithData).data; + } + + const is404 = + (error as ErrorIndexPatternNotFound).is404 || (error as any)?.output?.statusCode === 404; - const is404 = - (error as ErrorIndexPatternNotFound).is404 || (error as any)?.output?.statusCode === 404; + if (is404) { + return response.notFound({ + headers: { + 'content-type': 'application/json', + }, + body, + }); + } - if (is404) { - return response.notFound({ + return response.badRequest({ headers: { 'content-type': 'application/json', }, @@ -62,14 +66,6 @@ export const handleErrors = < }); } - return response.badRequest({ - headers: { - 'content-type': 'application/json', - }, - body, - }); + throw error; } - - throw error; - } -}; + }; diff --git a/src/plugins/data/server/kql_telemetry/usage_collector/fetch.test.ts b/src/plugins/data/server/kql_telemetry/usage_collector/fetch.test.ts index 2dd404bbd6de..4aec1522c1eb 100644 --- a/src/plugins/data/server/kql_telemetry/usage_collector/fetch.test.ts +++ b/src/plugins/data/server/kql_telemetry/usage_collector/fetch.test.ts @@ -70,10 +70,10 @@ function setupMockCallCluster( }); } } - const esClientMock = ({ + const esClientMock = { get: jest.fn().mockImplementation(mockedEsGetMethod), search: jest.fn().mockImplementation(mockedEsSearchMethod), - } as unknown) as ElasticsearchClient; + } as unknown as ElasticsearchClient; esClient = esClientMock; } diff --git a/src/plugins/data/server/kql_telemetry/usage_collector/make_kql_usage_collector.test.ts b/src/plugins/data/server/kql_telemetry/usage_collector/make_kql_usage_collector.test.ts index 6a6800114f90..877e0a6b1ef0 100644 --- a/src/plugins/data/server/kql_telemetry/usage_collector/make_kql_usage_collector.test.ts +++ b/src/plugins/data/server/kql_telemetry/usage_collector/make_kql_usage_collector.test.ts @@ -13,10 +13,10 @@ describe('makeKQLUsageCollector', () => { let usageCollectionMock: jest.Mocked; beforeEach(() => { - usageCollectionMock = ({ + usageCollectionMock = { makeUsageCollector: jest.fn(), registerCollector: jest.fn(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; }); it('should call registerCollector', () => { diff --git a/src/plugins/data/server/mocks.ts b/src/plugins/data/server/mocks.ts index 852dffcfa3d5..c766dc5e5765 100644 --- a/src/plugins/data/server/mocks.ts +++ b/src/plugins/data/server/mocks.ts @@ -40,9 +40,9 @@ function createStartContract() { } function createRequestHandlerContext() { - return ({ + return { search: createSearchRequestHandlerContext(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; } export const dataPluginMock = { diff --git a/src/plugins/data/server/plugin.ts b/src/plugins/data/server/plugin.ts index c1741cc31fc0..3342519782d7 100644 --- a/src/plugins/data/server/plugin.ts +++ b/src/plugins/data/server/plugin.ts @@ -65,7 +65,8 @@ export class DataServerPlugin DataPluginStart, DataPluginSetupDependencies, DataPluginStartDependencies - > { + > +{ private readonly searchService: SearchService; private readonly scriptsService: ScriptsService; private readonly kqlTelemetryService: KqlTelemetryService; diff --git a/src/plugins/data/server/saved_objects/index_pattern_migrations.test.ts b/src/plugins/data/server/saved_objects/index_pattern_migrations.test.ts index eca1fba85f0b..7d8ca120d6d6 100644 --- a/src/plugins/data/server/saved_objects/index_pattern_migrations.test.ts +++ b/src/plugins/data/server/saved_objects/index_pattern_migrations.test.ts @@ -9,7 +9,7 @@ import { SavedObjectMigrationContext } from 'kibana/server'; import { indexPatternSavedObjectTypeMigrations } from './index_pattern_migrations'; -const savedObjectMigrationContext = (null as unknown) as SavedObjectMigrationContext; +const savedObjectMigrationContext = null as unknown as SavedObjectMigrationContext; describe('migration index-pattern', () => { describe('6.5.0', () => { diff --git a/src/plugins/data/server/search/aggs/aggs_service.ts b/src/plugins/data/server/search/aggs/aggs_service.ts index ed18ef7e4f35..e65c6d413497 100644 --- a/src/plugins/data/server/search/aggs/aggs_service.ts +++ b/src/plugins/data/server/search/aggs/aggs_service.ts @@ -72,17 +72,17 @@ export class AggsService { }; const isDefaultTimezone = () => getConfig('dateFormat:tz') === 'Browser'; - const { - calculateAutoTimeExpression, - datatableUtilities, - types, - } = this.aggsCommonService.start({ - getConfig, - getIndexPattern: ( - await indexPatterns.indexPatternsServiceFactory(savedObjectsClient, elasticsearchClient) - ).get, - isDefaultTimezone, - }); + const { calculateAutoTimeExpression, datatableUtilities, types } = + this.aggsCommonService.start({ + getConfig, + getIndexPattern: ( + await indexPatterns.indexPatternsServiceFactory( + savedObjectsClient, + elasticsearchClient + ) + ).get, + isDefaultTimezone, + }); const aggTypesDependencies: AggTypesDependencies = { calculateBounds: this.calculateBounds, diff --git a/src/plugins/data/server/search/collectors/fetch.ts b/src/plugins/data/server/search/collectors/fetch.ts index aed35d73c7eb..8c4b79b29056 100644 --- a/src/plugins/data/server/search/collectors/fetch.ts +++ b/src/plugins/data/server/search/collectors/fetch.ts @@ -35,9 +35,8 @@ export function fetchProvider(config$: Observable) { averageDuration: null, }; } - const { successCount, errorCount, totalDuration } = esResponse.hits.hits[0]._source![ - 'search-telemetry' - ]; + const { successCount, errorCount, totalDuration } = + esResponse.hits.hits[0]._source!['search-telemetry']; const averageDuration = totalDuration / successCount; return { successCount, errorCount, averageDuration }; }; diff --git a/src/plugins/data/server/search/expressions/esaggs.test.ts b/src/plugins/data/server/search/expressions/esaggs.test.ts index 5833846cf96e..cc5b81657bc5 100644 --- a/src/plugins/data/server/search/expressions/esaggs.test.ts +++ b/src/plugins/data/server/search/expressions/esaggs.test.ts @@ -56,7 +56,7 @@ describe('esaggs expression function - server', () => { beforeEach(() => { jest.clearAllMocks(); mockHandlers = { - abortSignal: (jest.fn() as unknown) as jest.Mocked, + abortSignal: jest.fn() as unknown as jest.Mocked, getKibanaRequest: jest.fn().mockReturnValue({ id: 'hi' } as KibanaRequest), getSearchContext: jest.fn(), getSearchSessionId: jest.fn().mockReturnValue('abc123'), @@ -66,13 +66,13 @@ describe('esaggs expression function - server', () => { types: {}, }; startDependencies = { - aggs: ({ + aggs: { createAggConfigs: jest.fn().mockReturnValue({ foo: 'bar' }), - } as unknown) as jest.Mocked, - indexPatterns: ({ + } as unknown as jest.Mocked, + indexPatterns: { create: jest.fn().mockResolvedValue({}), - } as unknown) as jest.Mocked, - searchSource: ({} as unknown) as jest.Mocked, + } as unknown as jest.Mocked, + searchSource: {} as unknown as jest.Mocked, }; getStartDependencies = jest.fn().mockResolvedValue(startDependencies); definition = getFunctionDefinition({ getStartDependencies }); diff --git a/src/plugins/data/server/search/expressions/kibana_context.ts b/src/plugins/data/server/search/expressions/kibana_context.ts index 191a0fdb7ae8..fd5af4cc4b05 100644 --- a/src/plugins/data/server/search/expressions/kibana_context.ts +++ b/src/plugins/data/server/search/expressions/kibana_context.ts @@ -38,9 +38,7 @@ export function getKibanaContext({ const [{ savedObjects }] = await getStartServices(); return { - savedObjectsClient: (savedObjects.getScopedClient( - request - ) as any) as SavedObjectsClientCommon, + savedObjectsClient: savedObjects.getScopedClient(request) as any as SavedObjectsClientCommon, }; }); } diff --git a/src/plugins/data/server/search/routes/msearch.test.ts b/src/plugins/data/server/search/routes/msearch.test.ts index 303f83582f73..869a81b78347 100644 --- a/src/plugins/data/server/search/routes/msearch.test.ts +++ b/src/plugins/data/server/search/routes/msearch.test.ts @@ -61,7 +61,7 @@ describe('msearch route', () => { const mockRouter = mockCoreSetup.http.createRouter.mock.results[0].value; const handler = mockRouter.post.mock.calls[0][1]; - await handler((mockContext as unknown) as RequestHandlerContext, mockRequest, mockResponse); + await handler(mockContext as unknown as RequestHandlerContext, mockRequest, mockResponse); expect(mockClient.msearch.mock.calls[0][0].body).toEqual( convertRequestBody(mockBody as any, {}) @@ -109,7 +109,7 @@ describe('msearch route', () => { const mockRouter = mockCoreSetup.http.createRouter.mock.results[0].value; const handler = mockRouter.post.mock.calls[0][1]; - await handler((mockContext as unknown) as RequestHandlerContext, mockRequest, mockResponse); + await handler(mockContext as unknown as RequestHandlerContext, mockRequest, mockResponse); expect(mockClient.msearch).toBeCalledTimes(1); expect(mockResponse.customError).toBeCalled(); @@ -143,7 +143,7 @@ describe('msearch route', () => { const mockRouter = mockCoreSetup.http.createRouter.mock.results[0].value; const handler = mockRouter.post.mock.calls[0][1]; - await handler((mockContext as unknown) as RequestHandlerContext, mockRequest, mockResponse); + await handler(mockContext as unknown as RequestHandlerContext, mockRequest, mockResponse); expect(mockClient.msearch).toBeCalledTimes(1); expect(mockResponse.customError).toBeCalled(); diff --git a/src/plugins/data/server/search/routes/search.test.ts b/src/plugins/data/server/search/routes/search.test.ts index b333174bc2a0..06487d271c6e 100644 --- a/src/plugins/data/server/search/routes/search.test.ts +++ b/src/plugins/data/server/search/routes/search.test.ts @@ -28,7 +28,7 @@ describe('Search service', () => { const mockRouter = mockCoreSetup.http.createRouter.mock.results[0].value; const handler = mockRouter.post.mock.calls[0][1]; - await handler((mockContext as unknown) as RequestHandlerContext, mockRequest, mockResponse); + await handler(mockContext as unknown as RequestHandlerContext, mockRequest, mockResponse); } beforeEach(() => { diff --git a/src/plugins/data/server/search/search_service.test.ts b/src/plugins/data/server/search/search_service.test.ts index e3738fd3a930..1278c08b5971 100644 --- a/src/plugins/data/server/search/search_service.test.ts +++ b/src/plugins/data/server/search/search_service.test.ts @@ -61,14 +61,14 @@ describe('Search service', () => { describe('setup()', () => { it('exposes proper contract', async () => { const bfetch = bfetchPluginMock.createSetupContract(); - const setup = plugin.setup(mockCoreSetup, ({ + const setup = plugin.setup(mockCoreSetup, { packageInfo: { version: '8' }, bfetch, expressions: { registerFunction: jest.fn(), registerType: jest.fn(), }, - } as unknown) as SearchServiceSetupDependencies); + } as unknown as SearchServiceSetupDependencies); expect(setup).toHaveProperty('aggs'); expect(setup).toHaveProperty('registerSearchStrategy'); }); diff --git a/src/plugins/data/server/search/session/mocks.ts b/src/plugins/data/server/search/session/mocks.ts index ec99853088f7..b55292e4ac46 100644 --- a/src/plugins/data/server/search/session/mocks.ts +++ b/src/plugins/data/server/search/session/mocks.ts @@ -26,10 +26,10 @@ export function createSearchSessionsClientMock(): jest.Mocked< delete: jest.fn(), getConfig: jest.fn( () => - (({ + ({ defaultExpiration: moment.duration('1', 'w'), enabled: true, - } as unknown) as SearchSessionsConfigSchema) + } as unknown as SearchSessionsConfigSchema) ), }; } diff --git a/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.test.ts b/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.test.ts index 85ac5d8d1799..58a5e875f7c9 100644 --- a/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.test.ts +++ b/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.test.ts @@ -33,7 +33,7 @@ describe('EQL search strategy', () => { let mockLogger: Logger; beforeEach(() => { - mockLogger = ({ debug: jest.fn() } as unknown) as Logger; + mockLogger = { debug: jest.fn() } as unknown as Logger; }); describe('strategy interface', () => { @@ -58,7 +58,7 @@ describe('EQL search strategy', () => { beforeEach(() => { mockEqlSearch = jest.fn().mockResolvedValueOnce(getMockEqlResponse()); mockEqlGet = jest.fn().mockResolvedValueOnce(getMockEqlResponse()); - mockDeps = ({ + mockDeps = { uiSettingsClient: { get: jest.fn(), }, @@ -70,7 +70,7 @@ describe('EQL search strategy', () => { }, }, }, - } as unknown) as SearchStrategyDependencies; + } as unknown as SearchStrategyDependencies; params = { index: 'logstash-*', body: { query: 'process where 1 == 1' }, diff --git a/src/plugins/data/server/search/strategies/es_search/es_search_strategy.test.ts b/src/plugins/data/server/search/strategies/es_search/es_search_strategy.test.ts index c2280737d249..bbbc99d157fe 100644 --- a/src/plugins/data/server/search/strategies/es_search/es_search_strategy.test.ts +++ b/src/plugins/data/server/search/strategies/es_search/es_search_strategy.test.ts @@ -47,12 +47,12 @@ describe('ES search strategy', () => { return mockedApiCaller; }); - return ({ + return { uiSettingsClient: { get: () => {}, }, esClient: { asCurrentUser: { search: mockApiCaller } }, - } as unknown) as SearchStrategyDependencies; + } as unknown as SearchStrategyDependencies; } const mockConfig$ = pluginInitializerContextConfigMock({}).legacy.globalConfig$; diff --git a/src/plugins/data/server/search/strategies/es_search/request_utils.test.ts b/src/plugins/data/server/search/strategies/es_search/request_utils.test.ts index 5f18ff7e4f50..5d1826d92f18 100644 --- a/src/plugins/data/server/search/strategies/es_search/request_utils.test.ts +++ b/src/plugins/data/server/search/strategies/es_search/request_utils.test.ts @@ -22,35 +22,35 @@ const createSuccessTransportRequestPromise = ( describe('request utils', () => { describe('getShardTimeout', () => { test('returns an empty object if the config does not contain a value', () => { - const result = getShardTimeout(({ + const result = getShardTimeout({ elasticsearch: { shardTimeout: { asMilliseconds: jest.fn(), }, }, - } as unknown) as SharedGlobalConfig); + } as unknown as SharedGlobalConfig); expect(result).toEqual({}); }); test('returns an empty object if the config contains 0', () => { - const result = getShardTimeout(({ + const result = getShardTimeout({ elasticsearch: { shardTimeout: { asMilliseconds: jest.fn().mockReturnValue(0), }, }, - } as unknown) as SharedGlobalConfig); + } as unknown as SharedGlobalConfig); expect(result).toEqual({}); }); test('returns a duration if the config >= 0', () => { - const result = getShardTimeout(({ + const result = getShardTimeout({ elasticsearch: { shardTimeout: { asMilliseconds: jest.fn().mockReturnValue(10), }, }, - } as unknown) as SharedGlobalConfig); + } as unknown as SharedGlobalConfig); expect(result).toEqual({ timeout: '10ms' }); }); }); @@ -58,32 +58,32 @@ describe('request utils', () => { describe('getDefaultSearchParams', () => { describe('max_concurrent_shard_requests', () => { test('returns value if > 0', async () => { - const result = await getDefaultSearchParams(({ + const result = await getDefaultSearchParams({ get: jest.fn().mockResolvedValue(1), - } as unknown) as IUiSettingsClient); + } as unknown as IUiSettingsClient); expect(result).toHaveProperty('max_concurrent_shard_requests', 1); }); test('returns undefined if === 0', async () => { - const result = await getDefaultSearchParams(({ + const result = await getDefaultSearchParams({ get: jest.fn().mockResolvedValue(0), - } as unknown) as IUiSettingsClient); + } as unknown as IUiSettingsClient); expect(result.max_concurrent_shard_requests).toBe(undefined); }); test('returns undefined if undefined', async () => { - const result = await getDefaultSearchParams(({ + const result = await getDefaultSearchParams({ get: jest.fn(), - } as unknown) as IUiSettingsClient); + } as unknown as IUiSettingsClient); expect(result.max_concurrent_shard_requests).toBe(undefined); }); }); describe('other defaults', () => { test('returns ignore_unavailable and track_total_hits', async () => { - const result = await getDefaultSearchParams(({ + const result = await getDefaultSearchParams({ get: jest.fn(), - } as unknown) as IUiSettingsClient); + } as unknown as IUiSettingsClient); expect(result).toHaveProperty('ignore_unavailable', true); expect(result).toHaveProperty('track_total_hits', true); }); diff --git a/src/plugins/data/server/search/strategies/es_search/response_utils.test.ts b/src/plugins/data/server/search/strategies/es_search/response_utils.test.ts index bd9babd61a7c..fc35187429a9 100644 --- a/src/plugins/data/server/search/strategies/es_search/response_utils.test.ts +++ b/src/plugins/data/server/search/strategies/es_search/response_utils.test.ts @@ -12,14 +12,14 @@ import type { estypes } from '@elastic/elasticsearch'; describe('response utils', () => { describe('getTotalLoaded', () => { it('returns the total/loaded, not including skipped', () => { - const result = getTotalLoaded(({ + const result = getTotalLoaded({ _shards: { successful: 10, failed: 5, skipped: 5, total: 100, }, - } as unknown) as estypes.SearchResponse); + } as unknown as estypes.SearchResponse); expect(result).toEqual({ total: 100, @@ -30,14 +30,14 @@ describe('response utils', () => { describe('toKibanaSearchResponse', () => { it('returns rawResponse, isPartial, isRunning, total, and loaded', () => { - const result = toKibanaSearchResponse(({ + const result = toKibanaSearchResponse({ _shards: { successful: 10, failed: 5, skipped: 5, total: 100, }, - } as unknown) as estypes.SearchResponse); + } as unknown as estypes.SearchResponse); expect(result).toEqual({ rawResponse: { diff --git a/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.test.ts b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.test.ts index 7a1ef2fe0a48..8d5fbf98db2d 100644 --- a/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.test.ts +++ b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.test.ts @@ -48,7 +48,7 @@ describe('ES search strategy', () => { const mockLogger: any = { debug: () => {}, }; - const mockDeps = ({ + const mockDeps = { uiSettingsClient: { get: jest.fn(), }, @@ -63,7 +63,7 @@ describe('ES search strategy', () => { }, }, searchSessionsClient: createSearchSessionsClientMock(), - } as unknown) as SearchStrategyDependencies; + } as unknown as SearchStrategyDependencies; const mockLegacyConfig$ = new BehaviorSubject({ elasticsearch: { shardTimeout: { diff --git a/src/plugins/discover/public/__mocks__/config.ts b/src/plugins/discover/public/__mocks__/config.ts index 977dc5699a57..42ecbd351af7 100644 --- a/src/plugins/discover/public/__mocks__/config.ts +++ b/src/plugins/discover/public/__mocks__/config.ts @@ -9,7 +9,7 @@ import { IUiSettingsClient } from 'kibana/public'; import { SORT_DEFAULT_ORDER_SETTING } from '../../common'; -export const configMock = ({ +export const configMock = { get: (key: string) => { if (key === 'defaultIndex') { return 'the-index-pattern-id'; @@ -19,4 +19,4 @@ export const configMock = ({ return ''; }, -} as unknown) as IUiSettingsClient; +} as unknown as IUiSettingsClient; diff --git a/src/plugins/discover/public/__mocks__/index_pattern.ts b/src/plugins/discover/public/__mocks__/index_pattern.ts index 9e7049187f63..f9cc202f9063 100644 --- a/src/plugins/discover/public/__mocks__/index_pattern.ts +++ b/src/plugins/discover/public/__mocks__/index_pattern.ts @@ -69,7 +69,7 @@ fields.getAll = () => { return fields; }; -const indexPattern = ({ +const indexPattern = { id: 'the-index-pattern-id', title: 'the-index-pattern-title', metaFields: ['_index', '_score'], @@ -83,7 +83,7 @@ const indexPattern = ({ timeFieldName: '', docvalueFields: [], getFormatterForField: () => ({ convert: () => 'formatted' }), -} as unknown) as IndexPattern; +} as unknown as IndexPattern; indexPattern.flattenHit = indexPatterns.flattenHitWrapper(indexPattern, indexPattern.metaFields); indexPattern.isTimeBased = () => !!indexPattern.timeFieldName; diff --git a/src/plugins/discover/public/__mocks__/index_pattern_with_timefield.ts b/src/plugins/discover/public/__mocks__/index_pattern_with_timefield.ts index f52ab8fd1c29..f1f1d74f3af3 100644 --- a/src/plugins/discover/public/__mocks__/index_pattern_with_timefield.ts +++ b/src/plugins/discover/public/__mocks__/index_pattern_with_timefield.ts @@ -60,7 +60,7 @@ fields.getAll = () => { return fields; }; -const indexPattern = ({ +const indexPattern = { id: 'index-pattern-with-timefield-id', title: 'index-pattern-with-timefield', metaFields: ['_index', '_score'], @@ -72,7 +72,7 @@ const indexPattern = ({ getFieldByName: (name: string) => fields.getByName(name), timeFieldName: 'timestamp', getFormatterForField: () => ({ convert: () => 'formatted' }), -} as unknown) as IndexPattern; +} as unknown as IndexPattern; indexPattern.flattenHit = indexPatterns.flattenHitWrapper(indexPattern, indexPattern.metaFields); indexPattern.isTimeBased = () => !!indexPattern.timeFieldName; diff --git a/src/plugins/discover/public/__mocks__/index_patterns.ts b/src/plugins/discover/public/__mocks__/index_patterns.ts index 3425ea42f4e6..88447eacc884 100644 --- a/src/plugins/discover/public/__mocks__/index_patterns.ts +++ b/src/plugins/discover/public/__mocks__/index_patterns.ts @@ -9,7 +9,7 @@ import { IndexPatternsService } from '../../../data/common'; import { indexPatternMock } from './index_pattern'; -export const indexPatternsMock = ({ +export const indexPatternsMock = { getCache: () => { return [indexPatternMock]; }, @@ -19,4 +19,4 @@ export const indexPatternsMock = ({ } }, updateSavedObject: jest.fn(), -} as unknown) as jest.Mocked; +} as unknown as jest.Mocked; diff --git a/src/plugins/discover/public/__mocks__/saved_search.ts b/src/plugins/discover/public/__mocks__/saved_search.ts index c2d9bfeb1b4b..ebe65a577035 100644 --- a/src/plugins/discover/public/__mocks__/saved_search.ts +++ b/src/plugins/discover/public/__mocks__/saved_search.ts @@ -11,7 +11,7 @@ import { createSearchSourceMock } from '../../../data/public/mocks'; import { indexPatternMock } from './index_pattern'; import { indexPatternWithTimefieldMock } from './index_pattern_with_timefield'; -export const savedSearchMock = ({ +export const savedSearchMock = { id: 'the-saved-search-id', type: 'search', attributes: { @@ -31,9 +31,9 @@ export const savedSearchMock = ({ migrationVersion: { search: '7.5.0' }, error: undefined, searchSource: createSearchSourceMock({ index: indexPatternMock }), -} as unknown) as SavedSearch; +} as unknown as SavedSearch; -export const savedSearchMockWithTimeField = ({ +export const savedSearchMockWithTimeField = { id: 'the-saved-search-id-with-timefield', type: 'search', attributes: { @@ -53,4 +53,4 @@ export const savedSearchMockWithTimeField = ({ migrationVersion: { search: '7.5.0' }, error: undefined, searchSource: createSearchSourceMock({ index: indexPatternWithTimefieldMock }), -} as unknown) as SavedSearch; +} as unknown as SavedSearch; diff --git a/src/plugins/discover/public/__mocks__/services.ts b/src/plugins/discover/public/__mocks__/services.ts index 47c79c429f66..d24aefb6c819 100644 --- a/src/plugins/discover/public/__mocks__/services.ts +++ b/src/plugins/discover/public/__mocks__/services.ts @@ -22,7 +22,7 @@ import { TopNavMenu } from '../../../navigation/public'; import { FORMATS_UI_SETTINGS } from 'src/plugins/field_formats/common'; const dataPlugin = dataPluginMock.createStartContract(); -export const discoverServiceMock = ({ +export const discoverServiceMock = { core: coreMock.createStart(), chrome: chromeServiceMock.createStartContract(), history: () => ({ @@ -89,4 +89,4 @@ export const discoverServiceMock = ({ useChartsTheme: jest.fn(() => EUI_CHARTS_THEME_LIGHT.theme), useChartsBaseTheme: jest.fn(() => EUI_CHARTS_THEME_LIGHT.theme), }, -} as unknown) as DiscoverServices; +} as unknown as DiscoverServices; diff --git a/src/plugins/discover/public/__mocks__/ui_settings.ts b/src/plugins/discover/public/__mocks__/ui_settings.ts index 95d3e6ad2ba8..be50f73041f8 100644 --- a/src/plugins/discover/public/__mocks__/ui_settings.ts +++ b/src/plugins/discover/public/__mocks__/ui_settings.ts @@ -16,7 +16,7 @@ import { SEARCH_FIELDS_FROM_SOURCE, } from '../../common'; -export const uiSettingsMock = ({ +export const uiSettingsMock = { get: (key: string) => { if (key === SAMPLE_SIZE_SETTING) { return 10; @@ -32,4 +32,4 @@ export const uiSettingsMock = ({ return false; } }, -} as unknown) as IUiSettingsClient; +} as unknown as IUiSettingsClient; diff --git a/src/plugins/discover/public/application/apps/context/context_app.test.tsx b/src/plugins/discover/public/application/apps/context/context_app.test.tsx index a21b035c335d..d54a4f8bed24 100644 --- a/src/plugins/discover/public/application/apps/context/context_app.test.tsx +++ b/src/plugins/discover/public/application/apps/context/context_app.test.tsx @@ -42,7 +42,7 @@ describe('ContextApp test', () => { }; beforeEach(() => { - setServices(({ + setServices({ data: { search: { searchSource: { @@ -65,7 +65,7 @@ describe('ContextApp test', () => { history: () => {}, filterManager: mockFilterManager, uiSettings: uiSettingsMock, - } as unknown) as DiscoverServices); + } as unknown as DiscoverServices); }); it('renders correctly', async () => { diff --git a/src/plugins/discover/public/application/apps/context/context_app_content.test.tsx b/src/plugins/discover/public/application/apps/context/context_app_content.test.tsx index 17caef09c4c0..9b1c47d37203 100644 --- a/src/plugins/discover/public/application/apps/context/context_app_content.test.tsx +++ b/src/plugins/discover/public/application/apps/context/context_app_content.test.tsx @@ -48,15 +48,15 @@ describe('ContextAppContent test', () => { }, sort: [1603114502000, 2092], }; - defaultProps = ({ + defaultProps = { columns: ['order_date', '_source'], indexPattern: indexPatternMock, - appState: ({} as unknown) as AppState, - stateContainer: ({} as unknown) as GetStateReturn, + appState: {} as unknown as AppState, + stateContainer: {} as unknown as GetStateReturn, anchorStatus: LoadingStatus.LOADED, predecessorsStatus: LoadingStatus.LOADED, successorsStatus: LoadingStatus.LOADED, - rows: ([hit] as unknown) as EsHitRecordList, + rows: [hit] as unknown as EsHitRecordList, predecessors: [], successors: [], defaultStepSize: 5, @@ -72,7 +72,7 @@ describe('ContextAppContent test', () => { isLegacy: true, setAppState: () => {}, addFilter: () => {}, - } as unknown) as ContextAppContentProps; + } as unknown as ContextAppContentProps; }); it('should render legacy table correctly', () => { diff --git a/src/plugins/discover/public/application/apps/context/services/_stubs.ts b/src/plugins/discover/public/application/apps/context/services/_stubs.ts index d0318c9efbab..7e1473b876af 100644 --- a/src/plugins/discover/public/application/apps/context/services/_stubs.ts +++ b/src/plugins/discover/public/application/apps/context/services/_stubs.ts @@ -19,7 +19,7 @@ type SortHit = { }; export function createIndexPatternsStub() { - return ({ + return { get: sinon.spy((indexPatternId) => Promise.resolve({ id: indexPatternId, @@ -27,7 +27,7 @@ export function createIndexPatternsStub() { popularizeField: () => {}, }) ), - } as unknown) as IndexPatternsContract; + } as unknown as IndexPatternsContract; } /** diff --git a/src/plugins/discover/public/application/apps/context/services/anchor.test.ts b/src/plugins/discover/public/application/apps/context/services/anchor.test.ts index b58369781a4a..b4a76fa45ec2 100644 --- a/src/plugins/discover/public/application/apps/context/services/anchor.test.ts +++ b/src/plugins/discover/public/application/apps/context/services/anchor.test.ts @@ -24,7 +24,7 @@ describe('context app', function () { describe('function fetchAnchor', function () { beforeEach(() => { - searchSourceStub = createSearchSourceStub(([{ _id: 'hit1' }] as unknown) as EsHitRecordList); + searchSourceStub = createSearchSourceStub([{ _id: 'hit1' }] as unknown as EsHitRecordList); fetchAnchor = fetchAnchorProvider(createIndexPatternsStub(), searchSourceStub); }); @@ -173,7 +173,7 @@ describe('context app', function () { describe('useNewFields API', () => { beforeEach(() => { - searchSourceStub = createSearchSourceStub(([{ _id: 'hit1' }] as unknown) as EsHitRecordList); + searchSourceStub = createSearchSourceStub([{ _id: 'hit1' }] as unknown as EsHitRecordList); fetchAnchor = fetchAnchorProvider(createIndexPatternsStub(), searchSourceStub, true); }); diff --git a/src/plugins/discover/public/application/apps/context/services/context.predecessors.test.ts b/src/plugins/discover/public/application/apps/context/services/context.predecessors.test.ts index 6fad858488c4..028dec7b9fe1 100644 --- a/src/plugins/discover/public/application/apps/context/services/context.predecessors.test.ts +++ b/src/plugins/discover/public/application/apps/context/services/context.predecessors.test.ts @@ -46,7 +46,7 @@ describe('context predecessors', function () { beforeEach(() => { mockSearchSource = createContextSearchSourceStub('@timestamp'); - setServices(({ + setServices({ data: { search: { searchSource: { @@ -54,7 +54,7 @@ describe('context predecessors', function () { }, }, }, - } as unknown) as DiscoverServices); + } as unknown as DiscoverServices); fetchPredecessors = ( indexPatternId, @@ -238,7 +238,7 @@ describe('context predecessors', function () { beforeEach(() => { mockSearchSource = createContextSearchSourceStub('@timestamp'); - setServices(({ + setServices({ data: { search: { searchSource: { @@ -246,7 +246,7 @@ describe('context predecessors', function () { }, }, }, - } as unknown) as DiscoverServices); + } as unknown as DiscoverServices); fetchPredecessors = ( indexPatternId, diff --git a/src/plugins/discover/public/application/apps/context/services/context.successors.test.ts b/src/plugins/discover/public/application/apps/context/services/context.successors.test.ts index 6c44f0aa3f7b..656491f01f9c 100644 --- a/src/plugins/discover/public/application/apps/context/services/context.successors.test.ts +++ b/src/plugins/discover/public/application/apps/context/services/context.successors.test.ts @@ -45,7 +45,7 @@ describe('context successors', function () { beforeEach(() => { mockSearchSource = createContextSearchSourceStub('@timestamp'); - setServices(({ + setServices({ data: { search: { searchSource: { @@ -53,7 +53,7 @@ describe('context successors', function () { }, }, }, - } as unknown) as DiscoverServices); + } as unknown as DiscoverServices); fetchSuccessors = ( indexPatternId, @@ -240,7 +240,7 @@ describe('context successors', function () { beforeEach(() => { mockSearchSource = createContextSearchSourceStub('@timestamp'); - setServices(({ + setServices({ data: { search: { searchSource: { @@ -248,7 +248,7 @@ describe('context successors', function () { }, }, }, - } as unknown) as DiscoverServices); + } as unknown as DiscoverServices); fetchSuccessors = ( indexPatternId, diff --git a/src/plugins/discover/public/application/apps/context/services/context_state.test.ts b/src/plugins/discover/public/application/apps/context/services/context_state.test.ts index 401bc4d38a35..07491caf8989 100644 --- a/src/plugins/discover/public/application/apps/context/services/context_state.test.ts +++ b/src/plugins/discover/public/application/apps/context/services/context_state.test.ts @@ -28,7 +28,7 @@ describe('Test Discover Context State', () => { history, uiSettings: { get: (key: string) => - ((key === SEARCH_FIELDS_FROM_SOURCE ? true : ['_source']) as unknown) as T, + (key === SEARCH_FIELDS_FROM_SOURCE ? true : ['_source']) as unknown as T, } as IUiSettingsClient, }); state.startSync(); diff --git a/src/plugins/discover/public/application/apps/context/services/utils/fetch_hits_in_interval.ts b/src/plugins/discover/public/application/apps/context/services/utils/fetch_hits_in_interval.ts index feacf940e312..4cfbee2dc02b 100644 --- a/src/plugins/discover/public/application/apps/context/services/utils/fetch_hits_in_interval.ts +++ b/src/plugins/discover/public/application/apps/context/services/utils/fetch_hits_in_interval.ts @@ -77,5 +77,5 @@ export async function fetchHitsInInterval( .fetch(); // TODO: There's a difference in the definition of SearchResponse and EsHitRecord - return ((response.hits?.hits as unknown) as EsHitRecord[]) || []; + return (response.hits?.hits as unknown as EsHitRecord[]) || []; } diff --git a/src/plugins/discover/public/application/apps/context/utils/use_context_app_fetch.test.ts b/src/plugins/discover/public/application/apps/context/utils/use_context_app_fetch.test.ts index 8d6d81bcaa49..5efd5e1195c5 100644 --- a/src/plugins/discover/public/application/apps/context/utils/use_context_app_fetch.test.ts +++ b/src/plugins/discover/public/application/apps/context/utils/use_context_app_fetch.test.ts @@ -51,7 +51,7 @@ jest.mock('../services/anchor', () => ({ const initDefaults = (tieBreakerFields: string[], indexPatternId = 'the-index-pattern-id') => { const dangerNotification = jest.fn(); - setServices(({ + setServices({ data: { search: { searchSource: { @@ -71,11 +71,11 @@ const initDefaults = (tieBreakerFields: string[], indexPatternId = 'the-index-pa } }, }, - } as unknown) as DiscoverServices); + } as unknown as DiscoverServices); return { dangerNotification, - props: ({ + props: { anchorId: 'mock_anchor_id', indexPatternId, indexPattern: indexPatternMock, @@ -86,7 +86,7 @@ const initDefaults = (tieBreakerFields: string[], indexPatternId = 'the-index-pa }, useNewFieldsApi: false, services: getServices(), - } as unknown) as ContextAppFetchProps, + } as unknown as ContextAppFetchProps, }; }; diff --git a/src/plugins/discover/public/application/apps/main/components/chart/discover_chart.test.tsx b/src/plugins/discover/public/application/apps/main/components/chart/discover_chart.test.tsx index 732dee6106b3..63ce310e878e 100644 --- a/src/plugins/discover/public/application/apps/main/components/chart/discover_chart.test.tsx +++ b/src/plugins/discover/public/application/apps/main/components/chart/discover_chart.test.tsx @@ -34,23 +34,11 @@ function getProps(timefield?: string) { result: Number(esHits.length), }) as DataTotalHits$; - const chartData = ({ + const chartData = { xAxisOrderedValues: [ - 1623880800000, - 1623967200000, - 1624053600000, - 1624140000000, - 1624226400000, - 1624312800000, - 1624399200000, - 1624485600000, - 1624572000000, - 1624658400000, - 1624744800000, - 1624831200000, - 1624917600000, - 1625004000000, - 1625090400000, + 1623880800000, 1623967200000, 1624053600000, 1624140000000, 1624226400000, 1624312800000, + 1624399200000, 1624485600000, 1624572000000, 1624658400000, 1624744800000, 1624831200000, + 1624917600000, 1625004000000, 1625090400000, ], xAxisFormat: { id: 'date', params: { pattern: 'YYYY-MM-DD' } }, xAxisLabel: 'order_date per day', @@ -83,7 +71,7 @@ function getProps(timefield?: string) { { x: 1625004000000, y: 137 }, { x: 1625090400000, y: 66 }, ], - } as unknown) as Chart; + } as unknown as Chart; const charts$ = new BehaviorSubject({ fetchStatus: FetchStatus.COMPLETE, diff --git a/src/plugins/discover/public/application/apps/main/components/chart/histogram.tsx b/src/plugins/discover/public/application/apps/main/components/chart/histogram.tsx index bfb4cd138076..674db3f01e68 100644 --- a/src/plugins/discover/public/application/apps/main/components/chart/histogram.tsx +++ b/src/plugins/discover/public/application/apps/main/components/chart/histogram.tsx @@ -78,16 +78,17 @@ export function DiscoverHistogram({ ); const onElementClick = useCallback( - (xInterval: number): ElementClickListener => ([elementData]) => { - const startRange = (elementData as XYChartElementEvent)[0].x; + (xInterval: number): ElementClickListener => + ([elementData]) => { + const startRange = (elementData as XYChartElementEvent)[0].x; - const range = { - from: startRange, - to: startRange + xInterval, - }; + const range = { + from: startRange, + to: startRange + xInterval, + }; - timefilterUpdateHandler(range); - }, + timefilterUpdateHandler(range); + }, [timefilterUpdateHandler] ); diff --git a/src/plugins/discover/public/application/apps/main/components/doc_table/actions/columns.test.ts b/src/plugins/discover/public/application/apps/main/components/doc_table/actions/columns.test.ts index 3b73044b68e0..d0984ff6fa79 100644 --- a/src/plugins/discover/public/application/apps/main/components/doc_table/actions/columns.test.ts +++ b/src/plugins/discover/public/application/apps/main/components/doc_table/actions/columns.test.ts @@ -15,11 +15,11 @@ import { AppState } from '../../../services/discover_state'; function getStateColumnAction(state: {}, setAppState: (state: Partial) => void) { return getStateColumnActions({ - capabilities: ({ + capabilities: { discover: { save: false, }, - } as unknown) as Capabilities, + } as unknown as Capabilities, config: configMock, indexPattern: indexPatternMock, indexPatterns: indexPatternsMock, diff --git a/src/plugins/discover/public/application/apps/main/components/doc_table/components/table_header/table_header.test.tsx b/src/plugins/discover/public/application/apps/main/components/doc_table/components/table_header/table_header.test.tsx index 83320c1b6d3d..2738a04559fc 100644 --- a/src/plugins/discover/public/application/apps/main/components/doc_table/components/table_header/table_header.test.tsx +++ b/src/plugins/discover/public/application/apps/main/components/doc_table/components/table_header/table_header.test.tsx @@ -14,7 +14,7 @@ import { findTestSubject } from '@elastic/eui/lib/test'; import { SortOrder } from './helpers'; function getMockIndexPattern() { - return ({ + return { id: 'test', title: 'Test', timeFieldName: 'time', @@ -41,7 +41,7 @@ function getMockIndexPattern() { } as IndexPatternField; } }, - } as unknown) as IndexPattern; + } as unknown as IndexPattern; } function getMockProps(props = {}) { diff --git a/src/plugins/discover/public/application/apps/main/components/doc_table/components/table_row.test.tsx b/src/plugins/discover/public/application/apps/main/components/doc_table/components/table_row.test.tsx index 59ced9d5668a..887564168ac8 100644 --- a/src/plugins/discover/public/application/apps/main/components/doc_table/components/table_row.test.tsx +++ b/src/plugins/discover/public/application/apps/main/components/doc_table/components/table_row.test.tsx @@ -56,7 +56,7 @@ describe('Doc table row component', () => { beforeEach(() => { mockInlineFilter = jest.fn(); - defaultProps = ({ + defaultProps = { columns: ['_source'], filter: mockInlineFilter, indexPattern: indexPatternWithTimefieldMock, @@ -65,11 +65,11 @@ describe('Doc table row component', () => { filterManager: mockFilterManager, addBasePath: (path: string) => path, hideTimeColumn: true, - } as unknown) as TableRowProps; + } as unknown as TableRowProps; - setServices(({ + setServices({ uiSettings: uiSettingsMock, - } as unknown) as DiscoverServices); + } as unknown as DiscoverServices); setDocViewsRegistry(new DocViewsRegistry()); }); diff --git a/src/plugins/discover/public/application/apps/main/components/doc_table/doc_table_embeddable.tsx b/src/plugins/discover/public/application/apps/main/components/doc_table/doc_table_embeddable.tsx index c01f661eb116..84edf147dea4 100644 --- a/src/plugins/discover/public/application/apps/main/components/doc_table/doc_table_embeddable.tsx +++ b/src/plugins/discover/public/application/apps/main/components/doc_table/doc_table_embeddable.tsx @@ -25,17 +25,10 @@ const DocTableWrapperMemoized = memo(DocTableWrapper); export const DocTableEmbeddable = (props: DocTableEmbeddableProps) => { const tableWrapperRef = useRef(null); - const { - currentPage, - pageSize, - totalPages, - startIndex, - hasNextPage, - changePage, - changePageSize, - } = usePager({ - totalItems: props.rows.length, - }); + const { currentPage, pageSize, totalPages, startIndex, hasNextPage, changePage, changePageSize } = + usePager({ + totalItems: props.rows.length, + }); const showPagination = totalPages !== 0; const scrollTop = useCallback(() => { @@ -44,11 +37,10 @@ export const DocTableEmbeddable = (props: DocTableEmbeddableProps) => { } }, []); - const pageOfItems = useMemo(() => props.rows.slice(startIndex, pageSize + startIndex), [ - pageSize, - startIndex, - props.rows, - ]); + const pageOfItems = useMemo( + () => props.rows.slice(startIndex, pageSize + startIndex), + [pageSize, startIndex, props.rows] + ); const onPageChange = useCallback( (page: number) => { diff --git a/src/plugins/discover/public/application/apps/main/components/doc_table/lib/row_formatter.test.ts b/src/plugins/discover/public/application/apps/main/components/doc_table/lib/row_formatter.test.ts index c15c02264759..9cd2959f5d72 100644 --- a/src/plugins/discover/public/application/apps/main/components/doc_table/lib/row_formatter.test.ts +++ b/src/plugins/discover/public/application/apps/main/components/doc_table/lib/row_formatter.test.ts @@ -63,11 +63,11 @@ describe('Row formatter', () => { beforeEach(() => { // @ts-expect-error indexPattern.formatHit = formatHitMock; - setServices(({ + setServices({ uiSettings: { get: () => 100, }, - } as unknown) as DiscoverServices); + } as unknown as DiscoverServices); }); it('formats document properly', () => { @@ -110,11 +110,11 @@ describe('Row formatter', () => { }); it('limits number of rendered items', () => { - setServices(({ + setServices({ uiSettings: { get: () => 1, }, - } as unknown) as DiscoverServices); + } as unknown as DiscoverServices); expect(formatRow(hit, indexPattern, [])).toMatchInlineSnapshot(` { + const indexPatternList = [indexPattern].map((ip) => { return { ...ip, ...{ attributes: { title: ip.title } } }; - }) as unknown) as Array>; + }) as unknown as Array>; const main$ = new BehaviorSubject({ fetchStatus: FetchStatus.COMPLETE, @@ -60,23 +60,11 @@ function getProps(indexPattern: IndexPattern): DiscoverLayoutProps { result: Number(esHits.length), }) as DataTotalHits$; - const chartData = ({ + const chartData = { xAxisOrderedValues: [ - 1623880800000, - 1623967200000, - 1624053600000, - 1624140000000, - 1624226400000, - 1624312800000, - 1624399200000, - 1624485600000, - 1624572000000, - 1624658400000, - 1624744800000, - 1624831200000, - 1624917600000, - 1625004000000, - 1625090400000, + 1623880800000, 1623967200000, 1624053600000, 1624140000000, 1624226400000, 1624312800000, + 1624399200000, 1624485600000, 1624572000000, 1624658400000, 1624744800000, 1624831200000, + 1624917600000, 1625004000000, 1625090400000, ], xAxisFormat: { id: 'date', params: { pattern: 'YYYY-MM-DD' } }, xAxisLabel: 'order_date per day', @@ -109,7 +97,7 @@ function getProps(indexPattern: IndexPattern): DiscoverLayoutProps { { x: 1625004000000, y: 137 }, { x: 1625090400000, y: 66 }, ], - } as unknown) as Chart; + } as unknown as Chart; const charts$ = new BehaviorSubject({ fetchStatus: FetchStatus.COMPLETE, diff --git a/src/plugins/discover/public/application/apps/main/components/sidebar/change_indexpattern.tsx b/src/plugins/discover/public/application/apps/main/components/sidebar/change_indexpattern.tsx index 5f2f35e2419d..1c44cebb2c9a 100644 --- a/src/plugins/discover/public/application/apps/main/components/sidebar/change_indexpattern.tsx +++ b/src/plugins/discover/public/application/apps/main/components/sidebar/change_indexpattern.tsx @@ -83,7 +83,7 @@ export function ChangeIndexPattern({ checked: id === indexPatternId ? 'on' : undefined, }))} onChange={(choices) => { - const choice = (choices.find(({ checked }) => checked) as unknown) as { + const choice = choices.find(({ checked }) => checked) as unknown as { value: string; }; if (choice.value !== indexPatternId) { diff --git a/src/plugins/discover/public/application/apps/main/components/sidebar/discover_index_pattern.test.tsx b/src/plugins/discover/public/application/apps/main/components/sidebar/discover_index_pattern.test.tsx index 45d6faa9606e..50af66511de3 100644 --- a/src/plugins/discover/public/application/apps/main/components/sidebar/discover_index_pattern.test.tsx +++ b/src/plugins/discover/public/application/apps/main/components/sidebar/discover_index_pattern.test.tsx @@ -66,11 +66,11 @@ function selectIndexPatternPickerOption(instance: ShallowWrapper, selectedLabel: describe('DiscoverIndexPattern', () => { test('Invalid props dont cause an exception', () => { - const props = ({ + const props = { indexPatternList: null, selectedIndexPattern: null, onChangeIndexPattern: jest.fn(), - } as unknown) as DiscoverIndexPatternProps; + } as unknown as DiscoverIndexPatternProps; expect(shallow()).toMatchSnapshot(`""`); }); diff --git a/src/plugins/discover/public/application/apps/main/components/sidebar/discover_index_pattern_management.test.tsx b/src/plugins/discover/public/application/apps/main/components/sidebar/discover_index_pattern_management.test.tsx index a7db6f22395e..4e41c457ab8e 100644 --- a/src/plugins/discover/public/application/apps/main/components/sidebar/discover_index_pattern_management.test.tsx +++ b/src/plugins/discover/public/application/apps/main/components/sidebar/discover_index_pattern_management.test.tsx @@ -14,7 +14,7 @@ import { DiscoverServices } from '../../../../../build_services'; import { DiscoverIndexPatternManagement } from './discover_index_pattern_management'; import { stubLogstashIndexPattern } from '../../../../../../../data/common/stubs'; -const mockServices = ({ +const mockServices = { history: () => ({ location: { search: '', @@ -48,7 +48,7 @@ const mockServices = ({ }, }, }, -} as unknown) as DiscoverServices; +} as unknown as DiscoverServices; describe('Discover IndexPattern Management', () => { const indexPattern = stubLogstashIndexPattern; diff --git a/src/plugins/discover/public/application/apps/main/components/sidebar/discover_index_pattern_management.tsx b/src/plugins/discover/public/application/apps/main/components/sidebar/discover_index_pattern_management.tsx index 644c673f0eff..84f4cc1cecc0 100644 --- a/src/plugins/discover/public/application/apps/main/components/sidebar/discover_index_pattern_management.tsx +++ b/src/plugins/discover/public/application/apps/main/components/sidebar/discover_index_pattern_management.tsx @@ -35,7 +35,8 @@ export interface DiscoverIndexPatternManagementProps { export function DiscoverIndexPatternManagement(props: DiscoverIndexPatternManagementProps) { const { indexPatternFieldEditor, core } = props.services; const { useNewFieldsApi, selectedIndexPattern, editField } = props; - const indexPatternFieldEditPermission = indexPatternFieldEditor?.userPermissions.editIndexPattern(); + const indexPatternFieldEditPermission = + indexPatternFieldEditor?.userPermissions.editIndexPattern(); const canEditIndexPatternField = !!indexPatternFieldEditPermission && useNewFieldsApi; const [isAddIndexPatternFieldPopoverOpen, setIsAddIndexPatternFieldPopoverOpen] = useState(false); diff --git a/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar.test.tsx b/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar.test.tsx index 988a434f913a..e53bf006e2b4 100644 --- a/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar.test.tsx +++ b/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar.test.tsx @@ -31,9 +31,9 @@ function getCompProps(): DiscoverSidebarProps { const indexPattern = stubLogstashIndexPattern; // @ts-expect-error _.each() is passing additional args to flattenHit - const hits = (each(cloneDeep(realHits), indexPattern.flattenHit) as Array< + const hits = each(cloneDeep(realHits), indexPattern.flattenHit) as Array< Record - >) as ElasticSearchHit[]; + > as ElasticSearchHit[]; const indexPatternList = [ { id: '0', attributes: { title: 'b' } } as SavedObject, diff --git a/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar.tsx b/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar.tsx index 189620282f2f..97bc305065d3 100644 --- a/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar.tsx +++ b/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar.tsx @@ -101,7 +101,8 @@ export function DiscoverSidebarComponent({ const [fields, setFields] = useState(null); const { indexPatternFieldEditor } = services; - const indexPatternFieldEditPermission = indexPatternFieldEditor?.userPermissions.editIndexPattern(); + const indexPatternFieldEditPermission = + indexPatternFieldEditor?.userPermissions.editIndexPattern(); const canEditIndexPatternField = !!indexPatternFieldEditPermission && useNewFieldsApi; const [scrollContainer, setScrollContainer] = useState(null); const [fieldsToRender, setFieldsToRender] = useState(FIELDS_PER_PAGE); @@ -131,9 +132,10 @@ export function DiscoverSidebarComponent({ [documents, columns, selectedIndexPattern] ); - const popularLimit = useMemo(() => services.uiSettings.get(FIELDS_LIMIT_SETTING), [ - services.uiSettings, - ]); + const popularLimit = useMemo( + () => services.uiSettings.get(FIELDS_LIMIT_SETTING), + [services.uiSettings] + ); const { selected: selectedFields, diff --git a/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar_responsive.test.tsx b/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar_responsive.test.tsx index fc1c09ec8c82..9d73f885c988 100644 --- a/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar_responsive.test.tsx +++ b/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar_responsive.test.tsx @@ -27,7 +27,7 @@ import { FetchStatus } from '../../../../types'; import { DataDocuments$ } from '../../services/use_saved_search'; import { stubLogstashIndexPattern } from '../../../../../../../data/common/stubs'; -const mockServices = ({ +const mockServices = { history: () => ({ location: { search: '', @@ -48,7 +48,7 @@ const mockServices = ({ } }, }, -} as unknown) as DiscoverServices; +} as unknown as DiscoverServices; const mockfieldCounts: Record = {}; const mockCalcFieldCounts = jest.fn(() => { @@ -72,9 +72,9 @@ function getCompProps(): DiscoverSidebarResponsiveProps { const indexPattern = stubLogstashIndexPattern; // @ts-expect-error _.each() is passing additional args to flattenHit - const hits = (each(cloneDeep(realHits), indexPattern.flattenHit) as Array< + const hits = each(cloneDeep(realHits), indexPattern.flattenHit) as Array< Record - >) as ElasticSearchHit[]; + > as ElasticSearchHit[]; const indexPatternList = [ { id: '0', attributes: { title: 'b' } } as SavedObject, diff --git a/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar_responsive.tsx b/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar_responsive.tsx index 90a3d33ddbe6..ade9c3aae4b2 100644 --- a/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar_responsive.tsx +++ b/src/plugins/discover/public/application/apps/main/components/sidebar/discover_sidebar_responsive.tsx @@ -179,7 +179,8 @@ export function DiscoverSidebarResponsive(props: DiscoverSidebarResponsiveProps) const editField = useCallback( (fieldName?: string) => { - const indexPatternFieldEditPermission = indexPatternFieldEditor?.userPermissions.editIndexPattern(); + const indexPatternFieldEditPermission = + indexPatternFieldEditor?.userPermissions.editIndexPattern(); const canEditIndexPatternField = !!indexPatternFieldEditPermission && useNewFieldsApi; if (!canEditIndexPatternField || !selectedIndexPattern) { return; diff --git a/src/plugins/discover/public/application/apps/main/components/timechart_header/timechart_header.test.tsx b/src/plugins/discover/public/application/apps/main/components/timechart_header/timechart_header.test.tsx index e942ec59c45e..00dacc2166c6 100644 --- a/src/plugins/discover/public/application/apps/main/components/timechart_header/timechart_header.test.tsx +++ b/src/plugins/discover/public/application/apps/main/components/timechart_header/timechart_header.test.tsx @@ -18,23 +18,11 @@ import { BehaviorSubject } from 'rxjs'; import { Chart } from '../chart/point_series'; import { DataCharts$ } from '../../services/use_saved_search'; -const chartData = ({ +const chartData = { xAxisOrderedValues: [ - 1623880800000, - 1623967200000, - 1624053600000, - 1624140000000, - 1624226400000, - 1624312800000, - 1624399200000, - 1624485600000, - 1624572000000, - 1624658400000, - 1624744800000, - 1624831200000, - 1624917600000, - 1625004000000, - 1625090400000, + 1623880800000, 1623967200000, 1624053600000, 1624140000000, 1624226400000, 1624312800000, + 1624399200000, 1624485600000, 1624572000000, 1624658400000, 1624744800000, 1624831200000, + 1624917600000, 1625004000000, 1625090400000, ], xAxisFormat: { id: 'date', params: { pattern: 'YYYY-MM-DD' } }, xAxisLabel: 'order_date per day', @@ -67,7 +55,7 @@ const chartData = ({ { x: 1625004000000, y: 137 }, { x: 1625090400000, y: 66 }, ], -} as unknown) as Chart; +} as unknown as Chart; describe('timechart header', function () { let props: TimechartHeaderProps; let component: ReactWrapper; diff --git a/src/plugins/discover/public/application/apps/main/components/top_nav/get_top_nav_links.test.ts b/src/plugins/discover/public/application/apps/main/components/top_nav/get_top_nav_links.test.ts index fd918429b57d..d31ac6e0f2fe 100644 --- a/src/plugins/discover/public/application/apps/main/components/top_nav/get_top_nav_links.test.ts +++ b/src/plugins/discover/public/application/apps/main/components/top_nav/get_top_nav_links.test.ts @@ -13,7 +13,7 @@ import { savedSearchMock } from '../../../../../__mocks__/saved_search'; import { DiscoverServices } from '../../../../../build_services'; import { GetStateReturn } from '../../services/discover_state'; -const services = ({ +const services = { capabilities: { discover: { save: true, @@ -22,9 +22,9 @@ const services = ({ save: true, }, }, -} as unknown) as DiscoverServices; +} as unknown as DiscoverServices; -const state = ({} as unknown) as GetStateReturn; +const state = {} as unknown as GetStateReturn; test('getTopNavLinks result', () => { const topNavLinks = getTopNavLinks({ diff --git a/src/plugins/discover/public/application/apps/main/components/top_nav/on_save_search.test.tsx b/src/plugins/discover/public/application/apps/main/components/top_nav/on_save_search.test.tsx index e5f44a0fbf21..1f0cee0b7567 100644 --- a/src/plugins/discover/public/application/apps/main/components/top_nav/on_save_search.test.tsx +++ b/src/plugins/discover/public/application/apps/main/components/top_nav/on_save_search.test.tsx @@ -17,12 +17,12 @@ import { GetStateReturn } from '../../services/discover_state'; import { i18nServiceMock } from '../../../../../../../../core/public/mocks'; test('onSaveSearch', async () => { - const serviceMock = ({ + const serviceMock = { core: { i18n: i18nServiceMock.create(), }, - } as unknown) as DiscoverServices; - const stateMock = ({} as unknown) as GetStateReturn; + } as unknown as DiscoverServices; + const stateMock = {} as unknown as GetStateReturn; await onSaveSearch({ indexPattern: indexPatternMock, diff --git a/src/plugins/discover/public/application/apps/main/discover_main_app.test.tsx b/src/plugins/discover/public/application/apps/main/discover_main_app.test.tsx index aa5a2bc9bfba..db29da87b464 100644 --- a/src/plugins/discover/public/application/apps/main/discover_main_app.test.tsx +++ b/src/plugins/discover/public/application/apps/main/discover_main_app.test.tsx @@ -22,9 +22,9 @@ setHeaderActionMenuMounter(jest.fn()); describe('DiscoverMainApp', () => { test('renders', () => { const { history } = createSearchSessionMock(); - const indexPatternList = ([indexPatternMock].map((ip) => { + const indexPatternList = [indexPatternMock].map((ip) => { return { ...ip, ...{ attributes: { title: ip.title } } }; - }) as unknown) as Array>; + }) as unknown as Array>; const props = { indexPatternList, diff --git a/src/plugins/discover/public/application/apps/main/discover_main_route.tsx b/src/plugins/discover/public/application/apps/main/discover_main_route.tsx index d7b49d023104..53f95f38c96b 100644 --- a/src/plugins/discover/public/application/apps/main/discover_main_route.tsx +++ b/src/plugins/discover/public/application/apps/main/discover_main_route.tsx @@ -85,7 +85,7 @@ export function DiscoverMainRoute({ services, history }: DiscoverMainProps) { setSavedSearch(loadedSavedSearch); if (savedSearchId) { chrome.recentlyAccessed.add( - ((loadedSavedSearch as unknown) as SavedObjectDeprecated).getFullPath(), + (loadedSavedSearch as unknown as SavedObjectDeprecated).getFullPath(), loadedSavedSearch.title, loadedSavedSearch.id ); diff --git a/src/plugins/discover/public/application/apps/main/services/discover_state.test.ts b/src/plugins/discover/public/application/apps/main/services/discover_state.test.ts index 8dad40d373f3..905d81a6fc71 100644 --- a/src/plugins/discover/public/application/apps/main/services/discover_state.test.ts +++ b/src/plugins/discover/public/application/apps/main/services/discover_state.test.ts @@ -22,8 +22,7 @@ let state: GetStateReturn; const getCurrentUrl = () => history.createHref(history.location); const uiSettingsMock = { - get: (key: string) => - ((key === SEARCH_FIELDS_FROM_SOURCE ? true : ['_source']) as unknown) as T, + get: (key: string) => (key === SEARCH_FIELDS_FROM_SOURCE ? true : ['_source']) as unknown as T, } as IUiSettingsClient; describe('Test discover state', () => { @@ -151,7 +150,7 @@ describe('Test discover state with legacy migration', () => { }); describe('createSearchSessionRestorationDataProvider', () => { - let mockSavedSearch: SavedSearch = ({} as unknown) as SavedSearch; + let mockSavedSearch: SavedSearch = {} as unknown as SavedSearch; const mockDataPlugin = dataPluginMock.createStartContract(); const searchSessionInfoProvider = createSearchSessionRestorationDataProvider({ data: mockDataPlugin, @@ -168,12 +167,12 @@ describe('createSearchSessionRestorationDataProvider', () => { }); test('Saved Search with a title returns saved search title', async () => { - mockSavedSearch = ({ id: 'id', title: 'Name' } as unknown) as SavedSearch; + mockSavedSearch = { id: 'id', title: 'Name' } as unknown as SavedSearch; expect(await searchSessionInfoProvider.getName()).toBe('Name'); }); test('Saved Search without a title returns default name', async () => { - mockSavedSearch = ({ id: 'id', title: undefined } as unknown) as SavedSearch; + mockSavedSearch = { id: 'id', title: undefined } as unknown as SavedSearch; expect(await searchSessionInfoProvider.getName()).toBe('Discover'); }); }); diff --git a/src/plugins/discover/public/application/apps/main/services/use_saved_search.ts b/src/plugins/discover/public/application/apps/main/services/use_saved_search.ts index 8ed6667f8acc..27b6fd3d487e 100644 --- a/src/plugins/discover/public/application/apps/main/services/use_saved_search.ts +++ b/src/plugins/discover/public/application/apps/main/services/use_saved_search.ts @@ -217,10 +217,10 @@ export const useSavedSearch = ({ useNewFieldsApi, ]); - const reset = useCallback(() => sendResetMsg(dataSubjects, initialFetchStatus), [ - dataSubjects, - initialFetchStatus, - ]); + const reset = useCallback( + () => sendResetMsg(dataSubjects, initialFetchStatus), + [dataSubjects, initialFetchStatus] + ); return { refetch$, diff --git a/src/plugins/discover/public/application/apps/main/utils/calc_field_counts.test.ts b/src/plugins/discover/public/application/apps/main/utils/calc_field_counts.test.ts index bdea6611d3b7..a13fd88df7c2 100644 --- a/src/plugins/discover/public/application/apps/main/utils/calc_field_counts.test.ts +++ b/src/plugins/discover/public/application/apps/main/utils/calc_field_counts.test.ts @@ -12,10 +12,10 @@ import { ElasticSearchHit } from '../../../doc_views/doc_views_types'; describe('calcFieldCounts', () => { test('returns valid field count data', async () => { - const rows = ([ + const rows = [ { _id: 1, _source: { message: 'test1', bytes: 20 } }, { _id: 2, _source: { name: 'test2', extension: 'jpg' } }, - ] as unknown) as ElasticSearchHit[]; + ] as unknown as ElasticSearchHit[]; const result = calcFieldCounts({}, rows, indexPatternMock); expect(result).toMatchInlineSnapshot(` Object { @@ -29,10 +29,10 @@ describe('calcFieldCounts', () => { `); }); test('updates field count data', async () => { - const rows = ([ + const rows = [ { _id: 1, _source: { message: 'test1', bytes: 20 } }, { _id: 2, _source: { name: 'test2', extension: 'jpg' } }, - ] as unknown) as ElasticSearchHit[]; + ] as unknown as ElasticSearchHit[]; const result = calcFieldCounts({ message: 2 }, rows, indexPatternMock); expect(result).toMatchInlineSnapshot(` Object { diff --git a/src/plugins/discover/public/application/apps/main/utils/fetch_chart.test.ts b/src/plugins/discover/public/application/apps/main/utils/fetch_chart.test.ts index 07228bf0e4c6..2c050a9391a8 100644 --- a/src/plugins/discover/public/application/apps/main/utils/fetch_chart.test.ts +++ b/src/plugins/discover/public/application/apps/main/utils/fetch_chart.test.ts @@ -89,7 +89,7 @@ describe('test fetchCharts', () => { subjects.totalHits$.subscribe((value) => stateArrHits.push(value.fetchStatus)); savedSearchMockWithTimeField.searchSource.fetch$ = () => - of(({ + of({ id: 'Fjk5bndxTHJWU2FldVRVQ0tYR0VqOFEcRWtWNDhOdG5SUzJYcFhONVVZVTBJQToxMDMwOQ==', rawResponse: { took: 2, @@ -113,7 +113,7 @@ describe('test fetchCharts', () => { total: 1, loaded: 1, isRestored: false, - } as unknown) as IKibanaSearchResponse>); + } as unknown as IKibanaSearchResponse>); fetchChart(subjects, savedSearchMockWithTimeField.searchSource, deps).subscribe({ complete: () => { diff --git a/src/plugins/discover/public/application/apps/main/utils/get_chart_agg_config.test.ts b/src/plugins/discover/public/application/apps/main/utils/get_chart_agg_config.test.ts index 198205087465..3eef49fe6ddc 100644 --- a/src/plugins/discover/public/application/apps/main/utils/get_chart_agg_config.test.ts +++ b/src/plugins/discover/public/application/apps/main/utils/get_chart_agg_config.test.ts @@ -14,7 +14,7 @@ describe('getChartAggConfigs', () => { test('is working', () => { const indexPattern = indexPatternWithTimefieldMock; const setField = jest.fn(); - const searchSource = ({ + const searchSource = { setField, getField: (name: string) => { if (name === 'index') { @@ -22,7 +22,7 @@ describe('getChartAggConfigs', () => { } }, removeField: jest.fn(), - } as unknown) as SearchSource; + } as unknown as SearchSource; const dataMock = dataPluginMock.createStartContract(); diff --git a/src/plugins/discover/public/application/apps/main/utils/get_dimensions.test.ts b/src/plugins/discover/public/application/apps/main/utils/get_dimensions.test.ts index 443fc634ba54..b98662f2db3b 100644 --- a/src/plugins/discover/public/application/apps/main/utils/get_dimensions.test.ts +++ b/src/plugins/discover/public/application/apps/main/utils/get_dimensions.test.ts @@ -15,7 +15,7 @@ import { getChartAggConfigs } from './get_chart_agg_configs'; test('getDimensions', () => { const indexPattern = indexPatternWithTimefieldMock; const setField = jest.fn(); - const searchSource = ({ + const searchSource = { setField, removeField: jest.fn(), getField: (name: string) => { @@ -23,7 +23,7 @@ test('getDimensions', () => { return indexPattern; } }, - } as unknown) as SearchSource; + } as unknown as SearchSource; const dataMock = dataPluginMock.createStartContract(); dataMock.query.timefilter.timefilter.getTime = () => { diff --git a/src/plugins/discover/public/application/apps/main/utils/get_sharing_data.test.ts b/src/plugins/discover/public/application/apps/main/utils/get_sharing_data.test.ts index ffad3d955c1a..25d0ca5d66eb 100644 --- a/src/plugins/discover/public/application/apps/main/utils/get_sharing_data.test.ts +++ b/src/plugins/discover/public/application/apps/main/utils/get_sharing_data.test.ts @@ -17,7 +17,7 @@ describe('getSharingData', () => { let mockConfig: IUiSettingsClient; beforeEach(() => { - mockConfig = ({ + mockConfig = { get: (key: string) => { if (key === SORT_DEFAULT_ORDER_SETTING) { return 'desc'; @@ -27,7 +27,7 @@ describe('getSharingData', () => { } return false; }, - } as unknown) as IUiSettingsClient; + } as unknown as IUiSettingsClient; }); test('returns valid data for sharing', async () => { @@ -116,14 +116,14 @@ describe('getSharingData', () => { }); test('fields conditionally do not have prepended timeField', async () => { - mockConfig = ({ + mockConfig = { get: (key: string) => { if (key === DOC_HIDE_TIME_COLUMN_SETTING) { return true; } return false; }, - } as unknown) as IUiSettingsClient; + } as unknown as IUiSettingsClient; const index = { ...indexPatternMock } as IndexPattern; index.timeFieldName = 'cool-timefield'; diff --git a/src/plugins/discover/public/application/apps/main/utils/get_sharing_data.ts b/src/plugins/discover/public/application/apps/main/utils/get_sharing_data.ts index 225d90c61de1..65001f49f4d6 100644 --- a/src/plugins/discover/public/application/apps/main/utils/get_sharing_data.ts +++ b/src/plugins/discover/public/application/apps/main/utils/get_sharing_data.ts @@ -65,7 +65,7 @@ export interface DiscoverCapabilities { export const showPublicUrlSwitch = (anonymousUserCapabilities: Capabilities) => { if (!anonymousUserCapabilities.discover) return false; - const discover = (anonymousUserCapabilities.discover as unknown) as DiscoverCapabilities; + const discover = anonymousUserCapabilities.discover as unknown as DiscoverCapabilities; return !!discover.show; }; diff --git a/src/plugins/discover/public/application/apps/main/utils/resolve_index_pattern.test.ts b/src/plugins/discover/public/application/apps/main/utils/resolve_index_pattern.test.ts index 9ebbeafd28e1..56c4f8e6cd1b 100644 --- a/src/plugins/discover/public/application/apps/main/utils/resolve_index_pattern.test.ts +++ b/src/plugins/discover/public/application/apps/main/utils/resolve_index_pattern.test.ts @@ -37,7 +37,7 @@ describe('Resolve index pattern tests', () => { test('getFallbackIndexPatternId with an indexPatterns array', async () => { const list = await indexPatternsMock.getCache(); const result = await getFallbackIndexPatternId( - (list as unknown) as IndexPatternSavedObject[], + list as unknown as IndexPatternSavedObject[], '' ); expect(result).toBe('the-index-pattern-id'); diff --git a/src/plugins/discover/public/application/apps/main/utils/resolve_index_pattern.ts b/src/plugins/discover/public/application/apps/main/utils/resolve_index_pattern.ts index 226db12114de..d30b67db3118 100644 --- a/src/plugins/discover/public/application/apps/main/utils/resolve_index_pattern.ts +++ b/src/plugins/discover/public/application/apps/main/utils/resolve_index_pattern.ts @@ -78,7 +78,7 @@ export async function loadIndexPattern( indexPatterns: IndexPatternsContract, config: IUiSettingsClient ): Promise { - const indexPatternList = ((await indexPatterns.getCache()) as unknown) as IndexPatternSavedObject[]; + const indexPatternList = (await indexPatterns.getCache()) as unknown as IndexPatternSavedObject[]; const actualId = getIndexPatternId(id, indexPatternList, config.get('defaultIndex')); return { diff --git a/src/plugins/discover/public/application/components/discover_grid/discover_grid.tsx b/src/plugins/discover/public/application/components/discover_grid/discover_grid.tsx index ca0692a8c903..0fe506b3b853 100644 --- a/src/plugins/discover/public/application/components/discover_grid/discover_grid.tsx +++ b/src/plugins/discover/public/application/components/discover_grid/discover_grid.tsx @@ -218,10 +218,10 @@ export const DiscoverGrid = ({ */ const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: defaultPageSize }); const rowCount = useMemo(() => (displayedRows ? displayedRows.length : 0), [displayedRows]); - const pageCount = useMemo(() => Math.ceil(rowCount / pagination.pageSize), [ - rowCount, - pagination, - ]); + const pageCount = useMemo( + () => Math.ceil(rowCount / pagination.pageSize), + [rowCount, pagination] + ); const isOnLastPage = pagination.pageIndex === pageCount - 1; const paginationObj = useMemo(() => { diff --git a/src/plugins/discover/public/application/components/discover_grid/discover_grid_context.tsx b/src/plugins/discover/public/application/components/discover_grid/discover_grid_context.tsx index 0103ad3d9887..8d0fbec9d793 100644 --- a/src/plugins/discover/public/application/components/discover_grid/discover_grid_context.tsx +++ b/src/plugins/discover/public/application/components/discover_grid/discover_grid_context.tsx @@ -21,6 +21,6 @@ export interface GridContext { setSelectedDocs: (selected: string[]) => void; } -const defaultContext = ({} as unknown) as GridContext; +const defaultContext = {} as unknown as GridContext; export const DiscoverGridContext = React.createContext(defaultContext); diff --git a/src/plugins/discover/public/application/components/discover_grid/discover_grid_document_selection.tsx b/src/plugins/discover/public/application/components/discover_grid/discover_grid_document_selection.tsx index 03c17c801fa9..c87d425d601c 100644 --- a/src/plugins/discover/public/application/components/discover_grid/discover_grid_document_selection.tsx +++ b/src/plugins/discover/public/application/components/discover_grid/discover_grid_document_selection.tsx @@ -31,9 +31,8 @@ export const getDocId = (doc: ElasticSearchHit & { _routing?: string }) => { return [doc._index, doc._id, routing].join('::'); }; export const SelectButton = ({ rowIndex, setCellProps }: EuiDataGridCellValueElementProps) => { - const { selectedDocs, expanded, rows, isDarkMode, setSelectedDocs } = useContext( - DiscoverGridContext - ); + const { selectedDocs, expanded, rows, isDarkMode, setSelectedDocs } = + useContext(DiscoverGridContext); const doc = useMemo(() => rows[rowIndex], [rows, rowIndex]); const id = useMemo(() => getDocId(doc), [doc]); const checked = useMemo(() => selectedDocs.includes(id), [selectedDocs, id]); diff --git a/src/plugins/discover/public/application/components/discover_grid/discover_grid_flyout.test.tsx b/src/plugins/discover/public/application/components/discover_grid/discover_grid_flyout.test.tsx index 60841799b139..83fa447a50ba 100644 --- a/src/plugins/discover/public/application/components/discover_grid/discover_grid_flyout.test.tsx +++ b/src/plugins/discover/public/application/components/discover_grid/discover_grid_flyout.test.tsx @@ -23,10 +23,10 @@ describe('Discover flyout', function () { const getProps = () => { const onClose = jest.fn(); - const services = ({ + const services = { filterManager: createFilterManagerMock(), addBasePath: (path: string) => `/base${path}`, - } as unknown) as DiscoverServices; + } as unknown as DiscoverServices; return { columns: ['date'], diff --git a/src/plugins/discover/public/application/components/discover_grid/get_render_cell_value.tsx b/src/plugins/discover/public/application/components/discover_grid/get_render_cell_value.tsx index ecef98915ff6..a05297158066 100644 --- a/src/plugins/discover/public/application/components/discover_grid/get_render_cell_value.tsx +++ b/src/plugins/discover/public/application/components/discover_grid/get_render_cell_value.tsx @@ -23,174 +23,180 @@ import { JsonCodeEditor } from '../json_code_editor/json_code_editor'; import { defaultMonacoEditorWidth } from './constants'; import { EsHitRecord } from '../../types'; -export const getRenderCellValueFn = ( - indexPattern: IndexPattern, - rows: ElasticSearchHit[] | undefined, - rowsFlattened: Array>, - useNewFieldsApi: boolean, - fieldsToShow: string[], - maxDocFieldsDisplayed: number -) => ({ rowIndex, columnId, isDetails, setCellProps }: EuiDataGridCellValueElementProps) => { - const row = rows ? rows[rowIndex] : undefined; - const rowFlattened = rowsFlattened - ? (rowsFlattened[rowIndex] as Record) - : undefined; - - const field = indexPattern.fields.getByName(columnId); - const ctx = useContext(DiscoverGridContext); - - useEffect(() => { - if ((row as EsHitRecord).isAnchor) { - setCellProps({ - className: 'dscDocsGrid__cell--highlight', - }); - } else if (ctx.expanded && row && ctx.expanded._id === row._id) { - setCellProps({ - style: { - backgroundColor: ctx.isDarkMode - ? themeDark.euiColorHighlight - : themeLight.euiColorHighlight, - }, - }); - } else { - setCellProps({ style: undefined }); - } - }, [ctx, row, setCellProps]); - - if (typeof row === 'undefined' || typeof rowFlattened === 'undefined') { - return -; - } - - if ( - useNewFieldsApi && - !field && - row && - row.fields && - !(row.fields as Record)[columnId] - ) { - const innerColumns = Object.fromEntries( - Object.entries(row.fields as Record).filter(([key]) => { - return key.indexOf(`${columnId}.`) === 0; - }) - ); - if (isDetails) { - // nicely formatted JSON for the expanded view - return {JSON.stringify(innerColumns, null, 2)}; +export const getRenderCellValueFn = + ( + indexPattern: IndexPattern, + rows: ElasticSearchHit[] | undefined, + rowsFlattened: Array>, + useNewFieldsApi: boolean, + fieldsToShow: string[], + maxDocFieldsDisplayed: number + ) => + ({ rowIndex, columnId, isDetails, setCellProps }: EuiDataGridCellValueElementProps) => { + const row = rows ? rows[rowIndex] : undefined; + const rowFlattened = rowsFlattened + ? (rowsFlattened[rowIndex] as Record) + : undefined; + + const field = indexPattern.fields.getByName(columnId); + const ctx = useContext(DiscoverGridContext); + + useEffect(() => { + if ((row as EsHitRecord).isAnchor) { + setCellProps({ + className: 'dscDocsGrid__cell--highlight', + }); + } else if (ctx.expanded && row && ctx.expanded._id === row._id) { + setCellProps({ + style: { + backgroundColor: ctx.isDarkMode + ? themeDark.euiColorHighlight + : themeLight.euiColorHighlight, + }, + }); + } else { + setCellProps({ style: undefined }); + } + }, [ctx, row, setCellProps]); + + if (typeof row === 'undefined' || typeof rowFlattened === 'undefined') { + return -; } - // Put the most important fields first - const highlights: Record = (row.highlight as Record) ?? {}; - const highlightPairs: Array<[string, string]> = []; - const sourcePairs: Array<[string, string]> = []; - Object.entries(innerColumns).forEach(([key, values]) => { - const subField = indexPattern.getFieldByName(key); - const displayKey = indexPattern.fields.getByName - ? indexPattern.fields.getByName(key)?.displayName - : undefined; - const formatter = subField - ? indexPattern.getFormatterForField(subField) - : { convert: (v: unknown, ...rest: unknown[]) => String(v) }; - const formatted = (values as unknown[]) - .map((val: unknown) => - formatter.convert(val, 'html', { - field: subField, - hit: row, - indexPattern, - }) - ) - .join(', '); - const pairs = highlights[key] ? highlightPairs : sourcePairs; - if (displayKey) { - if (fieldsToShow.includes(displayKey)) { - pairs.push([displayKey, formatted]); - } - } else { - pairs.push([key, formatted]); + if ( + useNewFieldsApi && + !field && + row && + row.fields && + !(row.fields as Record)[columnId] + ) { + const innerColumns = Object.fromEntries( + Object.entries(row.fields as Record).filter(([key]) => { + return key.indexOf(`${columnId}.`) === 0; + }) + ); + if (isDetails) { + // nicely formatted JSON for the expanded view + return {JSON.stringify(innerColumns, null, 2)}; } - }); - return ( - // If you change the styling of this list (specifically something that will change the line-height) - // make sure to adjust the img overwrites attached to dscDiscoverGrid__descriptionListDescription - // in discover_grid.scss - - {[...highlightPairs, ...sourcePairs].slice(0, maxDocFieldsDisplayed).map(([key, value]) => ( - - {key} - - - ))} - - ); - } + // Put the most important fields first + const highlights: Record = (row.highlight as Record) ?? {}; + const highlightPairs: Array<[string, string]> = []; + const sourcePairs: Array<[string, string]> = []; + Object.entries(innerColumns).forEach(([key, values]) => { + const subField = indexPattern.getFieldByName(key); + const displayKey = indexPattern.fields.getByName + ? indexPattern.fields.getByName(key)?.displayName + : undefined; + const formatter = subField + ? indexPattern.getFormatterForField(subField) + : { convert: (v: unknown, ...rest: unknown[]) => String(v) }; + const formatted = (values as unknown[]) + .map((val: unknown) => + formatter.convert(val, 'html', { + field: subField, + hit: row, + indexPattern, + }) + ) + .join(', '); + const pairs = highlights[key] ? highlightPairs : sourcePairs; + if (displayKey) { + if (fieldsToShow.includes(displayKey)) { + pairs.push([displayKey, formatted]); + } + } else { + pairs.push([key, formatted]); + } + }); - if (typeof rowFlattened[columnId] === 'object' && isDetails) { - return ( - } - width={defaultMonacoEditorWidth} - /> - ); - } + return ( + // If you change the styling of this list (specifically something that will change the line-height) + // make sure to adjust the img overwrites attached to dscDiscoverGrid__descriptionListDescription + // in discover_grid.scss + + {[...highlightPairs, ...sourcePairs] + .slice(0, maxDocFieldsDisplayed) + .map(([key, value]) => ( + + {key} + + + ))} + + ); + } - if (field && field.type === '_source') { - if (isDetails) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return ; + if (typeof rowFlattened[columnId] === 'object' && isDetails) { + return ( + } + width={defaultMonacoEditorWidth} + /> + ); } - const formatted = indexPattern.formatHit(row); - - // Put the most important fields first - const highlights: Record = (row.highlight as Record) ?? {}; - const highlightPairs: Array<[string, string]> = []; - const sourcePairs: Array<[string, string]> = []; - Object.entries(formatted).forEach(([key, val]) => { - const pairs = highlights[key] ? highlightPairs : sourcePairs; - const displayKey = indexPattern.fields.getByName - ? indexPattern.fields.getByName(key)?.displayName - : undefined; - if (displayKey) { - if (fieldsToShow.includes(displayKey)) { - pairs.push([displayKey, val as string]); - } - } else { - pairs.push([key, val as string]); + + if (field && field.type === '_source') { + if (isDetails) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return ; } - }); + const formatted = indexPattern.formatHit(row); + + // Put the most important fields first + const highlights: Record = (row.highlight as Record) ?? {}; + const highlightPairs: Array<[string, string]> = []; + const sourcePairs: Array<[string, string]> = []; + Object.entries(formatted).forEach(([key, val]) => { + const pairs = highlights[key] ? highlightPairs : sourcePairs; + const displayKey = indexPattern.fields.getByName + ? indexPattern.fields.getByName(key)?.displayName + : undefined; + if (displayKey) { + if (fieldsToShow.includes(displayKey)) { + pairs.push([displayKey, val as string]); + } + } else { + pairs.push([key, val as string]); + } + }); - return ( - - {[...highlightPairs, ...sourcePairs].slice(0, maxDocFieldsDisplayed).map(([key, value]) => ( - - {key} - - - ))} - - ); - } + return ( + + {[...highlightPairs, ...sourcePairs] + .slice(0, maxDocFieldsDisplayed) + .map(([key, value]) => ( + + {key} + + + ))} + + ); + } + + if (!field?.type && rowFlattened && typeof rowFlattened[columnId] === 'object') { + if (isDetails) { + // nicely formatted JSON for the expanded view + return {JSON.stringify(rowFlattened[columnId], null, 2)}; + } - if (!field?.type && rowFlattened && typeof rowFlattened[columnId] === 'object') { - if (isDetails) { - // nicely formatted JSON for the expanded view - return {JSON.stringify(rowFlattened[columnId], null, 2)}; + return {JSON.stringify(rowFlattened[columnId])}; } - return {JSON.stringify(rowFlattened[columnId])}; - } - - const valueFormatted = indexPattern.formatField(row, columnId); - if (typeof valueFormatted === 'undefined') { - return -; - } - return ( - // eslint-disable-next-line react/no-danger - - ); -}; + const valueFormatted = indexPattern.formatField(row, columnId); + if (typeof valueFormatted === 'undefined') { + return -; + } + return ( + // eslint-disable-next-line react/no-danger + + ); + }; diff --git a/src/plugins/discover/public/application/components/source_viewer/source_viewer.test.tsx b/src/plugins/discover/public/application/components/source_viewer/source_viewer.test.tsx index d9e9199e6586..7895c1025dda 100644 --- a/src/plugins/discover/public/application/components/source_viewer/source_viewer.test.tsx +++ b/src/plugins/discover/public/application/components/source_viewer/source_viewer.test.tsx @@ -25,9 +25,9 @@ const mockIndexPattern = { getComputedFields: () => [], } as never; const getMock = jest.fn(() => Promise.resolve(mockIndexPattern)); -const mockIndexPatternService = ({ +const mockIndexPatternService = { get: getMock, -} as unknown) as IndexPattern; +} as unknown as IndexPattern; (getServices as jest.Mock).mockImplementation(() => ({ uiSettings: { 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 589c97b400eb..3f010d9d0773 100644 --- a/src/plugins/discover/public/application/components/table/table.test.tsx +++ b/src/plugins/discover/public/application/components/table/table.test.tsx @@ -29,7 +29,7 @@ import { getServices } from '../../../kibana_services'; }, })); -const indexPattern = ({ +const indexPattern = { fields: { getAll: () => [ { @@ -67,7 +67,7 @@ const indexPattern = ({ metaFields: ['_index', '_score'], flattenHit: undefined, formatHit: jest.fn((hit) => hit._source), -} as unknown) as IndexPattern; +} as unknown as IndexPattern; indexPattern.fields.getByName = (name: string) => { return indexPattern.fields.getAll().find((field) => field.name === name); @@ -167,12 +167,14 @@ describe('DocViewTable at Discover', () => { expect(rowComponent.length).toBe(1); }); - ([ - 'addInclusiveFilterButton', - 'collapseBtn', - 'toggleColumnButton', - 'underscoreWarning', - ] as const).forEach((element) => { + ( + [ + 'addInclusiveFilterButton', + 'collapseBtn', + 'toggleColumnButton', + 'underscoreWarning', + ] as const + ).forEach((element) => { const elementExist = check[element]; if (typeof elementExist === 'boolean') { @@ -266,7 +268,7 @@ describe('DocViewTable at Discover Doc', () => { }); describe('DocViewTable at Discover Doc with Fields API', () => { - const indexPatterneCommerce = ({ + const indexPatterneCommerce = { fields: { getAll: () => [ { @@ -385,7 +387,7 @@ describe('DocViewTable at Discover Doc with Fields API', () => { }); return result; }), - } as unknown) as IndexPattern; + } as unknown as IndexPattern; indexPatterneCommerce.fields.getByName = (name: string) => { return indexPatterneCommerce.fields.getAll().find((field) => field.name === name); diff --git a/src/plugins/discover/public/application/components/table/table.tsx b/src/plugins/discover/public/application/components/table/table.tsx index e89b27e8069f..eab3ba6e3d29 100644 --- a/src/plugins/discover/public/application/components/table/table.tsx +++ b/src/plugins/discover/public/application/components/table/table.tsx @@ -58,9 +58,10 @@ export const DocViewerTable = ({ }: DocViewRenderProps) => { const showMultiFields = getServices().uiSettings.get(SHOW_MULTIFIELDS); - const mapping = useCallback((name: string) => indexPattern?.fields.getByName(name), [ - indexPattern?.fields, - ]); + const mapping = useCallback( + (name: string) => indexPattern?.fields.getByName(name), + [indexPattern?.fields] + ); const formattedHit = useMemo(() => indexPattern?.formatHit(hit, 'html'), [hit, indexPattern]); diff --git a/src/plugins/discover/public/application/embeddable/saved_search_embeddable.tsx b/src/plugins/discover/public/application/embeddable/saved_search_embeddable.tsx index e060a0fbae87..500bad34e275 100644 --- a/src/plugins/discover/public/application/embeddable/saved_search_embeddable.tsx +++ b/src/plugins/discover/public/application/embeddable/saved_search_embeddable.tsx @@ -71,7 +71,8 @@ interface SearchEmbeddableConfig { export class SavedSearchEmbeddable extends Embeddable - implements ISearchEmbeddable { + implements ISearchEmbeddable +{ private readonly savedSearch: SavedSearch; private inspectorAdapters: Adapters; private panelTitle: string = ''; diff --git a/src/plugins/discover/public/application/embeddable/search_embeddable_factory.ts b/src/plugins/discover/public/application/embeddable/search_embeddable_factory.ts index b314d9ab55cd..95f5b2d3ce28 100644 --- a/src/plugins/discover/public/application/embeddable/search_embeddable_factory.ts +++ b/src/plugins/discover/public/application/embeddable/search_embeddable_factory.ts @@ -27,7 +27,8 @@ interface StartServices { } export class SearchEmbeddableFactory - implements EmbeddableFactoryDefinition { + implements EmbeddableFactoryDefinition +{ public readonly type = SEARCH_EMBEDDABLE_TYPE; public readonly savedObjectMetaData = { name: i18n.translate('discover.savedSearch.savedObjectName', { diff --git a/src/plugins/discover/public/application/helpers/get_context_url.test.ts b/src/plugins/discover/public/application/helpers/get_context_url.test.ts index 4856c9884566..97d31ca43142 100644 --- a/src/plugins/discover/public/application/helpers/get_context_url.test.ts +++ b/src/plugins/discover/public/application/helpers/get_context_url.test.ts @@ -8,10 +8,10 @@ import { getContextUrl } from './get_context_url'; import { FilterManager } from '../../../../data/public/query/filter_manager'; -const filterManager = ({ +const filterManager = { getGlobalFilters: () => [], getAppFilters: () => [], -} as unknown) as FilterManager; +} as unknown as FilterManager; const addBasePath = (path: string) => `/base${path}`; describe('Get context url', () => { diff --git a/src/plugins/discover/public/application/helpers/popularize_field.test.ts b/src/plugins/discover/public/application/helpers/popularize_field.test.ts index 7ae3994abd21..91673fd17d3b 100644 --- a/src/plugins/discover/public/application/helpers/popularize_field.test.ts +++ b/src/plugins/discover/public/application/helpers/popularize_field.test.ts @@ -10,17 +10,17 @@ import { Capabilities } from 'kibana/public'; import { IndexPattern, IndexPatternsService } from '../../../../data/public'; import { popularizeField } from './popularize_field'; -const capabilities = ({ +const capabilities = { indexPatterns: { save: true, }, -} as unknown) as Capabilities; +} as unknown as Capabilities; describe('Popularize field', () => { test('returns undefined if index pattern lacks id', async () => { - const indexPattern = ({} as unknown) as IndexPattern; + const indexPattern = {} as unknown as IndexPattern; const fieldName = '@timestamp'; - const indexPatternsService = ({} as unknown) as IndexPatternsService; + const indexPatternsService = {} as unknown as IndexPatternsService; const result = await popularizeField( indexPattern, fieldName, @@ -31,13 +31,13 @@ describe('Popularize field', () => { }); test('returns undefined if field not found', async () => { - const indexPattern = ({ + const indexPattern = { fields: { getByName: () => {}, }, - } as unknown) as IndexPattern; + } as unknown as IndexPattern; const fieldName = '@timestamp'; - const indexPatternsService = ({} as unknown) as IndexPatternsService; + const indexPatternsService = {} as unknown as IndexPatternsService; const result = await popularizeField( indexPattern, fieldName, @@ -51,16 +51,16 @@ describe('Popularize field', () => { const field = { count: 0, }; - const indexPattern = ({ + const indexPattern = { id: 'id', fields: { getByName: () => field, }, - } as unknown) as IndexPattern; + } as unknown as IndexPattern; const fieldName = '@timestamp'; - const indexPatternsService = ({ + const indexPatternsService = { updateSavedObject: async () => {}, - } as unknown) as IndexPatternsService; + } as unknown as IndexPatternsService; const result = await popularizeField( indexPattern, fieldName, @@ -75,18 +75,18 @@ describe('Popularize field', () => { const field = { count: 0, }; - const indexPattern = ({ + const indexPattern = { id: 'id', fields: { getByName: () => field, }, - } as unknown) as IndexPattern; + } as unknown as IndexPattern; const fieldName = '@timestamp'; - const indexPatternsService = ({ + const indexPatternsService = { updateSavedObject: async () => { throw new Error('unknown error'); }, - } as unknown) as IndexPatternsService; + } as unknown as IndexPatternsService; const result = await popularizeField( indexPattern, fieldName, @@ -100,19 +100,19 @@ describe('Popularize field', () => { const field = { count: 0, }; - const indexPattern = ({ + const indexPattern = { id: 'id', fields: { getByName: () => field, }, - } as unknown) as IndexPattern; + } as unknown as IndexPattern; const fieldName = '@timestamp'; - const indexPatternsService = ({ + const indexPatternsService = { updateSavedObject: jest.fn(), - } as unknown) as IndexPatternsService; - const result = await popularizeField(indexPattern, fieldName, indexPatternsService, ({ + } as unknown as IndexPatternsService; + const result = await popularizeField(indexPattern, fieldName, indexPatternsService, { indexPatterns: { save: false }, - } as unknown) as Capabilities); + } as unknown as Capabilities); expect(result).toBeUndefined(); expect(indexPatternsService.updateSavedObject).not.toHaveBeenCalled(); expect(field.count).toEqual(0); diff --git a/src/plugins/discover/public/application/helpers/use_data_grid_columns.test.tsx b/src/plugins/discover/public/application/helpers/use_data_grid_columns.test.tsx index 565e9a04e7af..ccee271b73e3 100644 --- a/src/plugins/discover/public/application/helpers/use_data_grid_columns.test.tsx +++ b/src/plugins/discover/public/application/helpers/use_data_grid_columns.test.tsx @@ -16,7 +16,7 @@ import { Capabilities } from '../../../../../core/types'; describe('useDataGridColumns', () => { const defaultProps = { - capabilities: ({ discover: { save: true } } as unknown) as Capabilities, + capabilities: { discover: { save: true } } as unknown as Capabilities, config: configMock, indexPattern: indexPatternMock, indexPatterns: indexPatternsMock, diff --git a/src/plugins/discover/public/application/services/use_es_doc_search.test.tsx b/src/plugins/discover/public/application/services/use_es_doc_search.test.tsx index 3fcb193c5f6f..af7d189e6288 100644 --- a/src/plugins/discover/public/application/services/use_es_doc_search.test.tsx +++ b/src/plugins/discover/public/application/services/use_es_doc_search.test.tsx @@ -37,9 +37,9 @@ jest.mock('../../kibana_services', () => ({ describe('Test of helper / hook', () => { test('buildSearchBody given useNewFieldsApi is false', () => { - const indexPattern = ({ + const indexPattern = { getComputedFields: () => ({ storedFields: [], scriptFields: [], docvalueFields: [] }), - } as unknown) as IndexPattern; + } as unknown as IndexPattern; const actual = buildSearchBody('1', indexPattern, false); expect(actual).toMatchInlineSnapshot(` Object { @@ -62,9 +62,9 @@ describe('Test of helper / hook', () => { }); test('buildSearchBody useNewFieldsApi is true', () => { - const indexPattern = ({ + const indexPattern = { getComputedFields: () => ({ storedFields: [], scriptFields: [], docvalueFields: [] }), - } as unknown) as IndexPattern; + } as unknown as IndexPattern; const actual = buildSearchBody('1', indexPattern, true); expect(actual).toMatchInlineSnapshot(` Object { @@ -92,9 +92,9 @@ describe('Test of helper / hook', () => { }); test('buildSearchBody with requestSource', () => { - const indexPattern = ({ + const indexPattern = { getComputedFields: () => ({ storedFields: [], scriptFields: [], docvalueFields: [] }), - } as unknown) as IndexPattern; + } as unknown as IndexPattern; const actual = buildSearchBody('1', indexPattern, true, true); expect(actual).toMatchInlineSnapshot(` Object { @@ -123,7 +123,7 @@ describe('Test of helper / hook', () => { }); test('buildSearchBody with runtime fields', () => { - const indexPattern = ({ + const indexPattern = { getComputedFields: () => ({ storedFields: [], scriptFields: [], @@ -137,7 +137,7 @@ describe('Test of helper / hook', () => { }, }, }), - } as unknown) as IndexPattern; + } as unknown as IndexPattern; const actual = buildSearchBody('1', indexPattern, true); expect(actual).toMatchInlineSnapshot(` Object { @@ -176,15 +176,15 @@ describe('Test of helper / hook', () => { getComputedFields: () => [], }; const getMock = jest.fn(() => Promise.resolve(indexPattern)); - const indexPatternService = ({ + const indexPatternService = { get: getMock, - } as unknown) as IndexPattern; - const props = ({ + } as unknown as IndexPattern; + const props = { id: '1', index: 'index1', indexPatternId: 'xyz', indexPatternService, - } as unknown) as DocProps; + } as unknown as DocProps; // eslint-disable-next-line @typescript-eslint/no-explicit-any let hook: any; await act(async () => { diff --git a/src/plugins/discover/public/kibana_services.ts b/src/plugins/discover/public/kibana_services.ts index 72925a1578c3..c68d6fbf479a 100644 --- a/src/plugins/discover/public/kibana_services.ts +++ b/src/plugins/discover/public/kibana_services.ts @@ -31,18 +31,16 @@ export function setServices(newServices: DiscoverServices) { export const setUiActions = (pluginUiActions: UiActionsStart) => (uiActions = pluginUiActions); export const getUiActions = () => uiActions; -export const [getHeaderActionMenuMounter, setHeaderActionMenuMounter] = createGetterSetter< - AppMountParameters['setHeaderActionMenu'] ->('headerActionMenuMounter'); +export const [getHeaderActionMenuMounter, setHeaderActionMenuMounter] = + createGetterSetter('headerActionMenuMounter'); export const [getUrlTracker, setUrlTracker] = createGetterSetter<{ setTrackedUrl: (url: string) => void; restorePreviousUrl: () => void; }>('urlTracker'); -export const [getDocViewsRegistry, setDocViewsRegistry] = createGetterSetter( - 'DocViewsRegistry' -); +export const [getDocViewsRegistry, setDocViewsRegistry] = + createGetterSetter('DocViewsRegistry'); /** * Makes sure discover and context are using one instance of history. @@ -68,6 +66,5 @@ export const syncHistoryLocations = () => { return h; }; -export const [getScopedHistory, setScopedHistory] = createGetterSetter( - 'scopedHistory' -); +export const [getScopedHistory, setScopedHistory] = + createGetterSetter('scopedHistory'); diff --git a/src/plugins/discover/public/mocks.ts b/src/plugins/discover/public/mocks.ts index 034b5b653747..71de630132b0 100644 --- a/src/plugins/discover/public/mocks.ts +++ b/src/plugins/discover/public/mocks.ts @@ -25,9 +25,9 @@ const createSetupContract = (): Setup => { const createStartContract = (): Start => { const startContract: Start = { savedSearchLoader: {} as DiscoverStart['savedSearchLoader'], - urlGenerator: ({ + urlGenerator: { createUrl: jest.fn(), - } as unknown) as DiscoverStart['urlGenerator'], + } as unknown as DiscoverStart['urlGenerator'], locator: sharePluginMock.createLocator(), }; return startContract; diff --git a/src/plugins/discover/public/plugin.tsx b/src/plugins/discover/public/plugin.tsx index 4624fa79ca14..0327b25fd864 100644 --- a/src/plugins/discover/public/plugin.tsx +++ b/src/plugins/discover/public/plugin.tsx @@ -195,7 +195,8 @@ export interface DiscoverStartPlugins { * Discover provides embeddables for Dashboards */ export class DiscoverPlugin - implements Plugin { + implements Plugin +{ constructor(private readonly initializerContext: PluginInitializerContext) {} private appStateUpdater = new BehaviorSubject(() => ({})); diff --git a/src/plugins/discover/public/saved_searches/_saved_search.ts b/src/plugins/discover/public/saved_searches/_saved_search.ts index 320332ca4ace..56533ed20b31 100644 --- a/src/plugins/discover/public/saved_searches/_saved_search.ts +++ b/src/plugins/discover/public/saved_searches/_saved_search.ts @@ -58,5 +58,5 @@ export function createSavedSearchClass(savedObjects: SavedObjectsStart) { } } - return (SavedSearch as unknown) as new (id: string) => SavedObject; + return SavedSearch as unknown as new (id: string) => SavedObject; } diff --git a/src/plugins/discover/public/url_generator.ts b/src/plugins/discover/public/url_generator.ts index 63dea20fecc0..7cc729fd7f7e 100644 --- a/src/plugins/discover/public/url_generator.ts +++ b/src/plugins/discover/public/url_generator.ts @@ -85,7 +85,8 @@ interface Params { export const SEARCH_SESSION_ID_QUERY_PARAM = 'searchSessionId'; export class DiscoverUrlGenerator - implements UrlGeneratorsDefinition { + implements UrlGeneratorsDefinition +{ constructor(private readonly params: Params) {} public readonly id = DISCOVER_APP_URL_GENERATOR; diff --git a/src/plugins/discover/server/saved_objects/search_migrations.test.ts b/src/plugins/discover/server/saved_objects/search_migrations.test.ts index fb608c0b6f3e..122371642fab 100644 --- a/src/plugins/discover/server/saved_objects/search_migrations.test.ts +++ b/src/plugins/discover/server/saved_objects/search_migrations.test.ts @@ -9,7 +9,7 @@ import { SavedObjectMigrationContext } from 'kibana/server'; import { searchMigrations } from './search_migrations'; -const savedObjectMigrationContext = (null as unknown) as SavedObjectMigrationContext; +const savedObjectMigrationContext = null as unknown as SavedObjectMigrationContext; const testMigrateMatchAllQuery = (migrationFn: Function) => { it('should migrate obsolete match_all query', () => { diff --git a/src/plugins/embeddable/common/mocks.ts b/src/plugins/embeddable/common/mocks.ts index 36d564d26b75..353cb3fcf08e 100644 --- a/src/plugins/embeddable/common/mocks.ts +++ b/src/plugins/embeddable/common/mocks.ts @@ -8,11 +8,12 @@ import { EmbeddablePersistableStateService } from './types'; -export const createEmbeddablePersistableStateServiceMock = (): jest.Mocked => { - return { - inject: jest.fn((state, references) => state), - extract: jest.fn((state) => ({ state, references: [] })), - getAllMigrations: jest.fn(() => ({})), - telemetry: jest.fn((state, collector) => ({})), +export const createEmbeddablePersistableStateServiceMock = + (): jest.Mocked => { + return { + inject: jest.fn((state, references) => state), + extract: jest.fn((state) => ({ state, references: [] })), + getAllMigrations: jest.fn(() => ({})), + telemetry: jest.fn((state, collector) => ({})), + }; }; -}; diff --git a/src/plugins/embeddable/public/lib/actions/edit_panel_action.test.tsx b/src/plugins/embeddable/public/lib/actions/edit_panel_action.test.tsx index eb6b585bfbcf..173190728846 100644 --- a/src/plugins/embeddable/public/lib/actions/edit_panel_action.test.tsx +++ b/src/plugins/embeddable/public/lib/actions/edit_panel_action.test.tsx @@ -46,12 +46,12 @@ test('redirects to app using state transfer with by value mode', async () => { applicationMock.currentAppId$ = of('superCoolCurrentApp'); const action = new EditPanelAction(getFactory, applicationMock, stateTransferMock); const embeddable = new EditableEmbeddable( - ({ + { id: '123', viewMode: ViewMode.EDIT, coolInput1: 1, coolInput2: 2, - } as unknown) as EmbeddableInput, + } as unknown as EmbeddableInput, true ); embeddable.getOutput = jest.fn(() => ({ editApp: 'ultraVisualize', editPath: '/123' })); diff --git a/src/plugins/embeddable/public/lib/containers/container.ts b/src/plugins/embeddable/public/lib/containers/container.ts index 5d51b0e17293..8b3780b26925 100644 --- a/src/plugins/embeddable/public/lib/containers/container.ts +++ b/src/plugins/embeddable/public/lib/containers/container.ts @@ -30,7 +30,8 @@ export abstract class Container< TContainerOutput extends ContainerOutput = ContainerOutput > extends Embeddable - implements IContainer { + implements IContainer +{ public readonly isContainer: boolean = true; public readonly children: { [key: string]: IEmbeddable | ErrorEmbeddable; @@ -150,13 +151,13 @@ export abstract class Container< explicitFiltered[key] = explicitInput[key]; }); - return ({ + return { ...containerInput, ...explicitFiltered, // Typescript has difficulties with inferring this type but it is accurate with all // tests I tried. Could probably be revisted with future releases of TS to see if // it can accurately infer the type. - } as unknown) as TEmbeddableInput; + } as unknown as TEmbeddableInput; } public destroy() { diff --git a/src/plugins/embeddable/public/lib/embeddables/embeddable.test.tsx b/src/plugins/embeddable/public/lib/embeddables/embeddable.test.tsx index 15e0e72eec2a..de0bcf3f8654 100644 --- a/src/plugins/embeddable/public/lib/embeddables/embeddable.test.tsx +++ b/src/plugins/embeddable/public/lib/embeddables/embeddable.test.tsx @@ -74,7 +74,7 @@ test('Embeddable reload is called if lastReloadRequest input time changes', asyn test('Embeddable reload is called if lastReloadRequest input time changed and new input is used', async () => { const hello = new FilterableEmbeddable({ id: '123', filters: [], lastReloadRequestTime: 0 }); - const aFilter = ({} as unknown) as MockFilter; + const aFilter = {} as unknown as MockFilter; hello.reload = jest.fn(() => { // when reload is called embeddable already has new input expect(hello.getInput().filters).toEqual([aFilter]); diff --git a/src/plugins/embeddable/public/lib/embeddables/embeddable.tsx b/src/plugins/embeddable/public/lib/embeddables/embeddable.tsx index 9dc82968541d..2e6a31e473e3 100644 --- a/src/plugins/embeddable/public/lib/embeddables/embeddable.tsx +++ b/src/plugins/embeddable/public/lib/embeddables/embeddable.tsx @@ -23,7 +23,8 @@ function getPanelTitle(input: EmbeddableInput, output: EmbeddableOutput) { export abstract class Embeddable< TEmbeddableInput extends EmbeddableInput = EmbeddableInput, TEmbeddableOutput extends EmbeddableOutput = EmbeddableOutput -> implements IEmbeddable { +> implements IEmbeddable +{ static runtimeId: number = 0; public readonly runtimeId = Embeddable.runtimeId++; diff --git a/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx b/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx index b66950c170d6..cce286bfe73b 100644 --- a/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx +++ b/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx @@ -48,8 +48,10 @@ const sortByOrderField = ( { order: orderB }: { order?: number } ) => (orderB || 0) - (orderA || 0); -const removeById = (disabledActions: string[]) => ({ id }: { id: string }) => - disabledActions.indexOf(id) === -1; +const removeById = + (disabledActions: string[]) => + ({ id }: { id: string }) => + disabledActions.indexOf(id) === -1; interface Props { embeddable: IEmbeddable; 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 72791d92591a..6b33d6b44b93 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 @@ -20,7 +20,8 @@ import { ContactCardInitializer } from './contact_card_initializer'; export const CONTACT_CARD_EMBEDDABLE = 'CONTACT_CARD_EMBEDDABLE'; export class ContactCardEmbeddableFactory - implements EmbeddableFactoryDefinition { + implements EmbeddableFactoryDefinition +{ public readonly type = CONTACT_CARD_EMBEDDABLE; constructor( diff --git a/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_exportable_embeddable_factory.tsx b/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_exportable_embeddable_factory.tsx index f25623210fd8..7b58d5c8b498 100644 --- a/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_exportable_embeddable_factory.tsx +++ b/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_exportable_embeddable_factory.tsx @@ -21,7 +21,8 @@ import { ContactCardInitializer } from './contact_card_initializer'; export const CONTACT_CARD_EXPORTABLE_EMBEDDABLE = 'CONTACT_CARD_EXPORTABLE_EMBEDDABLE'; export class ContactCardExportableEmbeddableFactory - implements EmbeddableFactoryDefinition { + implements EmbeddableFactoryDefinition +{ public readonly type = CONTACT_CARD_EXPORTABLE_EMBEDDABLE; constructor( diff --git a/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/slow_contact_card_embeddable_factory.ts b/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/slow_contact_card_embeddable_factory.ts index ddb810650996..7e9e01214e8c 100644 --- a/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/slow_contact_card_embeddable_factory.ts +++ b/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/slow_contact_card_embeddable_factory.ts @@ -17,7 +17,8 @@ interface SlowContactCardEmbeddableFactoryOptions { } export class SlowContactCardEmbeddableFactory - implements EmbeddableFactoryDefinition { + implements EmbeddableFactoryDefinition +{ private loadTickCount = 0; public readonly type = CONTACT_CARD_EMBEDDABLE; diff --git a/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_container_factory.ts b/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_container_factory.ts index 92bf3d81c705..3d37ce488282 100644 --- a/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_container_factory.ts +++ b/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_container_factory.ts @@ -16,7 +16,8 @@ import { import { EmbeddableStart } from '../../../plugin'; export class FilterableContainerFactory - implements EmbeddableFactoryDefinition { + implements EmbeddableFactoryDefinition +{ public readonly type = FILTERABLE_CONTAINER; constructor( diff --git a/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_embeddable_factory.ts b/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_embeddable_factory.ts index 3671ed6ca5c6..acaad2c1e9a8 100644 --- a/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_embeddable_factory.ts +++ b/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_embeddable_factory.ts @@ -16,7 +16,8 @@ import { EmbeddableFactoryDefinition } from '../../embeddables'; import { IContainer } from '../../containers'; export class FilterableEmbeddableFactory - implements EmbeddableFactoryDefinition { + implements EmbeddableFactoryDefinition +{ public readonly type = FILTERABLE_EMBEDDABLE; public async isEditable() { diff --git a/src/plugins/embeddable/public/mocks.tsx b/src/plugins/embeddable/public/mocks.tsx index ff2771f3fd58..94eb5e5cc6a0 100644 --- a/src/plugins/embeddable/public/mocks.tsx +++ b/src/plugins/embeddable/public/mocks.tsx @@ -89,7 +89,8 @@ export const mockRefOrValEmbeddable = < mockedByValueInput: ValTypeInput; } ): OriginalEmbeddableType & ReferenceOrValueEmbeddable => { - const newEmbeddable: ReferenceOrValueEmbeddable = (embeddable as unknown) as ReferenceOrValueEmbeddable; + const newEmbeddable: ReferenceOrValueEmbeddable = + embeddable as unknown as ReferenceOrValueEmbeddable; newEmbeddable.inputIsRefType = (input: unknown): input is RefTypeInput => !!(input as RefTypeInput).savedObjectId; newEmbeddable.getInputAsRefType = () => Promise.resolve(options.mockedByReferenceInput); diff --git a/src/plugins/embeddable/public/plugin.tsx b/src/plugins/embeddable/public/plugin.tsx index c644e1f3fdc2..994cdb709ccc 100644 --- a/src/plugins/embeddable/public/plugin.tsx +++ b/src/plugins/embeddable/public/plugin.tsx @@ -100,10 +100,8 @@ export interface EmbeddableStart extends PersistableStateService; export class EmbeddablePublicPlugin implements Plugin { - private readonly embeddableFactoryDefinitions: Map< - string, - EmbeddableFactoryDefinition - > = new Map(); + private readonly embeddableFactoryDefinitions: Map = + new Map(); private readonly embeddableFactories: EmbeddableFactoryRegistry = new Map(); private readonly enhancements: EnhancementsRegistry = new Map(); private customEmbeddableFactoryProvider?: EmbeddableFactoryProvider; @@ -155,27 +153,24 @@ export class EmbeddablePublicPlugin implements Plugin ({ - embeddable, - hideHeader, - }: { - embeddable: IEmbeddable; - hideHeader?: boolean; - }) => ( - - ); + const getEmbeddablePanelHoc = + () => + ({ embeddable, hideHeader }: { embeddable: IEmbeddable; hideHeader?: boolean }) => + ( + + ); const commonContract = { getEmbeddableFactory: this.getEmbeddableFactory, diff --git a/src/plugins/embeddable/public/tests/container.test.ts b/src/plugins/embeddable/public/tests/container.test.ts index 78b3a8437d2b..5f23add51bce 100644 --- a/src/plugins/embeddable/public/tests/container.test.ts +++ b/src/plugins/embeddable/public/tests/container.test.ts @@ -286,19 +286,14 @@ test('Container view mode change propagates to children', async () => { }); test(`Container updates its state when a child's input is updated`, async (done) => { - const { - container, - embeddable, - start, - coreStart, - uiActions, - } = await creatHelloWorldContainerAndEmbeddable( - { id: 'hello', panels: {}, viewMode: ViewMode.VIEW }, - { - id: '123', - firstName: 'Susy', - } - ); + const { container, embeddable, start, coreStart, uiActions } = + await creatHelloWorldContainerAndEmbeddable( + { id: 'hello', panels: {}, viewMode: ViewMode.VIEW }, + { + id: '123', + firstName: 'Susy', + } + ); expect(isErrorEmbeddable(embeddable)).toBe(false); diff --git a/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/authorization_provider.tsx b/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/authorization_provider.tsx index f29ab120013c..be49a7697afc 100644 --- a/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/authorization_provider.tsx +++ b/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/authorization_provider.tsx @@ -45,7 +45,11 @@ interface Props { } export const AuthorizationProvider = ({ privilegesEndpoint, httpClient, children }: Props) => { - const { isLoading, error, data: privilegesData } = useRequest(httpClient, { + const { + isLoading, + error, + data: privilegesData, + } = useRequest(httpClient, { path: privilegesEndpoint, method: 'get', }); diff --git a/src/plugins/es_ui_shared/public/components/json_editor/json_editor.tsx b/src/plugins/es_ui_shared/public/components/json_editor/json_editor.tsx index 9eb7695bbae0..8e662a97b279 100644 --- a/src/plugins/es_ui_shared/public/components/json_editor/json_editor.tsx +++ b/src/plugins/es_ui_shared/public/components/json_editor/json_editor.tsx @@ -32,7 +32,12 @@ function JsonEditorComp({ euiCodeEditorProps, error: propsError, }: Props) { - const { content, setContent, error: internalError, isControlled } = useJson({ + const { + content, + setContent, + error: internalError, + isControlled, + } = useJson({ defaultValue, onUpdate, value, diff --git a/src/plugins/es_ui_shared/public/forms/multi_content/multi_content_context.tsx b/src/plugins/es_ui_shared/public/forms/multi_content/multi_content_context.tsx index 7223751fbe3f..cda10c961c2c 100644 --- a/src/plugins/es_ui_shared/public/forms/multi_content/multi_content_context.tsx +++ b/src/plugins/es_ui_shared/public/forms/multi_content/multi_content_context.tsx @@ -46,12 +46,8 @@ export function useMultiContentContext(contentId: K) { const isMounted = useRef(false); const defaultValue = useRef(undefined); - const { - updateContentAt, - saveSnapshotAndRemoveContent, - getData, - getSingleContentData, - } = useMultiContentContext(); + const { updateContentAt, saveSnapshotAndRemoveContent, getData, getSingleContentData } = + useMultiContentContext(); const updateContent = useCallback( (content: Content) => { diff --git a/src/plugins/es_ui_shared/public/request/use_request.test.ts b/src/plugins/es_ui_shared/public/request/use_request.test.ts index 4e56604ab1a2..68edde133672 100644 --- a/src/plugins/es_ui_shared/public/request/use_request.test.ts +++ b/src/plugins/es_ui_shared/public/request/use_request.test.ts @@ -118,12 +118,8 @@ describe('useRequest hook', () => { }); it('surfaces body-shaped errors from requests', async () => { - const { - setupErrorWithBodyRequest, - completeRequest, - hookResult, - getErrorWithBodyResponse, - } = helpers; + const { setupErrorWithBodyRequest, completeRequest, hookResult, getErrorWithBodyResponse } = + helpers; setupErrorWithBodyRequest(); await completeRequest(); diff --git a/src/plugins/es_ui_shared/static/forms/components/fields/range_field.tsx b/src/plugins/es_ui_shared/static/forms/components/fields/range_field.tsx index 36bbd0a82ce0..c063e46a247b 100644 --- a/src/plugins/es_ui_shared/static/forms/components/fields/range_field.tsx +++ b/src/plugins/es_ui_shared/static/forms/components/fields/range_field.tsx @@ -24,7 +24,7 @@ export const RangeField = ({ field, euiFieldProps = {}, idAria, ...rest }: Props const onChange = useCallback( (e: React.ChangeEvent | React.MouseEvent) => { - const event = ({ ...e, value: `${e.currentTarget.value}` } as unknown) as React.ChangeEvent<{ + const event = { ...e, value: `${e.currentTarget.value}` } as unknown as React.ChangeEvent<{ value: string; }>; onFieldChange(event); diff --git a/src/plugins/es_ui_shared/static/forms/components/fields/toggle_field.tsx b/src/plugins/es_ui_shared/static/forms/components/fields/toggle_field.tsx index db8ffb97f751..c7e0cb65767d 100644 --- a/src/plugins/es_ui_shared/static/forms/components/fields/toggle_field.tsx +++ b/src/plugins/es_ui_shared/static/forms/components/fields/toggle_field.tsx @@ -23,7 +23,7 @@ export const ToggleField = ({ field, euiFieldProps = {}, idAria, ...rest }: Prop // Shim for sufficient overlap between EuiSwitchEvent and FieldHook[onChange] event const onChange = (e: EuiSwitchEvent) => { - const event = ({ ...e, value: `${e.target.checked}` } as unknown) as React.ChangeEvent<{ + const event = { ...e, value: `${e.target.checked}` } as unknown as React.ChangeEvent<{ value: string; }>; field.onChange(event); diff --git a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/contains_char.ts b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/contains_char.ts index 0c883e1f5e73..8aa55b789f46 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/contains_char.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/contains_char.ts @@ -10,25 +10,27 @@ import { ValidationFunc, ValidationError } from '../../hook_form_lib'; import { containsChars } from '../../../validators/string'; import { ERROR_CODE } from './types'; -export const containsCharsField = ({ - message, - chars, -}: { - message: string | ((err: Partial) => string); - chars: string | string[]; -}) => (...args: Parameters): ReturnType> => { - const [{ value }] = args; +export const containsCharsField = + ({ + message, + chars, + }: { + message: string | ((err: Partial) => string); + chars: string | string[]; + }) => + (...args: Parameters): ReturnType> => { + const [{ value }] = args; - if (typeof value !== 'string') { - return; - } + if (typeof value !== 'string') { + return; + } - const { doesContain, charsFound } = containsChars(chars)(value as string); - if (doesContain) { - return { - code: 'ERR_INVALID_CHARS', - charsFound, - message: typeof message === 'function' ? message({ charsFound }) : message, - }; - } -}; + const { doesContain, charsFound } = containsChars(chars)(value as string); + if (doesContain) { + return { + code: 'ERR_INVALID_CHARS', + charsFound, + message: typeof message === 'function' ? message({ charsFound }) : message, + }; + } + }; diff --git a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/empty_field.ts b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/empty_field.ts index 42a71197fe4f..3b0dd49b8096 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/empty_field.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/empty_field.ts @@ -11,16 +11,16 @@ import { isEmptyString } from '../../../validators/string'; import { isEmptyArray } from '../../../validators/array'; import { ERROR_CODE } from './types'; -export const emptyField = (message: string) => ( - ...args: Parameters -): ReturnType> => { - const [{ value, path }] = args; +export const emptyField = + (message: string) => + (...args: Parameters): ReturnType> => { + const [{ value, path }] = args; - if (typeof value === 'string') { - return isEmptyString(value) ? { code: 'ERR_FIELD_MISSING', path, message } : undefined; - } + if (typeof value === 'string') { + return isEmptyString(value) ? { code: 'ERR_FIELD_MISSING', path, message } : undefined; + } - if (Array.isArray(value)) { - return isEmptyArray(value) ? { code: 'ERR_FIELD_MISSING', path, message } : undefined; - } -}; + if (Array.isArray(value)) { + return isEmptyArray(value) ? { code: 'ERR_FIELD_MISSING', path, message } : undefined; + } + }; diff --git a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/index_name.ts b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/index_name.ts index 3dbfd7c6c289..7c0d29217334 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/index_name.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/index_name.ts @@ -11,45 +11,45 @@ import { ValidationFunc } from '../../hook_form_lib'; import { startsWith, containsChars } from '../../../validators/string'; import { ERROR_CODE } from './types'; -export const indexNameField = (i18n: any) => ( - ...args: Parameters -): ReturnType> => { - const [{ value }] = args; +export const indexNameField = + (i18n: any) => + (...args: Parameters): ReturnType> => { + const [{ value }] = args; - if (startsWith('.')(value as string)) { - return { - code: 'ERR_FIELD_FORMAT', - formatType: 'INDEX_NAME', - message: i18n.translate('esUi.forms.fieldValidation.indexNameStartsWithDotError', { - defaultMessage: 'The index name cannot start with a dot (.).', - }), - }; - } + if (startsWith('.')(value as string)) { + return { + code: 'ERR_FIELD_FORMAT', + formatType: 'INDEX_NAME', + message: i18n.translate('esUi.forms.fieldValidation.indexNameStartsWithDotError', { + defaultMessage: 'The index name cannot start with a dot (.).', + }), + }; + } - const { doesContain: doesContainSpaces } = containsChars(' ')(value as string); - if (doesContainSpaces) { - return { - code: 'ERR_FIELD_FORMAT', - formatType: 'INDEX_NAME', - message: i18n.translate('esUi.forms.fieldValidation.indexNameSpacesError', { - defaultMessage: 'The index name cannot contain spaces.', - }), - }; - } + const { doesContain: doesContainSpaces } = containsChars(' ')(value as string); + if (doesContainSpaces) { + return { + code: 'ERR_FIELD_FORMAT', + formatType: 'INDEX_NAME', + message: i18n.translate('esUi.forms.fieldValidation.indexNameSpacesError', { + defaultMessage: 'The index name cannot contain spaces.', + }), + }; + } - const { charsFound, doesContain } = containsChars(indices.INDEX_ILLEGAL_CHARACTERS_VISIBLE)( - value as string - ); - if (doesContain) { - return { - message: i18n.translate('esUi.forms.fieldValidation.indexNameInvalidCharactersError', { - defaultMessage: - 'The index name contains the invalid {characterListLength, plural, one {character} other {characters}} { characterList }.', - values: { - characterList: charsFound.join(' '), - characterListLength: charsFound.length, - }, - }), - }; - } -}; + const { charsFound, doesContain } = containsChars(indices.INDEX_ILLEGAL_CHARACTERS_VISIBLE)( + value as string + ); + if (doesContain) { + return { + message: i18n.translate('esUi.forms.fieldValidation.indexNameInvalidCharactersError', { + defaultMessage: + 'The index name contains the invalid {characterListLength, plural, one {character} other {characters}} { characterList }.', + values: { + characterList: charsFound.join(' '), + characterListLength: charsFound.length, + }, + }), + }; + } + }; diff --git a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/index_pattern_field.ts b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/index_pattern_field.ts index aabd254b75f7..5aadefa6005f 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/index_pattern_field.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/index_pattern_field.ts @@ -12,43 +12,43 @@ import { ERROR_CODE } from './types'; import { indexPatterns } from '../../../../../data/public'; -export const indexPatternField = (i18n: any) => ( - ...args: Parameters -): ReturnType> => { - const [{ value }] = args; - - if (typeof value !== 'string') { - return; - } - - // Validate it does not contain spaces - const { doesContain } = containsChars(' ')(value); - - if (doesContain) { - return { - code: 'ERR_FIELD_FORMAT', - formatType: 'INDEX_PATTERN', - message: i18n.translate('esUi.forms.fieldValidation.indexPatternSpacesError', { - defaultMessage: 'The index pattern cannot contain spaces.', - }), - }; - } - - // Validate illegal characters - const errors = indexPatterns.validate(value); - - if (errors[indexPatterns.ILLEGAL_CHARACTERS_KEY]) { - return { - code: 'ERR_FIELD_FORMAT', - formatType: 'INDEX_PATTERN', - message: i18n.translate('esUi.forms.fieldValidation.indexPatternInvalidCharactersError', { - defaultMessage: - 'The index pattern contains the invalid {characterListLength, plural, one {character} other {characters}} { characterList }.', - values: { - characterList: errors[indexPatterns.ILLEGAL_CHARACTERS_KEY].join(' '), - characterListLength: errors[indexPatterns.ILLEGAL_CHARACTERS_KEY].length, - }, - }), - }; - } -}; +export const indexPatternField = + (i18n: any) => + (...args: Parameters): ReturnType> => { + const [{ value }] = args; + + if (typeof value !== 'string') { + return; + } + + // Validate it does not contain spaces + const { doesContain } = containsChars(' ')(value); + + if (doesContain) { + return { + code: 'ERR_FIELD_FORMAT', + formatType: 'INDEX_PATTERN', + message: i18n.translate('esUi.forms.fieldValidation.indexPatternSpacesError', { + defaultMessage: 'The index pattern cannot contain spaces.', + }), + }; + } + + // Validate illegal characters + const errors = indexPatterns.validate(value); + + if (errors[indexPatterns.ILLEGAL_CHARACTERS_KEY]) { + return { + code: 'ERR_FIELD_FORMAT', + formatType: 'INDEX_PATTERN', + message: i18n.translate('esUi.forms.fieldValidation.indexPatternInvalidCharactersError', { + defaultMessage: + 'The index pattern contains the invalid {characterListLength, plural, one {character} other {characters}} { characterList }.', + values: { + characterList: errors[indexPatterns.ILLEGAL_CHARACTERS_KEY].join(' '), + characterListLength: errors[indexPatterns.ILLEGAL_CHARACTERS_KEY].length, + }, + }), + }; + } + }; diff --git a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/is_json.ts b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/is_json.ts index cd23a2709dae..62817f0df4cf 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/is_json.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/is_json.ts @@ -10,20 +10,19 @@ import { ValidationFunc } from '../../hook_form_lib'; import { isJSON } from '../../../validators/string'; import { ERROR_CODE } from './types'; -export const isJsonField = ( - message: string, - { allowEmptyString = false }: { allowEmptyString?: boolean } = {} -) => (...args: Parameters): ReturnType> => { - const [{ value }] = args; +export const isJsonField = + (message: string, { allowEmptyString = false }: { allowEmptyString?: boolean } = {}) => + (...args: Parameters): ReturnType> => { + const [{ value }] = args; - if (typeof value !== 'string' || (allowEmptyString && value.trim() === '')) { - return; - } + if (typeof value !== 'string' || (allowEmptyString && value.trim() === '')) { + return; + } - if (!isJSON(value)) { - return { - code: 'ERR_JSON_FORMAT', - message, - }; - } -}; + if (!isJSON(value)) { + return { + code: 'ERR_JSON_FORMAT', + message, + }; + } + }; diff --git a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/lowercase_string.ts b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/lowercase_string.ts index 49b17aeb8c38..3fcc429a49a9 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/lowercase_string.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/lowercase_string.ts @@ -10,19 +10,19 @@ import { ValidationFunc } from '../../hook_form_lib'; import { isLowerCaseString } from '../../../validators/string'; import { ERROR_CODE } from './types'; -export const lowerCaseStringField = (message: string) => ( - ...args: Parameters -): ReturnType> => { - const [{ value }] = args; +export const lowerCaseStringField = + (message: string) => + (...args: Parameters): ReturnType> => { + const [{ value }] = args; - if (typeof value !== 'string') { - return; - } + if (typeof value !== 'string') { + return; + } - if (!isLowerCaseString(value)) { - return { - code: 'ERR_LOWERCASE_STRING', - message, - }; - } -}; + if (!isLowerCaseString(value)) { + return { + code: 'ERR_LOWERCASE_STRING', + message, + }; + } + }; diff --git a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/max_length.ts b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/max_length.ts index 3ba0a272003c..bf92bbe7d7bf 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/max_length.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/max_length.ts @@ -11,32 +11,34 @@ import { hasMaxLengthString } from '../../../validators/string'; import { hasMaxLengthArray } from '../../../validators/array'; import { ERROR_CODE } from './types'; -export const maxLengthField = ({ - length = 0, - message, -}: { - length: number; - message: string | ((err: Partial) => string); -}) => (...args: Parameters): ReturnType> => { - const [{ value }] = args; +export const maxLengthField = + ({ + length = 0, + message, + }: { + length: number; + message: string | ((err: Partial) => string); + }) => + (...args: Parameters): ReturnType> => { + const [{ value }] = args; - // Validate for Arrays - if (Array.isArray(value)) { - return hasMaxLengthArray(length)(value) + // Validate for Arrays + if (Array.isArray(value)) { + return hasMaxLengthArray(length)(value) + ? undefined + : { + code: 'ERR_MAX_LENGTH', + length, + message: typeof message === 'function' ? message({ length }) : message, + }; + } + + // Validate for Strings + return hasMaxLengthString(length)((value as string).trim()) ? undefined : { code: 'ERR_MAX_LENGTH', length, message: typeof message === 'function' ? message({ length }) : message, }; - } - - // Validate for Strings - return hasMaxLengthString(length)((value as string).trim()) - ? undefined - : { - code: 'ERR_MAX_LENGTH', - length, - message: typeof message === 'function' ? message({ length }) : message, - }; -}; + }; diff --git a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/min_length.ts b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/min_length.ts index 7a0aa35da4bd..851aae83521a 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/min_length.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/min_length.ts @@ -11,32 +11,34 @@ import { hasMinLengthString } from '../../../validators/string'; import { hasMinLengthArray } from '../../../validators/array'; import { ERROR_CODE } from './types'; -export const minLengthField = ({ - length = 0, - message, -}: { - length: number; - message: string | ((err: Partial) => string); -}) => (...args: Parameters): ReturnType> => { - const [{ value }] = args; +export const minLengthField = + ({ + length = 0, + message, + }: { + length: number; + message: string | ((err: Partial) => string); + }) => + (...args: Parameters): ReturnType> => { + const [{ value }] = args; - // Validate for Arrays - if (Array.isArray(value)) { - return hasMinLengthArray(length)(value) + // Validate for Arrays + if (Array.isArray(value)) { + return hasMinLengthArray(length)(value) + ? undefined + : { + code: 'ERR_MIN_LENGTH', + length, + message: typeof message === 'function' ? message({ length }) : message, + }; + } + + // Validate for Strings + return hasMinLengthString(length)((value as string).trim()) ? undefined : { code: 'ERR_MIN_LENGTH', length, message: typeof message === 'function' ? message({ length }) : message, }; - } - - // Validate for Strings - return hasMinLengthString(length)((value as string).trim()) - ? undefined - : { - code: 'ERR_MIN_LENGTH', - length, - message: typeof message === 'function' ? message({ length }) : message, - }; -}; + }; diff --git a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/min_selectable_selection.ts b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/min_selectable_selection.ts index 9545012cc948..f532881555db 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/min_selectable_selection.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/min_selectable_selection.ts @@ -20,22 +20,24 @@ const { optionsToSelectedValue } = multiSelectComponent; * of items selected. * @param total Minimum number of items */ -export const minSelectableSelectionField = ({ - total = 0, - message, -}: { - total: number; - message: string | ((err: Partial) => string); -}) => (...args: Parameters): ReturnType> => { - const [{ value }] = args; +export const minSelectableSelectionField = + ({ + total = 0, + message, + }: { + total: number; + message: string | ((err: Partial) => string); + }) => + (...args: Parameters): ReturnType> => { + const [{ value }] = args; - // We need to convert all the options from the multi selectable component, to the - // an actual Array of selection _before_ validating the Array length. - return hasMinLengthArray(total)(optionsToSelectedValue(value as EuiSelectableOption[])) - ? undefined - : { - code: 'ERR_MIN_SELECTION', - total, - message: typeof message === 'function' ? message({ length }) : message, - }; -}; + // We need to convert all the options from the multi selectable component, to the + // an actual Array of selection _before_ validating the Array length. + return hasMinLengthArray(total)(optionsToSelectedValue(value as EuiSelectableOption[])) + ? undefined + : { + code: 'ERR_MIN_SELECTION', + total, + message: typeof message === 'function' ? message({ length }) : message, + }; + }; diff --git a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/number_greater_than.ts b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/number_greater_than.ts index aaa71d97016f..da4b5b239f10 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/number_greater_than.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/number_greater_than.ts @@ -10,22 +10,24 @@ import { ValidationFunc, ValidationError } from '../../hook_form_lib'; import { isNumberGreaterThan } from '../../../validators/number'; import { ERROR_CODE } from './types'; -export const numberGreaterThanField = ({ - than, - message, - allowEquality = false, -}: { - than: number; - message: string | ((err: Partial) => string); - allowEquality?: boolean; -}) => (...args: Parameters): ReturnType> => { - const [{ value }] = args; +export const numberGreaterThanField = + ({ + than, + message, + allowEquality = false, + }: { + than: number; + message: string | ((err: Partial) => string); + allowEquality?: boolean; + }) => + (...args: Parameters): ReturnType> => { + const [{ value }] = args; - return isNumberGreaterThan(than, allowEquality)(value as number) - ? undefined - : { - code: 'ERR_GREATER_THAN_NUMBER', - than, - message: typeof message === 'function' ? message({ than }) : message, - }; -}; + return isNumberGreaterThan(than, allowEquality)(value as number) + ? undefined + : { + code: 'ERR_GREATER_THAN_NUMBER', + than, + message: typeof message === 'function' ? message({ than }) : message, + }; + }; diff --git a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/number_smaller_than.ts b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/number_smaller_than.ts index a407cd45cbb9..5a965602f0c1 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/number_smaller_than.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/number_smaller_than.ts @@ -10,22 +10,24 @@ import { ValidationFunc, ValidationError } from '../../hook_form_lib'; import { isNumberSmallerThan } from '../../../validators/number'; import { ERROR_CODE } from './types'; -export const numberSmallerThanField = ({ - than, - message, - allowEquality = false, -}: { - than: number; - message: string | ((err: Partial) => string); - allowEquality?: boolean; -}) => (...args: Parameters): ReturnType> => { - const [{ value }] = args; +export const numberSmallerThanField = + ({ + than, + message, + allowEquality = false, + }: { + than: number; + message: string | ((err: Partial) => string); + allowEquality?: boolean; + }) => + (...args: Parameters): ReturnType> => { + const [{ value }] = args; - return isNumberSmallerThan(than, allowEquality)(value as number) - ? undefined - : { - code: 'ERR_SMALLER_THAN_NUMBER', - than, - message: typeof message === 'function' ? message({ than }) : message, - }; -}; + return isNumberSmallerThan(than, allowEquality)(value as number) + ? undefined + : { + code: 'ERR_SMALLER_THAN_NUMBER', + than, + message: typeof message === 'function' ? message({ than }) : message, + }; + }; diff --git a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/starts_with.ts b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/starts_with.ts index be8bb3c50309..4043fd3e4b7b 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/starts_with.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/starts_with.ts @@ -10,20 +10,20 @@ import { ValidationFunc } from '../../hook_form_lib'; import { startsWith } from '../../../validators/string'; import { ERROR_CODE } from './types'; -export const startsWithField = ({ message, char }: { message: string; char: string }) => ( - ...args: Parameters -): ReturnType> => { - const [{ value }] = args; +export const startsWithField = + ({ message, char }: { message: string; char: string }) => + (...args: Parameters): ReturnType> => { + const [{ value }] = args; - if (typeof value !== 'string') { - return; - } + if (typeof value !== 'string') { + return; + } - if (startsWith(char)(value)) { - return { - code: 'ERR_FIRST_CHAR', - char, - message, - }; - } -}; + if (startsWith(char)(value)) { + return { + code: 'ERR_FIRST_CHAR', + char, + message, + }; + } + }; diff --git a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/url.ts b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/url.ts index 2320c78954d4..ef05325030b2 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/field_validators/url.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/field_validators/url.ts @@ -10,20 +10,20 @@ import { ValidationFunc, ValidationError } from '../../hook_form_lib'; import { isUrl } from '../../../validators/string'; import { ERROR_CODE } from './types'; -export const urlField = (message: string) => ( - ...args: Parameters -): ReturnType> => { - const [{ value }] = args; +export const urlField = + (message: string) => + (...args: Parameters): ReturnType> => { + const [{ value }] = args; - const error: ValidationError = { - code: 'ERR_FIELD_FORMAT', - formatType: 'URL', - message, - }; + const error: ValidationError = { + code: 'ERR_FIELD_FORMAT', + formatType: 'URL', + message, + }; - if (typeof value !== 'string') { - return error; - } + if (typeof value !== 'string') { + return error; + } - return isUrl(value) ? undefined : error; -}; + return isUrl(value) ? undefined : error; + }; 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 89eacfc0cb9d..a73eee1bd8bd 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 @@ -106,7 +106,7 @@ function UseFieldComp(props: Props ); 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 ececf724db45..af6904dbacdd 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 @@ -40,7 +40,7 @@ export const useField = ( const { type = FIELD_TYPES.TEXT, defaultValue = '', // The value to use a fallback mecanism when no initial value is passed - initialValue = config.defaultValue ?? (('' as unknown) as I), // The value explicitly passed + initialValue = config.defaultValue ?? ('' as unknown as I), // The value explicitly passed isIncludedInOutput = true, label = '', labelAppend = '', @@ -364,7 +364,7 @@ export const useField = ( // ---------------------------------- const serializeValue: FieldHook['__serializeValue'] = useCallback( (internalValue: I = value) => { - return serializer ? serializer(internalValue) : ((internalValue as unknown) as T); + return serializer ? serializer(internalValue) : (internalValue as unknown as T); }, [serializer, value] ); @@ -463,7 +463,7 @@ export const useField = ( ? event.target.checked : event.target.value; - setValue((newValue as unknown) as I); + setValue(newValue as unknown as I); }, [setValue] ); 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 864579a8c71f..23827c0d1aa3 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 @@ -25,8 +25,15 @@ export interface UseFormReturn { export function useForm( formConfig?: FormConfig ): UseFormReturn { - const { onSubmit, schema, serializer, deserializer, options, id = 'default', defaultValue } = - formConfig ?? {}; + const { + onSubmit, + schema, + serializer, + deserializer, + options, + id = 'default', + defaultValue, + } = formConfig ?? {}; const initDefaultValue = useCallback( (_defaultValue?: Partial): { [key: string]: any } => { diff --git a/src/plugins/es_ui_shared/static/validators/array/has_max_length.ts b/src/plugins/es_ui_shared/static/validators/array/has_max_length.ts index 86524a7065f0..75b8a763c136 100644 --- a/src/plugins/es_ui_shared/static/validators/array/has_max_length.ts +++ b/src/plugins/es_ui_shared/static/validators/array/has_max_length.ts @@ -6,4 +6,7 @@ * Side Public License, v 1. */ -export const hasMaxLengthArray = (length = 5) => (value: any[]): boolean => value.length <= length; +export const hasMaxLengthArray = + (length = 5) => + (value: any[]): boolean => + value.length <= length; diff --git a/src/plugins/es_ui_shared/static/validators/array/has_min_length.ts b/src/plugins/es_ui_shared/static/validators/array/has_min_length.ts index 67ec079bd749..b32687881012 100644 --- a/src/plugins/es_ui_shared/static/validators/array/has_min_length.ts +++ b/src/plugins/es_ui_shared/static/validators/array/has_min_length.ts @@ -6,4 +6,7 @@ * Side Public License, v 1. */ -export const hasMinLengthArray = (length = 1) => (value: any[]): boolean => value.length >= length; +export const hasMinLengthArray = + (length = 1) => + (value: any[]): boolean => + value.length >= length; diff --git a/src/plugins/es_ui_shared/static/validators/number/greater_than.ts b/src/plugins/es_ui_shared/static/validators/number/greater_than.ts index 4d6c29ec340f..6526fdc44061 100644 --- a/src/plugins/es_ui_shared/static/validators/number/greater_than.ts +++ b/src/plugins/es_ui_shared/static/validators/number/greater_than.ts @@ -6,5 +6,7 @@ * Side Public License, v 1. */ -export const isNumberGreaterThan = (than: number, allowEquality = false) => (value: number) => - allowEquality ? value >= than : value > than; +export const isNumberGreaterThan = + (than: number, allowEquality = false) => + (value: number) => + allowEquality ? value >= than : value > than; diff --git a/src/plugins/es_ui_shared/static/validators/number/smaller_than.ts b/src/plugins/es_ui_shared/static/validators/number/smaller_than.ts index 3f921587f358..38001493f6ee 100644 --- a/src/plugins/es_ui_shared/static/validators/number/smaller_than.ts +++ b/src/plugins/es_ui_shared/static/validators/number/smaller_than.ts @@ -6,5 +6,7 @@ * Side Public License, v 1. */ -export const isNumberSmallerThan = (than: number, allowEquality = false) => (value: number) => - allowEquality ? value <= than : value < than; +export const isNumberSmallerThan = + (than: number, allowEquality = false) => + (value: number) => + allowEquality ? value <= than : value < than; diff --git a/src/plugins/expression_error/public/plugin.ts b/src/plugins/expression_error/public/plugin.ts index 3727cab5436c..0b82ccf5d2db 100755 --- a/src/plugins/expression_error/public/plugin.ts +++ b/src/plugins/expression_error/public/plugin.ts @@ -22,7 +22,8 @@ export type ExpressionErrorPluginSetup = void; export type ExpressionErrorPluginStart = void; export class ExpressionErrorPlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, { expressions }: SetupDeps): ExpressionErrorPluginSetup { expressions.registerRenderer(errorRenderer); expressions.registerRenderer(debugRenderer); diff --git a/src/plugins/expression_image/public/plugin.ts b/src/plugins/expression_image/public/plugin.ts index 44feea412163..6e6c02248642 100755 --- a/src/plugins/expression_image/public/plugin.ts +++ b/src/plugins/expression_image/public/plugin.ts @@ -23,7 +23,8 @@ export type ExpressionImagePluginSetup = void; export type ExpressionImagePluginStart = void; export class ExpressionImagePlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, { expressions }: SetupDeps): ExpressionImagePluginSetup { expressions.registerFunction(imageFunction); expressions.registerRenderer(imageRenderer); diff --git a/src/plugins/expression_image/server/plugin.ts b/src/plugins/expression_image/server/plugin.ts index d3259d45107e..b342bb96647c 100755 --- a/src/plugins/expression_image/server/plugin.ts +++ b/src/plugins/expression_image/server/plugin.ts @@ -22,7 +22,8 @@ export type ExpressionImagePluginSetup = void; export type ExpressionImagePluginStart = void; export class ExpressionImagePlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, { expressions }: SetupDeps): ExpressionImagePluginSetup { expressions.registerFunction(imageFunction); } diff --git a/src/plugins/expression_metric/public/plugin.ts b/src/plugins/expression_metric/public/plugin.ts index c11a5a4cdcad..8711a824fb7b 100755 --- a/src/plugins/expression_metric/public/plugin.ts +++ b/src/plugins/expression_metric/public/plugin.ts @@ -23,8 +23,8 @@ export type ExpressionMetricPluginSetup = void; export type ExpressionMetricPluginStart = void; export class ExpressionMetricPlugin - implements - Plugin { + implements Plugin +{ public setup(core: CoreSetup, { expressions }: SetupDeps): ExpressionMetricPluginSetup { expressions.registerFunction(metricFunction); expressions.registerRenderer(metricRenderer); diff --git a/src/plugins/expression_metric/server/plugin.ts b/src/plugins/expression_metric/server/plugin.ts index 81c87f5c0558..29281faf0b79 100755 --- a/src/plugins/expression_metric/server/plugin.ts +++ b/src/plugins/expression_metric/server/plugin.ts @@ -22,8 +22,8 @@ export type ExpressionMetricPluginSetup = void; export type ExpressionMetricPluginStart = void; export class ExpressionMetricPlugin - implements - Plugin { + implements Plugin +{ public setup(core: CoreSetup, { expressions }: SetupDeps): ExpressionMetricPluginSetup { expressions.registerFunction(metricFunction); } diff --git a/src/plugins/expression_repeat_image/public/plugin.ts b/src/plugins/expression_repeat_image/public/plugin.ts index aba8fff219c4..d71ce99eb1bd 100755 --- a/src/plugins/expression_repeat_image/public/plugin.ts +++ b/src/plugins/expression_repeat_image/public/plugin.ts @@ -29,7 +29,8 @@ export class ExpressionRepeatImagePlugin ExpressionRepeatImagePluginStart, SetupDeps, StartDeps - > { + > +{ public setup(core: CoreSetup, { expressions }: SetupDeps): ExpressionRepeatImagePluginSetup { expressions.registerFunction(repeatImageFunction); expressions.registerRenderer(repeatImageRenderer); diff --git a/src/plugins/expression_repeat_image/server/plugin.ts b/src/plugins/expression_repeat_image/server/plugin.ts index 744a3fb7f35b..eff5e24ef65f 100755 --- a/src/plugins/expression_repeat_image/server/plugin.ts +++ b/src/plugins/expression_repeat_image/server/plugin.ts @@ -28,7 +28,8 @@ export class ExpressionRepeatImagePlugin ExpressionRepeatImagePluginStart, SetupDeps, StartDeps - > { + > +{ public setup(core: CoreSetup, { expressions }: SetupDeps): ExpressionRepeatImagePluginSetup { expressions.registerFunction(repeatImageFunction); } diff --git a/src/plugins/expression_reveal_image/public/plugin.ts b/src/plugins/expression_reveal_image/public/plugin.ts index c3522b43ca0c..c5e1b5c8d916 100755 --- a/src/plugins/expression_reveal_image/public/plugin.ts +++ b/src/plugins/expression_reveal_image/public/plugin.ts @@ -29,7 +29,8 @@ export class ExpressionRevealImagePlugin ExpressionRevealImagePluginStart, SetupDeps, StartDeps - > { + > +{ public setup(core: CoreSetup, { expressions }: SetupDeps): ExpressionRevealImagePluginSetup { expressions.registerFunction(revealImageFunction); expressions.registerRenderer(revealImageRenderer); diff --git a/src/plugins/expression_reveal_image/server/plugin.ts b/src/plugins/expression_reveal_image/server/plugin.ts index 446ef018eb7d..c85ff9c62081 100644 --- a/src/plugins/expression_reveal_image/server/plugin.ts +++ b/src/plugins/expression_reveal_image/server/plugin.ts @@ -28,7 +28,8 @@ export class ExpressionRevealImagePlugin ExpressionRevealImagePluginStart, SetupDeps, StartDeps - > { + > +{ public setup(core: CoreSetup, { expressions }: SetupDeps): ExpressionRevealImagePluginSetup { expressions.registerFunction(revealImageFunction); } diff --git a/src/plugins/expression_shape/public/components/progress/shapes/unicorn.tsx b/src/plugins/expression_shape/public/components/progress/shapes/unicorn.tsx index 020176244e44..505a3b41bcbb 100644 --- a/src/plugins/expression_shape/public/components/progress/shapes/unicorn.tsx +++ b/src/plugins/expression_shape/public/components/progress/shapes/unicorn.tsx @@ -17,8 +17,7 @@ export const Unicorn = createShape({ }, shapeType: SvgElementTypes.path, shapeProps: { - d: - 'M 123 189 C 93 141 129 126 102 96 L 78 102 L 48 117 L 42 129 Q 30 132 21 126 L 18 114 L 27 90 L 42 72 L 48 57 L 3 6 L 57 42 L 63 33 L 60 15 L 69 27 L 69 15 L 84 27 Q 162 36 195 108 Q 174 159 123 189 Z', + d: 'M 123 189 C 93 141 129 126 102 96 L 78 102 L 48 117 L 42 129 Q 30 132 21 126 L 18 114 L 27 90 L 42 72 L 48 57 L 3 6 L 57 42 L 63 33 L 60 15 L 69 27 L 69 15 L 84 27 Q 162 36 195 108 Q 174 159 123 189 Z', }, textAttributes: { x: '0', diff --git a/src/plugins/expression_shape/public/plugin.ts b/src/plugins/expression_shape/public/plugin.ts index 0b8fa274e2b0..9403bce0af72 100755 --- a/src/plugins/expression_shape/public/plugin.ts +++ b/src/plugins/expression_shape/public/plugin.ts @@ -23,7 +23,8 @@ export type ExpressionShapePluginSetup = void; export type ExpressionShapePluginStart = void; export class ExpressionShapePlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, { expressions }: SetupDeps): ExpressionShapePluginSetup { expressions.registerFunction(shapeFunction); expressions.registerFunction(progressFunction); diff --git a/src/plugins/expression_shape/server/plugin.ts b/src/plugins/expression_shape/server/plugin.ts index d6eb7a8e717c..a98d0fe3f17f 100644 --- a/src/plugins/expression_shape/server/plugin.ts +++ b/src/plugins/expression_shape/server/plugin.ts @@ -22,7 +22,8 @@ export type ExpressionShapePluginSetup = void; export type ExpressionShapePluginStart = void; export class ExpressionShapePlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, { expressions }: SetupDeps): ExpressionShapePluginSetup { expressions.registerFunction(shapeFunction); expressions.registerFunction(progressFunction); diff --git a/src/plugins/expressions/common/ast/build_function.ts b/src/plugins/expressions/common/ast/build_function.ts index 0003a5233d30..1ccd8d8795a8 100644 --- a/src/plugins/expressions/common/ast/build_function.ts +++ b/src/plugins/expressions/common/ast/build_function.ts @@ -21,22 +21,20 @@ import { format } from './format'; // Infers the types from an ExpressionFunctionDefinition. // @internal -export type InferFunctionDefinition< - FnDef extends AnyExpressionFunctionDefinition -> = FnDef extends ExpressionFunctionDefinition< - infer Name, - infer Input, - infer Arguments, - infer Output, - infer Context -> - ? { name: Name; input: Input; arguments: Arguments; output: Output; context: Context } - : never; +export type InferFunctionDefinition = + FnDef extends ExpressionFunctionDefinition< + infer Name, + infer Input, + infer Arguments, + infer Output, + infer Context + > + ? { name: Name; input: Input; arguments: Arguments; output: Output; context: Context } + : never; // Shortcut for inferring args from a function definition. -type FunctionArgs< - FnDef extends AnyExpressionFunctionDefinition -> = InferFunctionDefinition['arguments']; +type FunctionArgs = + InferFunctionDefinition['arguments']; // Gets a list of possible arg names for a given function. type FunctionArgName = { diff --git a/src/plugins/expressions/common/execution/execution.ts b/src/plugins/expressions/common/execution/execution.ts index 75b6c9e60613..0c4185c82dc3 100644 --- a/src/plugins/expressions/common/execution/execution.ts +++ b/src/plugins/expressions/common/execution/execution.ts @@ -158,11 +158,8 @@ export class Execution< * Contract is a public representation of `Execution` instances. Contract we * can return to other plugins for their consumption. */ - public readonly contract: ExecutionContract< - Input, - Output, - InspectorAdapters - > = new ExecutionContract(this); + public readonly contract: ExecutionContract = + new ExecutionContract(this); public readonly expression: string; @@ -474,17 +471,19 @@ export class Execution< // Create the functions to resolve the argument ASTs into values // These are what are passed to the actual functions if you opt out of resolving const resolveArgFns = mapValues(dealiasedArgAsts, (asts, argName) => - asts.map((item) => (subInput = input) => - this.interpret(item, subInput).pipe( - pluck('result'), - map((output) => { - if (isExpressionValueError(output)) { - throw output.error; - } - - return this.cast(output, argDefs[argName].types); - }) - ) + asts.map( + (item) => + (subInput = input) => + this.interpret(item, subInput).pipe( + pluck('result'), + map((output) => { + if (isExpressionValueError(output)) { + throw output.error; + } + + return this.cast(output, argDefs[argName].types); + }) + ) ) ); diff --git a/src/plugins/expressions/common/executor/container.ts b/src/plugins/expressions/common/executor/container.ts index 87c45bb2c40b..9d3796ac64f4 100644 --- a/src/plugins/expressions/common/executor/container.ts +++ b/src/plugins/expressions/common/executor/container.ts @@ -49,12 +49,14 @@ export interface ExecutorPureSelectors { export const pureSelectors: ExecutorPureSelectors = { getFunction: (state) => (id) => state.functions[id] || null, getType: (state) => (id) => state.types[id] || null, - getContext: ({ context }) => () => context, + getContext: + ({ context }) => + () => + context, }; -export type ExecutorContainer< - Context extends Record = Record -> = StateContainer, ExecutorPureTransitions, ExecutorPureSelectors>; +export type ExecutorContainer = Record> = + StateContainer, ExecutorPureTransitions, ExecutorPureSelectors>; export const createExecutorContainer = < Context extends Record = Record diff --git a/src/plugins/expressions/common/executor/executor.test.ts b/src/plugins/expressions/common/executor/executor.test.ts index 75758dad783a..4a3d6045a7b4 100644 --- a/src/plugins/expressions/common/executor/executor.test.ts +++ b/src/plugins/expressions/common/executor/executor.test.ts @@ -173,12 +173,12 @@ describe('Executor', () => { return injectFn(state); }, migrations: { - '7.10.0': (((state: ExpressionAstFunction, version: string): ExpressionAstFunction => { + '7.10.0': ((state: ExpressionAstFunction, version: string): ExpressionAstFunction => { return migrateFn(state, version); - }) as any) as MigrateFunction, - '7.10.1': (((state: ExpressionAstFunction, version: string): ExpressionAstFunction => { + }) as any as MigrateFunction, + '7.10.1': ((state: ExpressionAstFunction, version: string): ExpressionAstFunction => { return migrateFn(state, version); - }) as any) as MigrateFunction, + }) as any as MigrateFunction, }, fn: jest.fn(), }; diff --git a/src/plugins/expressions/common/executor/executor.ts b/src/plugins/expressions/common/executor/executor.ts index eb0e344b6dd6..55d3a7b89786 100644 --- a/src/plugins/expressions/common/executor/executor.ts +++ b/src/plugins/expressions/common/executor/executor.ts @@ -84,7 +84,8 @@ export class FunctionsRegistry implements IRegistry { } export class Executor = Record> - implements PersistableStateService { + implements PersistableStateService +{ static createWithDefaults = Record>( state?: ExecutorState ): Executor { diff --git a/src/plugins/expressions/common/expression_functions/expression_function.ts b/src/plugins/expressions/common/expression_functions/expression_function.ts index 963d2186af73..05a5dbb638c0 100644 --- a/src/plugins/expressions/common/expression_functions/expression_function.ts +++ b/src/plugins/expressions/common/expression_functions/expression_function.ts @@ -58,9 +58,10 @@ export class ExpressionFunction implements PersistableState ) => Record; - extract: ( - state: ExpressionAstFunction['arguments'] - ) => { state: ExpressionAstFunction['arguments']; references: SavedObjectReference[] }; + extract: (state: ExpressionAstFunction['arguments']) => { + state: ExpressionAstFunction['arguments']; + references: SavedObjectReference[]; + }; inject: ( state: ExpressionAstFunction['arguments'], references: SavedObjectReference[] diff --git a/src/plugins/expressions/common/expression_functions/specs/tests/ui_setting.test.ts b/src/plugins/expressions/common/expression_functions/specs/tests/ui_setting.test.ts index fb2c87588a4d..6b3a458aa7e5 100644 --- a/src/plugins/expressions/common/expression_functions/specs/tests/ui_setting.test.ts +++ b/src/plugins/expressions/common/expression_functions/specs/tests/ui_setting.test.ts @@ -20,12 +20,12 @@ describe('uiSetting', () => { let uiSettings: jest.Mocked; beforeEach(() => { - uiSettings = ({ + uiSettings = { get: jest.fn(), - } as unknown) as jest.Mocked; - getStartDependencies = (jest.fn(async () => ({ + } as unknown as jest.Mocked; + getStartDependencies = jest.fn(async () => ({ uiSettings, - })) as unknown) as typeof getStartDependencies; + })) as unknown as typeof getStartDependencies; uiSetting = getUiSettingFn({ getStartDependencies }); }); diff --git a/src/plugins/expressions/public/react_expression_renderer.tsx b/src/plugins/expressions/public/react_expression_renderer.tsx index 2640be16eae4..428419c4ff02 100644 --- a/src/plugins/expressions/public/react_expression_renderer.tsx +++ b/src/plugins/expressions/public/react_expression_renderer.tsx @@ -79,9 +79,8 @@ export const ReactExpressionRenderer = ({ const hasHandledErrorRef = useRef(false); // will call done() in LayoutEffect when done with rendering custom error state - const errorRenderHandlerRef: React.MutableRefObject = useRef( - null - ); + const errorRenderHandlerRef: React.MutableRefObject = + useRef(null); const [debouncedExpression, setDebouncedExpression] = useState(expression); const [waitingForDebounceToComplete, setDebouncePending] = useState(false); const firstRender = useRef(true); diff --git a/src/plugins/expressions/public/services/index.ts b/src/plugins/expressions/public/services/index.ts index db473037a0a4..198ff129bcce 100644 --- a/src/plugins/expressions/public/services/index.ts +++ b/src/plugins/expressions/public/services/index.ts @@ -10,18 +10,13 @@ import { NotificationsStart } from 'kibana/public'; import { createGetterSetter } from '../../../kibana_utils/public'; import { ExpressionsService, ExpressionRendererRegistry } from '../../common'; -export const [getNotifications, setNotifications] = createGetterSetter( - 'Notifications' -); +export const [getNotifications, setNotifications] = + createGetterSetter('Notifications'); -export const [ - getRenderersRegistry, - setRenderersRegistry, -] = createGetterSetter('Renderers registry'); +export const [getRenderersRegistry, setRenderersRegistry] = + createGetterSetter('Renderers registry'); -export const [ - getExpressionsService, - setExpressionsService, -] = createGetterSetter('ExpressionsService'); +export const [getExpressionsService, setExpressionsService] = + createGetterSetter('ExpressionsService'); export * from './expressions_services'; diff --git a/src/plugins/expressions/server/plugin.ts b/src/plugins/expressions/server/plugin.ts index 2e45daf6e0f8..65942ddb0ec1 100644 --- a/src/plugins/expressions/server/plugin.ts +++ b/src/plugins/expressions/server/plugin.ts @@ -15,7 +15,8 @@ export type ExpressionsServerSetup = ExpressionsServiceSetup; export type ExpressionsServerStart = ExpressionsServiceStart; export class ExpressionsServerPlugin - implements Plugin { + implements Plugin +{ readonly expressions: ExpressionsService = new ExpressionsService(); constructor(initializerContext: PluginInitializerContext) {} diff --git a/src/plugins/field_formats/common/converters/duration.ts b/src/plugins/field_formats/common/converters/duration.ts index c913ee03d9d3..72f893b59ef4 100644 --- a/src/plugins/field_formats/common/converters/duration.ts +++ b/src/plugins/field_formats/common/converters/duration.ts @@ -179,9 +179,9 @@ const outputFormats = [ function parseInputAsDuration(val: number, inputFormat: string) { const ratio = ratioToSeconds[inputFormat] || 1; - const kind = (inputFormat in ratioToSeconds - ? 'seconds' - : inputFormat) as unitOfTime.DurationConstructor; + const kind = ( + inputFormat in ratioToSeconds ? 'seconds' : inputFormat + ) as unitOfTime.DurationConstructor; return moment.duration(val * ratio, kind); } @@ -193,9 +193,9 @@ function formatInputHumanPrecise( includeSpace: string ) { const ratio = ratioToSeconds[inputFormat] || 1; - const kind = (inputFormat in ratioToSeconds - ? 'seconds' - : inputFormat) as unitOfTime.DurationConstructor; + const kind = ( + inputFormat in ratioToSeconds ? 'seconds' : inputFormat + ) as unitOfTime.DurationConstructor; const valueInDuration = moment.duration(val * ratio, kind); return formatDuration( diff --git a/src/plugins/home/public/application/components/add_data/add_data.test.tsx b/src/plugins/home/public/application/components/add_data/add_data.test.tsx index 3e324685c840..4018ae67c19e 100644 --- a/src/plugins/home/public/application/components/add_data/add_data.test.tsx +++ b/src/plugins/home/public/application/components/add_data/add_data.test.tsx @@ -27,7 +27,7 @@ beforeEach(() => { jest.clearAllMocks(); }); -const applicationStartMock = ({} as unknown) as ApplicationStart; +const applicationStartMock = {} as unknown as ApplicationStart; const addBasePathMock = jest.fn((path: string) => (path ? path : 'path')); diff --git a/src/plugins/home/public/application/components/manage_data/manage_data.test.tsx b/src/plugins/home/public/application/components/manage_data/manage_data.test.tsx index 24b8b118f766..fb222be65778 100644 --- a/src/plugins/home/public/application/components/manage_data/manage_data.test.tsx +++ b/src/plugins/home/public/application/components/manage_data/manage_data.test.tsx @@ -29,13 +29,13 @@ beforeEach(() => { jest.clearAllMocks(); }); -const applicationStartMock = ({ +const applicationStartMock = { capabilities: { navLinks: { management: true, dev_tools: true } }, -} as unknown) as ApplicationStart; +} as unknown as ApplicationStart; -const applicationStartMockRestricted = ({ +const applicationStartMockRestricted = { capabilities: { navLinks: { management: false, dev_tools: false } }, -} as unknown) as ApplicationStart; +} as unknown as ApplicationStart; const addBasePathMock = jest.fn((path: string) => (path ? path : 'path')); diff --git a/src/plugins/home/public/application/components/manage_data/manage_data.tsx b/src/plugins/home/public/application/components/manage_data/manage_data.tsx index 746afad9d5b5..b374bdd2e161 100644 --- a/src/plugins/home/public/application/components/manage_data/manage_data.tsx +++ b/src/plugins/home/public/application/components/manage_data/manage_data.tsx @@ -39,10 +39,8 @@ export const ManageData: FC = ({ addBasePath, application, features }) => ?.useUrl({ sectionId: '' }); if (features.length) { - const { - management: isManagementEnabled, - dev_tools: isDevToolsEnabled, - } = application.capabilities.navLinks; + const { management: isManagementEnabled, dev_tools: isDevToolsEnabled } = + application.capabilities.navLinks; return ( <> diff --git a/src/plugins/home/public/plugin.ts b/src/plugins/home/public/plugin.ts index 7dd1d8728ad7..d3ef97ed11be 100644 --- a/src/plugins/home/public/plugin.ts +++ b/src/plugins/home/public/plugin.ts @@ -56,7 +56,8 @@ export class HomePublicPlugin HomePublicPluginStart, HomePluginSetupDependencies, HomePluginStartDependencies - > { + > +{ private readonly featuresCatalogueRegistry = new FeatureCatalogueRegistry(); private readonly environmentService = new EnvironmentService(); private readonly tutorialService = new TutorialService(); @@ -76,10 +77,8 @@ export class HomePublicPlugin const trackUiMetric = usageCollection ? usageCollection.reportUiCounter.bind(usageCollection, 'Kibana_home') : () => {}; - const [ - coreStart, - { telemetry, data, urlForwarding: urlForwardingStart }, - ] = await core.getStartServices(); + const [coreStart, { telemetry, data, urlForwarding: urlForwardingStart }] = + await core.getStartServices(); setServices({ share, trackUiMetric, 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 4940a7dd5c22..0b38d8359890 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 @@ -120,12 +120,14 @@ export class FeatureCatalogueRegistry { export type FeatureCatalogueRegistrySetup = ReturnType; -const compareByKey = (key: keyof T) => (left: T, right: T) => { - if (left[key] < right[key]) { - return -1; - } else if (left[key] > right[key]) { - return 1; - } else { - return 0; - } -}; +const compareByKey = + (key: keyof T) => + (left: T, right: T) => { + if (left[key] < right[key]) { + return -1; + } else if (left[key] > right[key]) { + return 1; + } else { + return 0; + } + }; diff --git a/src/plugins/home/server/services/sample_data/data_sets/flights/saved_objects.ts b/src/plugins/home/server/services/sample_data/data_sets/flights/saved_objects.ts index 8227e48501aa..8552d74201fe 100644 --- a/src/plugins/home/server/services/sample_data/data_sets/flights/saved_objects.ts +++ b/src/plugins/home/server/services/sample_data/data_sets/flights/saved_objects.ts @@ -254,20 +254,17 @@ export const getSavedObjects = (): SavedObject[] => [ }, { id: 'd3d7af60-4c81-11e8-b3d7-01146121b73d', - name: - 'aa810aa2-29c9-4a75-b39e-f4f267de1732:control_aa810aa2-29c9-4a75-b39e-f4f267de1732_0_index_pattern', + name: 'aa810aa2-29c9-4a75-b39e-f4f267de1732:control_aa810aa2-29c9-4a75-b39e-f4f267de1732_0_index_pattern', type: 'index-pattern', }, { id: 'd3d7af60-4c81-11e8-b3d7-01146121b73d', - name: - 'aa810aa2-29c9-4a75-b39e-f4f267de1732:control_aa810aa2-29c9-4a75-b39e-f4f267de1732_1_index_pattern', + name: 'aa810aa2-29c9-4a75-b39e-f4f267de1732:control_aa810aa2-29c9-4a75-b39e-f4f267de1732_1_index_pattern', type: 'index-pattern', }, { id: 'd3d7af60-4c81-11e8-b3d7-01146121b73d', - name: - 'aa810aa2-29c9-4a75-b39e-f4f267de1732:control_aa810aa2-29c9-4a75-b39e-f4f267de1732_2_index_pattern', + name: 'aa810aa2-29c9-4a75-b39e-f4f267de1732:control_aa810aa2-29c9-4a75-b39e-f4f267de1732_2_index_pattern', type: 'index-pattern', }, { @@ -277,8 +274,7 @@ export const getSavedObjects = (): SavedObject[] => [ }, { id: 'd3d7af60-4c81-11e8-b3d7-01146121b73d', - name: - '086ac2e9-dd16-4b45-92b8-1e43ff7e3f65:indexpattern-datasource-layer-03c34665-471c-49c7-acf1-5a11f517421c', + name: '086ac2e9-dd16-4b45-92b8-1e43ff7e3f65:indexpattern-datasource-layer-03c34665-471c-49c7-acf1-5a11f517421c', type: 'index-pattern', }, { @@ -288,8 +284,7 @@ export const getSavedObjects = (): SavedObject[] => [ }, { id: 'd3d7af60-4c81-11e8-b3d7-01146121b73d', - name: - '9271deff-5a61-4665-83fc-f9fdc6bf0c0b:indexpattern-datasource-layer-b4712d43-1e84-4f5b-878d-8e38ba748317', + name: '9271deff-5a61-4665-83fc-f9fdc6bf0c0b:indexpattern-datasource-layer-b4712d43-1e84-4f5b-878d-8e38ba748317', type: 'index-pattern', }, { @@ -299,8 +294,7 @@ export const getSavedObjects = (): SavedObject[] => [ }, { id: 'd3d7af60-4c81-11e8-b3d7-01146121b73d', - name: - 'aa591c29-1a31-4ee1-a71d-b829c06fd162:indexpattern-datasource-layer-b4712d43-1e84-4f5b-878d-8e38ba748317', + name: 'aa591c29-1a31-4ee1-a71d-b829c06fd162:indexpattern-datasource-layer-b4712d43-1e84-4f5b-878d-8e38ba748317', type: 'index-pattern', }, { @@ -315,8 +309,7 @@ export const getSavedObjects = (): SavedObject[] => [ }, { id: 'd3d7af60-4c81-11e8-b3d7-01146121b73d', - name: - 'b766e3b8-4544-46ed-99e6-9ecc4847e2a2:indexpattern-datasource-layer-b4712d43-1e84-4f5b-878d-8e38ba748317', + name: 'b766e3b8-4544-46ed-99e6-9ecc4847e2a2:indexpattern-datasource-layer-b4712d43-1e84-4f5b-878d-8e38ba748317', type: 'index-pattern', }, { @@ -326,8 +319,7 @@ export const getSavedObjects = (): SavedObject[] => [ }, { id: 'd3d7af60-4c81-11e8-b3d7-01146121b73d', - name: - '2e33ade5-96e5-40b4-b460-493e5d4fa834:indexpattern-datasource-layer-b4712d43-1e84-4f5b-878d-8e38ba748317', + name: '2e33ade5-96e5-40b4-b460-493e5d4fa834:indexpattern-datasource-layer-b4712d43-1e84-4f5b-878d-8e38ba748317', type: 'index-pattern', }, { @@ -342,8 +334,7 @@ export const getSavedObjects = (): SavedObject[] => [ }, { id: 'd3d7af60-4c81-11e8-b3d7-01146121b73d', - name: - 'fb86b32f-fb7a-45cf-9511-f366fef51bbd:indexpattern-datasource-layer-f26e8f7a-4118-4227-bea0-5c02d8b270f7', + name: 'fb86b32f-fb7a-45cf-9511-f366fef51bbd:indexpattern-datasource-layer-f26e8f7a-4118-4227-bea0-5c02d8b270f7', type: 'index-pattern', }, { @@ -353,8 +344,7 @@ export const getSavedObjects = (): SavedObject[] => [ }, { id: 'd3d7af60-4c81-11e8-b3d7-01146121b73d', - name: - '5d53db36-2d5a-4adc-af7b-cec4c1a294e0:indexpattern-datasource-layer-0c8e136b-a822-4fb3-836d-e06cbea4eea4', + name: '5d53db36-2d5a-4adc-af7b-cec4c1a294e0:indexpattern-datasource-layer-0c8e136b-a822-4fb3-836d-e06cbea4eea4', type: 'index-pattern', }, { @@ -369,8 +359,7 @@ export const getSavedObjects = (): SavedObject[] => [ }, { id: 'd3d7af60-4c81-11e8-b3d7-01146121b73d', - name: - '0cc42484-16f7-42ec-b38c-9bf8be69cde7:indexpattern-datasource-layer-e80cc05e-c52a-4e5f-ac71-4b37274867f5', + name: '0cc42484-16f7-42ec-b38c-9bf8be69cde7:indexpattern-datasource-layer-e80cc05e-c52a-4e5f-ac71-4b37274867f5', type: 'index-pattern', }, { @@ -380,8 +369,7 @@ export const getSavedObjects = (): SavedObject[] => [ }, { id: 'd3d7af60-4c81-11e8-b3d7-01146121b73d', - name: - '392b4936-f753-47bc-a98d-a4e41a0a4cd4:indexpattern-datasource-layer-8fa993db-c147-4954-adf7-4ff264d42576', + name: '392b4936-f753-47bc-a98d-a4e41a0a4cd4:indexpattern-datasource-layer-8fa993db-c147-4954-adf7-4ff264d42576', type: 'index-pattern', }, ], diff --git a/src/plugins/home/server/services/sample_data/data_sets/logs/saved_objects.ts b/src/plugins/home/server/services/sample_data/data_sets/logs/saved_objects.ts index f7e8c824030b..c60110176b67 100644 --- a/src/plugins/home/server/services/sample_data/data_sets/logs/saved_objects.ts +++ b/src/plugins/home/server/services/sample_data/data_sets/logs/saved_objects.ts @@ -396,20 +396,17 @@ export const getSavedObjects = (): SavedObject[] => [ }, { id: '90943e30-9a47-11e8-b64d-95841ca0b247', - name: - '30326cdb-4ddd-49eb-a4f1-b555caa21d7c:control_30326cdb-4ddd-49eb-a4f1-b555caa21d7c_0_index_pattern', + name: '30326cdb-4ddd-49eb-a4f1-b555caa21d7c:control_30326cdb-4ddd-49eb-a4f1-b555caa21d7c_0_index_pattern', type: 'index-pattern', }, { id: '90943e30-9a47-11e8-b64d-95841ca0b247', - name: - '30326cdb-4ddd-49eb-a4f1-b555caa21d7c:control_30326cdb-4ddd-49eb-a4f1-b555caa21d7c_1_index_pattern', + name: '30326cdb-4ddd-49eb-a4f1-b555caa21d7c:control_30326cdb-4ddd-49eb-a4f1-b555caa21d7c_1_index_pattern', type: 'index-pattern', }, { id: '90943e30-9a47-11e8-b64d-95841ca0b247', - name: - '30326cdb-4ddd-49eb-a4f1-b555caa21d7c:control_30326cdb-4ddd-49eb-a4f1-b555caa21d7c_2_index_pattern', + name: '30326cdb-4ddd-49eb-a4f1-b555caa21d7c:control_30326cdb-4ddd-49eb-a4f1-b555caa21d7c_2_index_pattern', type: 'index-pattern', }, { @@ -419,8 +416,7 @@ export const getSavedObjects = (): SavedObject[] => [ }, { id: '90943e30-9a47-11e8-b64d-95841ca0b247', - name: - 'bb94016e-f4a6-49ca-87a9-296a2869d570:indexpattern-datasource-layer-483defd2-775b-4a62-bdef-496c819bb8ed', + name: 'bb94016e-f4a6-49ca-87a9-296a2869d570:indexpattern-datasource-layer-483defd2-775b-4a62-bdef-496c819bb8ed', type: 'index-pattern', }, { @@ -430,8 +426,7 @@ export const getSavedObjects = (): SavedObject[] => [ }, { id: '90943e30-9a47-11e8-b64d-95841ca0b247', - name: - '01d8e435-91c0-484f-a11e-856747050b0a:indexpattern-datasource-layer-f3793bb7-3971-4753-866d-4008e77a9f9a', + name: '01d8e435-91c0-484f-a11e-856747050b0a:indexpattern-datasource-layer-f3793bb7-3971-4753-866d-4008e77a9f9a', type: 'index-pattern', }, { @@ -441,8 +436,7 @@ export const getSavedObjects = (): SavedObject[] => [ }, { id: '90943e30-9a47-11e8-b64d-95841ca0b247', - name: - '8c1456d4-1993-4ba2-b701-04aca02c9fef:indexpattern-datasource-layer-f3793bb7-3971-4753-866d-4008e77a9f9a', + name: '8c1456d4-1993-4ba2-b701-04aca02c9fef:indexpattern-datasource-layer-f3793bb7-3971-4753-866d-4008e77a9f9a', type: 'index-pattern', }, { @@ -457,8 +451,7 @@ export const getSavedObjects = (): SavedObject[] => [ }, { id: '90943e30-9a47-11e8-b64d-95841ca0b247', - name: - '1d5f0b3f-d9d2-4b26-997b-83bc5ca3090b:indexpattern-datasource-layer-c35dc8ee-50d1-4ef7-8b4b-9c21a7e7d3b0', + name: '1d5f0b3f-d9d2-4b26-997b-83bc5ca3090b:indexpattern-datasource-layer-c35dc8ee-50d1-4ef7-8b4b-9c21a7e7d3b0', type: 'index-pattern', }, { 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 72d8c31cbafd..e3e213196889 100644 --- a/src/plugins/home/server/services/sample_data/routes/list.ts +++ b/src/plugins/home/server/services/sample_data/routes/list.ts @@ -36,11 +36,10 @@ export const createListRoute = (router: IRouter, sampleDatasets: SampleDatasetSc const dataIndexConfig = sampleDataset.dataIndices[i]; const index = createIndexName(sampleDataset.id, dataIndexConfig.id); try { - const { - body: indexExists, - } = await context.core.elasticsearch.client.asCurrentUser.indices.exists({ - index, - }); + const { body: indexExists } = + await context.core.elasticsearch.client.asCurrentUser.indices.exists({ + index, + }); if (!indexExists) { sampleDataset.status = NOT_INSTALLED; return; diff --git a/src/plugins/home/server/tutorials/instructions/logstash_instructions.ts b/src/plugins/home/server/tutorials/instructions/logstash_instructions.ts index 350464a47b40..28a99f21e25c 100644 --- a/src/plugins/home/server/tutorials/instructions/logstash_instructions.ts +++ b/src/plugins/home/server/tutorials/instructions/logstash_instructions.ts @@ -37,8 +37,7 @@ export const createLogstashInstructions = () => ({ { defaultMessage: 'First time using Logstash? See the [Getting Started Guide]({link}).', values: { - link: - '{config.docs.base_url}guide/en/logstash/current/getting-started-with-logstash.html', + link: '{config.docs.base_url}guide/en/logstash/current/getting-started-with-logstash.html', }, } ), @@ -61,8 +60,7 @@ export const createLogstashInstructions = () => ({ { defaultMessage: 'Follow the installation instructions [here]({link}).', values: { - link: - 'https://docs.oracle.com/javase/8/docs/technotes/guides/install/windows_jre_install.html', + link: 'https://docs.oracle.com/javase/8/docs/technotes/guides/install/windows_jre_install.html', }, } ), diff --git a/src/plugins/index_pattern_editor/public/components/empty_prompts/empty_prompts.tsx b/src/plugins/index_pattern_editor/public/components/empty_prompts/empty_prompts.tsx index 591d3975acae..51c64f4c1340 100644 --- a/src/plugins/index_pattern_editor/public/components/empty_prompts/empty_prompts.tsx +++ b/src/plugins/index_pattern_editor/public/components/empty_prompts/empty_prompts.tsx @@ -21,7 +21,7 @@ import { PromptFooter } from './prompt_footer'; import { FLEET_ASSETS_TO_IGNORE } from '../../../../data/common'; const removeAliases = (item: MatchedItem) => - !((item as unknown) as ResolveIndexResponseItemAlias).indices; + !(item as unknown as ResolveIndexResponseItemAlias).indices; interface Props { onCancel: () => void; diff --git a/src/plugins/index_pattern_editor/public/components/index_pattern_editor.tsx b/src/plugins/index_pattern_editor/public/components/index_pattern_editor.tsx index bc0b6156a784..cbf6e4bdf730 100644 --- a/src/plugins/index_pattern_editor/public/components/index_pattern_editor.tsx +++ b/src/plugins/index_pattern_editor/public/components/index_pattern_editor.tsx @@ -24,9 +24,8 @@ export const IndexPatternEditor = ({ defaultTypeIsRollup = false, requireTimestampField = false, }: IndexPatternEditorPropsWithServices) => { - const { - Provider: KibanaReactContextProvider, - } = createKibanaReactContext(services); + const { Provider: KibanaReactContextProvider } = + createKibanaReactContext(services); return ( diff --git a/src/plugins/index_pattern_editor/public/components/index_pattern_editor_flyout_content.tsx b/src/plugins/index_pattern_editor/public/components/index_pattern_editor_flyout_content.tsx index c4d8ed11fe7c..707a0cedd39c 100644 --- a/src/plugins/index_pattern_editor/public/components/index_pattern_editor_flyout_content.tsx +++ b/src/plugins/index_pattern_editor/public/components/index_pattern_editor_flyout_content.tsx @@ -126,10 +126,8 @@ const IndexPatternEditorFlyoutContentComponent = ({ const [isLoadingIndexPatterns, setIsLoadingIndexPatterns] = useState(true); const [existingIndexPatterns, setExistingIndexPatterns] = useState([]); const [rollupIndex, setRollupIndex] = useState(); - const [ - rollupIndicesCapabilities, - setRollupIndicesCapabilities, - ] = useState({}); + const [rollupIndicesCapabilities, setRollupIndicesCapabilities] = + useState({}); const [matchedIndices, setMatchedIndices] = useState({ allIndices: [], exactMatchedIndices: [], diff --git a/src/plugins/index_pattern_editor/public/components/preview_panel/indices_list/indices_list.test.tsx b/src/plugins/index_pattern_editor/public/components/preview_panel/indices_list/indices_list.test.tsx index 6d40861cb4e0..c26ff17b2d8f 100644 --- a/src/plugins/index_pattern_editor/public/components/preview_panel/indices_list/indices_list.test.tsx +++ b/src/plugins/index_pattern_editor/public/components/preview_panel/indices_list/indices_list.test.tsx @@ -11,10 +11,10 @@ import { IndicesList } from '../indices_list'; import { shallow } from 'enzyme'; import { MatchedItem } from '../../../types'; -const indices = ([ +const indices = [ { name: 'kibana', tags: [] }, { name: 'es', tags: [] }, -] as unknown) as MatchedItem[]; +] as unknown as MatchedItem[]; describe('IndicesList', () => { it('should render normally', () => { diff --git a/src/plugins/index_pattern_editor/public/components/preview_panel/status_message/status_message.test.tsx b/src/plugins/index_pattern_editor/public/components/preview_panel/status_message/status_message.test.tsx index 1bae9bdf3c66..c92a653c8c17 100644 --- a/src/plugins/index_pattern_editor/public/components/preview_panel/status_message/status_message.test.tsx +++ b/src/plugins/index_pattern_editor/public/components/preview_panel/status_message/status_message.test.tsx @@ -16,12 +16,12 @@ const tagsPartial = { }; const matchedIndices = { - allIndices: ([ + allIndices: [ { name: 'kibana', ...tagsPartial }, { name: 'es', ...tagsPartial }, - ] as unknown) as MatchedItem[], + ] as unknown as MatchedItem[], exactMatchedIndices: [] as MatchedItem[], - partialMatchedIndices: ([{ name: 'kibana', ...tagsPartial }] as unknown) as MatchedItem[], + partialMatchedIndices: [{ name: 'kibana', ...tagsPartial }] as unknown as MatchedItem[], visibleIndices: [], }; @@ -42,7 +42,7 @@ describe('StatusMessage', () => { it('should render with exact matches', () => { const localMatchedIndices = { ...matchedIndices, - exactMatchedIndices: ([{ name: 'kibana', ...tagsPartial }] as unknown) as MatchedItem[], + exactMatchedIndices: [{ name: 'kibana', ...tagsPartial }] as unknown as MatchedItem[], }; const component = shallow( diff --git a/src/plugins/index_pattern_editor/public/lib/get_indices.ts b/src/plugins/index_pattern_editor/public/lib/get_indices.ts index 8d642174232a..de93e2c17793 100644 --- a/src/plugins/index_pattern_editor/public/lib/get_indices.ts +++ b/src/plugins/index_pattern_editor/public/lib/get_indices.ts @@ -49,35 +49,34 @@ const getIndexTags = (isRollupIndex: (indexName: string) => boolean) => (indexNa ] : []; -export const searchResponseToArray = ( - getTags: (indexName: string) => Tag[], - showAllIndices: boolean -) => (response: IEsSearchResponse) => { - const { rawResponse } = response; - if (!rawResponse.aggregations) { - return []; - } else { - // @ts-expect-error @elastic/elasticsearch no way to declare a type for aggregation in the search response - return rawResponse.aggregations.indices.buckets - .map((bucket: { key: string }) => { - return bucket.key; - }) - .filter((indexName: string) => { - if (showAllIndices) { - return true; - } else { - return !indexName.startsWith('.'); - } - }) - .map((indexName: string) => { - return { - name: indexName, - tags: getTags(indexName), - item: {}, - }; - }); - } -}; +export const searchResponseToArray = + (getTags: (indexName: string) => Tag[], showAllIndices: boolean) => + (response: IEsSearchResponse) => { + const { rawResponse } = response; + if (!rawResponse.aggregations) { + return []; + } else { + // @ts-expect-error @elastic/elasticsearch no way to declare a type for aggregation in the search response + return rawResponse.aggregations.indices.buckets + .map((bucket: { key: string }) => { + return bucket.key; + }) + .filter((indexName: string) => { + if (showAllIndices) { + return true; + } else { + return !indexName.startsWith('.'); + } + }) + .map((indexName: string) => { + return { + name: indexName, + tags: getTags(indexName), + item: {}, + }; + }); + } + }; export const getIndicesViaSearch = async ({ pattern, diff --git a/src/plugins/index_pattern_editor/public/lib/get_matched_indices.test.ts b/src/plugins/index_pattern_editor/public/lib/get_matched_indices.test.ts index bb762e78cc89..b584532c61b5 100644 --- a/src/plugins/index_pattern_editor/public/lib/get_matched_indices.test.ts +++ b/src/plugins/index_pattern_editor/public/lib/get_matched_indices.test.ts @@ -36,12 +36,8 @@ const exactIndices = [ describe('getMatchedIndices', () => { it('should return all indices', () => { - const { - allIndices, - exactMatchedIndices, - partialMatchedIndices, - visibleIndices, - } = getMatchedIndices(indices, partialIndices, exactIndices, true); + const { allIndices, exactMatchedIndices, partialMatchedIndices, visibleIndices } = + getMatchedIndices(indices, partialIndices, exactIndices, true); expect(allIndices).toEqual([ { name: 'kibana', tags }, @@ -70,12 +66,8 @@ describe('getMatchedIndices', () => { }); it('should return all indices except for system indices', () => { - const { - allIndices, - exactMatchedIndices, - partialMatchedIndices, - visibleIndices, - } = getMatchedIndices(indices, partialIndices, exactIndices, false); + const { allIndices, exactMatchedIndices, partialMatchedIndices, visibleIndices } = + getMatchedIndices(indices, partialIndices, exactIndices, false); expect(allIndices).toEqual([ { name: 'kibana', tags }, diff --git a/src/plugins/index_pattern_editor/public/open_editor.tsx b/src/plugins/index_pattern_editor/public/open_editor.tsx index afeaff11f740..290af83c94fe 100644 --- a/src/plugins/index_pattern_editor/public/open_editor.tsx +++ b/src/plugins/index_pattern_editor/public/open_editor.tsx @@ -26,69 +26,68 @@ interface Dependencies { searchClient: DataPublicPluginStart['search']['search']; } -export const getEditorOpener = ({ core, indexPatternService, searchClient }: Dependencies) => ( - options: IndexPatternEditorProps -): CloseEditor => { - const { uiSettings, overlays, docLinks, notifications, http, application } = core; - const { - Provider: KibanaReactContextProvider, - } = createKibanaReactContext({ - uiSettings, - docLinks, - http, - notifications, - application, - indexPatternService, - searchClient, - }); +export const getEditorOpener = + ({ core, indexPatternService, searchClient }: Dependencies) => + (options: IndexPatternEditorProps): CloseEditor => { + const { uiSettings, overlays, docLinks, notifications, http, application } = core; + const { Provider: KibanaReactContextProvider } = + createKibanaReactContext({ + uiSettings, + docLinks, + http, + notifications, + application, + indexPatternService, + searchClient, + }); - let overlayRef: OverlayRef | null = null; + let overlayRef: OverlayRef | null = null; - const openEditor = ({ - onSave, - onCancel = () => {}, - defaultTypeIsRollup = false, - requireTimestampField = false, - }: IndexPatternEditorProps): CloseEditor => { - const closeEditor = () => { - if (overlayRef) { - overlayRef.close(); - overlayRef = null; - } - }; + const openEditor = ({ + onSave, + onCancel = () => {}, + defaultTypeIsRollup = false, + requireTimestampField = false, + }: IndexPatternEditorProps): CloseEditor => { + const closeEditor = () => { + if (overlayRef) { + overlayRef.close(); + overlayRef = null; + } + }; - const onSaveIndexPattern = (indexPattern: IndexPattern) => { - closeEditor(); + const onSaveIndexPattern = (indexPattern: IndexPattern) => { + closeEditor(); - if (onSave) { - onSave(indexPattern); - } - }; + if (onSave) { + onSave(indexPattern); + } + }; - overlayRef = overlays.openFlyout( - toMountPoint( - - - { - closeEditor(); - onCancel(); - }} - defaultTypeIsRollup={defaultTypeIsRollup} - requireTimestampField={requireTimestampField} - /> - - - ), - { - hideCloseButton: true, - size: 'l', - } - ); + overlayRef = overlays.openFlyout( + toMountPoint( + + + { + closeEditor(); + onCancel(); + }} + defaultTypeIsRollup={defaultTypeIsRollup} + requireTimestampField={requireTimestampField} + /> + + + ), + { + hideCloseButton: true, + size: 'l', + } + ); - return closeEditor; - }; + return closeEditor; + }; - return openEditor(options); -}; + return openEditor(options); + }; diff --git a/src/plugins/index_pattern_editor/public/plugin.tsx b/src/plugins/index_pattern_editor/public/plugin.tsx index 246386c5800e..f31abd76d7f5 100644 --- a/src/plugins/index_pattern_editor/public/plugin.tsx +++ b/src/plugins/index_pattern_editor/public/plugin.tsx @@ -20,7 +20,8 @@ import { getEditorOpener } from './open_editor'; import { IndexPatternEditor } from './components/index_pattern_editor'; export class IndexPatternEditorPlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, plugins: SetupPlugins): PluginSetup { return {}; } diff --git a/src/plugins/index_pattern_field_editor/__jest__/client_integration/helpers/setup_environment.tsx b/src/plugins/index_pattern_field_editor/__jest__/client_integration/helpers/setup_environment.tsx index d87b49d35c68..a996a4ae512b 100644 --- a/src/plugins/index_pattern_field_editor/__jest__/client_integration/helpers/setup_environment.tsx +++ b/src/plugins/index_pattern_field_editor/__jest__/client_integration/helpers/setup_environment.tsx @@ -59,64 +59,66 @@ export const fieldFormatsOptions = [{ id: 'upper', title: 'UpperCaseString' } as export const indexPatternNameForTest = 'testIndexPattern'; -export const WithFieldEditorDependencies = ( - Comp: FunctionComponent, - overridingDependencies?: Partial -) => (props: T) => { - // Setup mocks - (fieldFormats.getByFieldType as jest.MockedFunction< - typeof fieldFormats['getByFieldType'] - >).mockReturnValue(fieldFormatsOptions); - - (fieldFormats.getDefaultType as jest.MockedFunction< - typeof fieldFormats['getDefaultType'] - >).mockReturnValue({ id: 'testDefaultFormat', title: 'TestDefaultFormat' } as any); - - (fieldFormats.getInstance as jest.MockedFunction< - typeof fieldFormats['getInstance'] - >).mockImplementation((id: string) => { - if (id === 'upper') { - return { - convertObject: { - html(value: string = '') { - return `${value.toUpperCase()}`; +export const WithFieldEditorDependencies = + ( + Comp: FunctionComponent, + overridingDependencies?: Partial + ) => + (props: T) => { + // Setup mocks + ( + fieldFormats.getByFieldType as jest.MockedFunction + ).mockReturnValue(fieldFormatsOptions); + + ( + fieldFormats.getDefaultType as jest.MockedFunction + ).mockReturnValue({ id: 'testDefaultFormat', title: 'TestDefaultFormat' } as any); + + ( + fieldFormats.getInstance as jest.MockedFunction + ).mockImplementation((id: string) => { + if (id === 'upper') { + return { + convertObject: { + html(value: string = '') { + return `${value.toUpperCase()}`; + }, }, - }, - } as any; - } - }); - - const dependencies: Context = { - indexPattern: { - title: indexPatternNameForTest, - fields: { getAll: spyIndexPatternGetAllFields }, - } as any, - uiSettings: uiSettingsServiceMock.createStartContract(), - fieldTypeToProcess: 'runtime', - existingConcreteFields: [], - namesNotAllowed: [], - links: { - runtimePainless: 'https://elastic.co', - }, - services: { - notifications: notificationServiceMock.createStartContract(), - search, - api: apiService, - }, - fieldFormatEditors: { - getAll: () => [], - getById: () => undefined, - }, - fieldFormats, + } as any; + } + }); + + const dependencies: Context = { + indexPattern: { + title: indexPatternNameForTest, + fields: { getAll: spyIndexPatternGetAllFields }, + } as any, + uiSettings: uiSettingsServiceMock.createStartContract(), + fieldTypeToProcess: 'runtime', + existingConcreteFields: [], + namesNotAllowed: [], + links: { + runtimePainless: 'https://elastic.co', + }, + services: { + notifications: notificationServiceMock.createStartContract(), + search, + api: apiService, + }, + fieldFormatEditors: { + getAll: () => [], + getById: () => undefined, + }, + fieldFormats, + }; + + const mergedDependencies = merge({}, dependencies, overridingDependencies); + + return ( + + + + + + ); }; - - const mergedDependencies = merge({}, dependencies, overridingDependencies); - - return ( - - - - - - ); -}; diff --git a/src/plugins/index_pattern_field_editor/public/components/field_editor/field_editor.tsx b/src/plugins/index_pattern_field_editor/public/components/field_editor/field_editor.tsx index b46d587dc414..11183d575e95 100644 --- a/src/plugins/index_pattern_field_editor/public/components/field_editor/field_editor.tsx +++ b/src/plugins/index_pattern_field_editor/public/components/field_editor/field_editor.tsx @@ -151,12 +151,8 @@ const formSerializer = (field: FieldFormInternal): Field => { }; const FieldEditorComponent = ({ field, onChange, onFormModifiedChange, syntaxError }: Props) => { - const { - links, - namesNotAllowed, - existingConcreteFields, - fieldTypeToProcess, - } = useFieldEditorContext(); + const { links, namesNotAllowed, existingConcreteFields, fieldTypeToProcess } = + useFieldEditorContext(); const { params: { update: updatePreviewParams }, panel: { setIsVisible: setIsPanelVisible }, diff --git a/src/plugins/index_pattern_field_editor/public/components/field_editor/lib.ts b/src/plugins/index_pattern_field_editor/public/components/field_editor/lib.ts index ba44682ba65e..5b2e66c66fe3 100644 --- a/src/plugins/index_pattern_field_editor/public/components/field_editor/lib.ts +++ b/src/plugins/index_pattern_field_editor/public/components/field_editor/lib.ts @@ -13,20 +13,20 @@ import { Field } from '../../types'; import { schema } from './form_schema'; import type { Props } from './field_editor'; -const createNameNotAllowedValidator = ( - namesNotAllowed: string[] -): ValidationFunc<{}, string, string> => ({ value }) => { - if (namesNotAllowed.includes(value)) { - return { - message: i18n.translate( - 'indexPatternFieldEditor.editor.runtimeFieldsEditor.existRuntimeFieldNamesValidationErrorMessage', - { - defaultMessage: 'A field with this name already exists.', - } - ), - }; - } -}; +const createNameNotAllowedValidator = + (namesNotAllowed: string[]): ValidationFunc<{}, string, string> => + ({ value }) => { + if (namesNotAllowed.includes(value)) { + return { + message: i18n.translate( + 'indexPatternFieldEditor.editor.runtimeFieldsEditor.existRuntimeFieldNamesValidationErrorMessage', + { + defaultMessage: 'A field with this name already exists.', + } + ), + }; + } + }; /** * Dynamically retrieve the config for the "name" field, adding diff --git a/src/plugins/index_pattern_field_editor/public/components/field_editor_flyout_content_container.tsx b/src/plugins/index_pattern_field_editor/public/components/field_editor_flyout_content_container.tsx index cf2b29bbc97e..ea981662c1ff 100644 --- a/src/plugins/index_pattern_field_editor/public/components/field_editor_flyout_content_container.tsx +++ b/src/plugins/index_pattern_field_editor/public/components/field_editor_flyout_content_container.tsx @@ -103,10 +103,10 @@ export const FieldEditorFlyoutContentContainer = ({ return existing; }, [fields, field]); - const validateRuntimeField = useMemo(() => getRuntimeFieldValidator(indexPattern.title, search), [ - search, - indexPattern, - ]); + const validateRuntimeField = useMemo( + () => getRuntimeFieldValidator(indexPattern.title, search), + [search, indexPattern] + ); const services = useMemo( () => ({ diff --git a/src/plugins/index_pattern_field_editor/public/components/field_format_editor/editors/bytes/bytes.test.tsx b/src/plugins/index_pattern_field_editor/public/components/field_format_editor/editors/bytes/bytes.test.tsx index 219a51e421b4..afca37bd6f21 100644 --- a/src/plugins/index_pattern_field_editor/public/components/field_format_editor/editors/bytes/bytes.test.tsx +++ b/src/plugins/index_pattern_field_editor/public/components/field_format_editor/editors/bytes/bytes.test.tsx @@ -51,7 +51,7 @@ describe('BytesFormatEditor', () => { const component = shallow( { const component = shallowWithI18nProvider( { const component = shallowWithI18nProvider( { const component = shallowWithI18nProvider( { const component = shallow( { const component = shallow( { const component = shallow( { const component = shallow( { shallow( { const component = shallow( { const component = shallow( { const component = shallow( (input: number | Record) => - typeof input === 'number' ? input.toFixed(2) : JSON.stringify(input) + .mockImplementation( + () => (input: number | Record) => + typeof input === 'number' ? input.toFixed(2) : JSON.stringify(input) ), getParamDefaults: jest.fn().mockImplementation(() => { return { id: 'number', params: {} }; @@ -40,7 +41,7 @@ describe('HistogramFormatEditor', () => { const component = shallow( { const component = shallow( { const component = shallow( { const component = shallowWithI18nProvider( { const component = shallowWithI18nProvider( { const component = shallow( { const component = shallow( { const component = shallow( { }, }; - await input!.invoke('onChange')!((changeEvent as unknown) as ChangeEvent); + await input!.invoke('onChange')!(changeEvent as unknown as ChangeEvent); expect(onError).toBeCalledWith(changeEvent.target.validationMessage); expect(onChange).not.toBeCalled(); @@ -79,7 +79,7 @@ describe('TruncateFormatEditor', () => { const component = shallow( { }, }; onError.mockClear(); - await input!.invoke('onChange')!((changeEvent as unknown) as ChangeEvent); + await input!.invoke('onChange')!(changeEvent as unknown as ChangeEvent); expect(onError).not.toBeCalled(); expect(onChange).toBeCalledWith({ fieldLength: 123 }); }); diff --git a/src/plugins/index_pattern_field_editor/public/components/field_format_editor/editors/url/url.test.tsx b/src/plugins/index_pattern_field_editor/public/components/field_format_editor/editors/url/url.test.tsx index 79dc63230dc3..48d3a5dfea7c 100644 --- a/src/plugins/index_pattern_field_editor/public/components/field_format_editor/editors/url/url.test.tsx +++ b/src/plugins/index_pattern_field_editor/public/components/field_format_editor/editors/url/url.test.tsx @@ -22,7 +22,7 @@ jest.mock('@elastic/eui/lib/services/accessibility', () => { }); const fieldType = 'string'; -const format = ({ +const format = { getConverterFor: jest .fn() .mockImplementation(() => (input: string) => `converted url for ${input}`), @@ -33,7 +33,7 @@ const format = ({ { kind: 'audio', text: 'Audio' }, ], }, -} as unknown) as FieldFormat; +} as unknown as FieldFormat; const formatParams = { openLinkInCurrentTab: true, urlTemplate: '', diff --git a/src/plugins/index_pattern_field_editor/public/components/flyout_panels/flyout_panel.tsx b/src/plugins/index_pattern_field_editor/public/components/flyout_panels/flyout_panel.tsx index 05f127c09c99..fcd09ce6a38d 100644 --- a/src/plugins/index_pattern_field_editor/public/components/flyout_panels/flyout_panel.tsx +++ b/src/plugins/index_pattern_field_editor/public/components/flyout_panels/flyout_panel.tsx @@ -91,10 +91,10 @@ export const Panel: React.FC> = ({ }); }, []); - const ctx = useMemo(() => ({ registerContent, registerFooter }), [ - registerFooter, - registerContent, - ]); + const ctx = useMemo( + () => ({ registerContent, registerFooter }), + [registerFooter, registerContent] + ); useLayoutEffect(() => { const { removePanel, isFixedWidth } = addPanel({ width }); diff --git a/src/plugins/index_pattern_field_editor/public/components/preview/field_preview_context.tsx b/src/plugins/index_pattern_field_editor/public/components/preview/field_preview_context.tsx index e1fc4b05883f..e49e0ef6885d 100644 --- a/src/plugins/index_pattern_field_editor/public/components/preview/field_preview_context.tsx +++ b/src/plugins/index_pattern_field_editor/public/components/preview/field_preview_context.tsx @@ -159,10 +159,10 @@ export const FieldPreviewProvider: FunctionComponent = ({ children }) => { const [pinnedFields, setPinnedFields] = useState<{ [key: string]: boolean }>({}); const { documents, currentIdx } = clusterData; - const currentDocument: EsDocument | undefined = useMemo(() => documents[currentIdx], [ - documents, - currentIdx, - ]); + const currentDocument: EsDocument | undefined = useMemo( + () => documents[currentIdx], + [documents, currentIdx] + ); const currentDocIndex = currentDocument?._index; const currentDocId: string = currentDocument?._id ?? ''; @@ -180,9 +180,9 @@ export const FieldPreviewProvider: FunctionComponent = ({ children }) => { return false; } - const allParamsDefined = (['type', 'script', 'index', 'document'] as Array< - keyof Params - >).every((key) => Boolean(params[key])); + const allParamsDefined = (['type', 'script', 'index', 'document'] as Array).every( + (key) => Boolean(params[key]) + ); if (!allParamsDefined) { return false; diff --git a/src/plugins/index_pattern_field_editor/public/lib/runtime_field_validation.ts b/src/plugins/index_pattern_field_editor/public/lib/runtime_field_validation.ts index 789c4f7fa71f..5f80b7823b6a 100644 --- a/src/plugins/index_pattern_field_editor/public/lib/runtime_field_validation.ts +++ b/src/plugins/index_pattern_field_editor/public/lib/runtime_field_validation.ts @@ -92,28 +92,27 @@ export const parseEsError = ( * This is a temporary solution. In a future work we will have a dedicate * ES API to debug the script. */ -export const getRuntimeFieldValidator = ( - index: string, - searchService: DataPublicPluginStart['search'] -) => async (runtimeField: EsRuntimeField) => { - return await searchService - .search({ - params: { - index, - body: { - runtime_mappings: { - temp: runtimeField, - }, - size: 0, - query: { - match_none: {}, +export const getRuntimeFieldValidator = + (index: string, searchService: DataPublicPluginStart['search']) => + async (runtimeField: EsRuntimeField) => { + return await searchService + .search({ + params: { + index, + body: { + runtime_mappings: { + temp: runtimeField, + }, + size: 0, + query: { + match_none: {}, + }, }, }, - }, - }) - .toPromise() - .then(() => null) - .catch((e) => { - return parseEsError(e.attributes); - }); -}; + }) + .toPromise() + .then(() => null) + .catch((e) => { + return parseEsError(e.attributes); + }); + }; diff --git a/src/plugins/index_pattern_field_editor/public/open_delete_modal.tsx b/src/plugins/index_pattern_field_editor/public/open_delete_modal.tsx index 72dbb7686335..19ed7010ca3e 100644 --- a/src/plugins/index_pattern_field_editor/public/open_delete_modal.tsx +++ b/src/plugins/index_pattern_field_editor/public/open_delete_modal.tsx @@ -35,54 +35,52 @@ interface Dependencies { usageCollection: UsageCollectionStart; } -export const getFieldDeleteModalOpener = ({ - core, - indexPatternService, - usageCollection, -}: Dependencies) => (options: OpenFieldDeleteModalOptions): CloseEditor => { - const { overlays, notifications } = core; +export const getFieldDeleteModalOpener = + ({ core, indexPatternService, usageCollection }: Dependencies) => + (options: OpenFieldDeleteModalOptions): CloseEditor => { + const { overlays, notifications } = core; - let overlayRef: OverlayRef | null = null; + let overlayRef: OverlayRef | null = null; - const openDeleteModal = ({ - onDelete, - fieldName, - ctx: { indexPattern }, - }: OpenFieldDeleteModalOptions): CloseEditor => { - const fieldsToDelete = Array.isArray(fieldName) ? fieldName : [fieldName]; - const closeModal = () => { - if (overlayRef) { - overlayRef.close(); - overlayRef = null; - } - }; + const openDeleteModal = ({ + onDelete, + fieldName, + ctx: { indexPattern }, + }: OpenFieldDeleteModalOptions): CloseEditor => { + const fieldsToDelete = Array.isArray(fieldName) ? fieldName : [fieldName]; + const closeModal = () => { + if (overlayRef) { + overlayRef.close(); + overlayRef = null; + } + }; - const onConfirmDelete = async () => { - closeModal(); + const onConfirmDelete = async () => { + closeModal(); - await removeFields(fieldsToDelete, indexPattern, { - indexPatternService, - usageCollection, - notifications, - }); + await removeFields(fieldsToDelete, indexPattern, { + indexPatternService, + usageCollection, + notifications, + }); - if (onDelete) { - onDelete(fieldsToDelete); - } - }; + if (onDelete) { + onDelete(fieldsToDelete); + } + }; - overlayRef = overlays.openModal( - toMountPoint( - - ) - ); + overlayRef = overlays.openModal( + toMountPoint( + + ) + ); - return closeModal; - }; + return closeModal; + }; - return openDeleteModal(options); -}; + return openDeleteModal(options); + }; diff --git a/src/plugins/index_pattern_field_editor/public/open_editor.tsx b/src/plugins/index_pattern_field_editor/public/open_editor.tsx index 946e666bf820..19b5d1fde831 100644 --- a/src/plugins/index_pattern_field_editor/public/open_editor.tsx +++ b/src/plugins/index_pattern_field_editor/public/open_editor.tsx @@ -43,116 +43,118 @@ interface Dependencies { usageCollection: UsageCollectionStart; } -export const getFieldEditorOpener = ({ - core, - indexPatternService, - fieldFormats, - fieldFormatEditors, - search, - usageCollection, - apiService, -}: Dependencies) => (options: OpenFieldEditorOptions): CloseEditor => { - const { uiSettings, overlays, docLinks, notifications } = core; - const { Provider: KibanaReactContextProvider } = createKibanaReactContext({ - uiSettings, - docLinks, - http: core.http, - }); - - let overlayRef: OverlayRef | null = null; - const canCloseValidator = { - current: () => true, - }; - - const onMounted = (args: { canCloseValidator: () => boolean }) => { - canCloseValidator.current = args.canCloseValidator; - }; - - const openEditor = ({ - onSave, - fieldName, - ctx: { indexPattern }, - }: OpenFieldEditorOptions): CloseEditor => { - const closeEditor = () => { - if (overlayRef) { - overlayRef.close(); - overlayRef = null; - } +export const getFieldEditorOpener = + ({ + core, + indexPatternService, + fieldFormats, + fieldFormatEditors, + search, + usageCollection, + apiService, + }: Dependencies) => + (options: OpenFieldEditorOptions): CloseEditor => { + const { uiSettings, overlays, docLinks, notifications } = core; + const { Provider: KibanaReactContextProvider } = createKibanaReactContext({ + uiSettings, + docLinks, + http: core.http, + }); + + let overlayRef: OverlayRef | null = null; + const canCloseValidator = { + current: () => true, }; - const onSaveField = (updatedField: IndexPatternField) => { - closeEditor(); + const onMounted = (args: { canCloseValidator: () => boolean }) => { + canCloseValidator.current = args.canCloseValidator; + }; - if (onSave) { - onSave(updatedField); + const openEditor = ({ + onSave, + fieldName, + ctx: { indexPattern }, + }: OpenFieldEditorOptions): CloseEditor => { + const closeEditor = () => { + if (overlayRef) { + overlayRef.close(); + overlayRef = null; + } + }; + + const onSaveField = (updatedField: IndexPatternField) => { + closeEditor(); + + if (onSave) { + onSave(updatedField); + } + }; + + const field = fieldName ? indexPattern.getFieldByName(fieldName) : undefined; + + if (fieldName && !field) { + const err = i18n.translate('indexPatternFieldEditor.noSuchFieldName', { + defaultMessage: "Field named '{fieldName}' not found on index pattern", + values: { fieldName }, + }); + notifications.toasts.addDanger(err); + return closeEditor; } - }; - const field = fieldName ? indexPattern.getFieldByName(fieldName) : undefined; + const isNewRuntimeField = !fieldName; + const isExistingRuntimeField = field && field.runtimeField && !field.isMapped; + const fieldTypeToProcess: InternalFieldType = + isNewRuntimeField || isExistingRuntimeField ? 'runtime' : 'concrete'; + + overlayRef = overlays.openFlyout( + toMountPoint( + + + + ), + { + className: euiFlyoutClassname, + maxWidth: 708, + size: 'l', + ownFocus: true, + hideCloseButton: true, + 'aria-label': isNewRuntimeField + ? i18n.translate('indexPatternFieldEditor.createField.flyoutAriaLabel', { + defaultMessage: 'Create field', + }) + : i18n.translate('indexPatternFieldEditor.editField.flyoutAriaLabel', { + defaultMessage: 'Edit {fieldName} field', + values: { + fieldName, + }, + }), + onClose: (flyout) => { + const canClose = canCloseValidator.current(); + if (canClose) { + flyout.close(); + } + }, + } + ); - if (fieldName && !field) { - const err = i18n.translate('indexPatternFieldEditor.noSuchFieldName', { - defaultMessage: "Field named '{fieldName}' not found on index pattern", - values: { fieldName }, - }); - notifications.toasts.addDanger(err); return closeEditor; - } - - const isNewRuntimeField = !fieldName; - const isExistingRuntimeField = field && field.runtimeField && !field.isMapped; - const fieldTypeToProcess: InternalFieldType = - isNewRuntimeField || isExistingRuntimeField ? 'runtime' : 'concrete'; - - overlayRef = overlays.openFlyout( - toMountPoint( - - - - ), - { - className: euiFlyoutClassname, - maxWidth: 708, - size: 'l', - ownFocus: true, - hideCloseButton: true, - 'aria-label': isNewRuntimeField - ? i18n.translate('indexPatternFieldEditor.createField.flyoutAriaLabel', { - defaultMessage: 'Create field', - }) - : i18n.translate('indexPatternFieldEditor.editField.flyoutAriaLabel', { - defaultMessage: 'Edit {fieldName} field', - values: { - fieldName, - }, - }), - onClose: (flyout) => { - const canClose = canCloseValidator.current(); - if (canClose) { - flyout.close(); - } - }, - } - ); + }; - return closeEditor; + return openEditor(options); }; - - return openEditor(options); -}; diff --git a/src/plugins/index_pattern_field_editor/public/plugin.test.tsx b/src/plugins/index_pattern_field_editor/public/plugin.test.tsx index 75bb1322d305..de7a88b4c6d2 100644 --- a/src/plugins/index_pattern_field_editor/public/plugin.test.tsx +++ b/src/plugins/index_pattern_field_editor/public/plugin.test.tsx @@ -112,7 +112,7 @@ describe('IndexPatternFieldEditorPlugin', () => { }; const { openDeleteModal } = await plugin.start(coreStartMocked, pluginStartMocked); - const indexPatternMock = ({ removeRuntimeField: removeFieldSpy } as unknown) as IndexPattern; + const indexPatternMock = { removeRuntimeField: removeFieldSpy } as unknown as IndexPattern; openDeleteModal({ onDelete: onDeleteSpy, diff --git a/src/plugins/index_pattern_field_editor/public/plugin.ts b/src/plugins/index_pattern_field_editor/public/plugin.ts index 4bf8dd5c1c4e..c6d4aab1a95b 100644 --- a/src/plugins/index_pattern_field_editor/public/plugin.ts +++ b/src/plugins/index_pattern_field_editor/public/plugin.ts @@ -16,7 +16,8 @@ import { getFieldDeleteModalOpener } from './open_delete_modal'; import { initApi } from './lib/api'; export class IndexPatternFieldEditorPlugin - implements Plugin { + implements Plugin +{ private readonly formatEditorService = new FormatEditorService(); public setup(core: CoreSetup, plugins: SetupPlugins): PluginSetup { diff --git a/src/plugins/index_pattern_field_editor/server/routes/field_preview.ts b/src/plugins/index_pattern_field_editor/server/routes/field_preview.ts index 238701904e22..11ec1ca7d566 100644 --- a/src/plugins/index_pattern_field_editor/server/routes/field_preview.ts +++ b/src/plugins/index_pattern_field_editor/server/routes/field_preview.ts @@ -54,7 +54,7 @@ export const registerFieldPreviewRoute = ({ router }: RouteDependencies): void = body, }); - const fieldValue = (response.body.result as any[]) as HttpResponsePayload; + const fieldValue = response.body.result as any[] as HttpResponsePayload; return res.ok({ body: { values: fieldValue } }); } catch (error) { diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/create_edit_field/create_edit_field.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/create_edit_field/create_edit_field.tsx index 0c0adc6dd502..5b5c472ad235 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/create_edit_field/create_edit_field.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/create_edit_field/create_edit_field.tsx @@ -34,20 +34,16 @@ const newFieldPlaceholder = i18n.translate( export const CreateEditField = withRouter( ({ indexPattern, mode, fieldName, history }: CreateEditFieldProps) => { - const { - uiSettings, - chrome, - notifications, - data, - } = useKibana().services; + const { uiSettings, chrome, notifications, data } = + useKibana().services; const spec = mode === 'edit' && fieldName ? indexPattern.fields.getByName(fieldName)?.spec - : (({ + : ({ scripted: true, type: 'number', name: undefined, - } as unknown) as IndexPatternField); + } as unknown as IndexPatternField); const url = `/patterns/${indexPattern.id}`; 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 f23696ac6c7d..11961714e9f8 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 @@ -56,12 +56,8 @@ const confirmModalOptionsDelete = { export const EditIndexPattern = withRouter( ({ indexPattern, history, location }: EditIndexPatternProps) => { - const { - uiSettings, - overlays, - chrome, - data, - } = useKibana().services; + const { uiSettings, overlays, chrome, data } = + useKibana().services; const [fields, setFields] = useState(indexPattern.getNonScriptedFields()); const [conflictedFields, setConflictedFields] = useState( indexPattern.fields.getAll().filter((field) => field.type === 'conflict') 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 2f288dc07291..4928e3026d15 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 @@ -33,12 +33,12 @@ const helpers = { getFieldInfo, }; -const indexPattern = ({ +const indexPattern = { getNonScriptedFields: () => fields, getFormatterForFieldNoDefault: () => ({ params: () => ({}) }), -} as unknown) as IndexPattern; +} as unknown as IndexPattern; -const rollupIndexPattern = ({ +const rollupIndexPattern = { type: IndexPatternType.ROLLUP, typeMeta: { params: { @@ -64,12 +64,12 @@ const rollupIndexPattern = ({ }, getNonScriptedFields: () => fields, getFormatterForFieldNoDefault: () => ({ params: () => ({}) }), -} as unknown) as IndexPattern; +} as unknown as IndexPattern; const mockFieldToIndexPatternField = ( spec: Record ) => { - return new IndexPatternField((spec as unknown) as IndexPatternField['spec']); + return new IndexPatternField(spec as unknown as IndexPatternField['spec']); }; const fields = [ diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/header/header.test.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/header/header.test.tsx index 609769690dba..99ffb4ada636 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/header/header.test.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/header/header.test.tsx @@ -22,9 +22,9 @@ describe('Header', () => { const component = mount( , { wrappingComponent: KibanaContextProvider, diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_field_table.test.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_field_table.test.tsx index 75da4dce7436..1f5220aa01c4 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_field_table.test.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_field_table.test.tsx @@ -168,10 +168,10 @@ describe('ScriptedFieldsTable', () => { const component = shallow( , index: number = 0 ) => { - const columns = component.prop>>( - 'columns' - ); + const columns = + component.prop>>('columns'); return { render: columns[index].render as (...args: any) => ReactElement, }; 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 6594d677884c..e6c4edfc13e9 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 @@ -80,11 +80,8 @@ export function Tabs({ location, refreshFields, }: TabsProps) { - const { - uiSettings, - docLinks, - indexPatternFieldEditor, - } = useKibana().services; + const { uiSettings, docLinks, indexPatternFieldEditor } = + useKibana().services; const [fieldFilter, setFieldFilter] = useState(''); const [indexedFieldTypeFilter, setIndexedFieldTypeFilter] = useState(''); const [scriptedFieldLanguageFilter, setScriptedFieldLanguageFilter] = useState(''); @@ -304,15 +301,11 @@ export function Tabs({ const [selectedTabId, setSelectedTabId] = useState(euiTabs[0].id); useEffect(() => { - const { - startSyncingState, - stopSyncingState, - setCurrentTab, - getCurrentTab, - } = createEditIndexPatternPageStateContainer({ - useHashedUrl: uiSettings.get('state:storeInSessionStorage'), - defaultTab: TAB_INDEXED_FIELDS, - }); + const { startSyncingState, stopSyncingState, setCurrentTab, getCurrentTab } = + createEditIndexPatternPageStateContainer({ + useHashedUrl: uiSettings.get('state:storeInSessionStorage'), + defaultTab: TAB_INDEXED_FIELDS, + }); startSyncingState(); setSyncingStateFunc({ diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/utils.test.ts b/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/utils.test.ts index f52fdaf1af63..6bc51c1d67db 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/utils.test.ts +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/utils.test.ts @@ -12,8 +12,8 @@ import { IndexPatternField, IndexPattern } from '../../../../../data/public'; test('getPath() should encode "fieldName"', () => { expect( getPath( - ({ name: 'Memory: Allocated Bytes/sec' } as unknown) as IndexPatternField, - ({ id: 'id' } as unknown) as IndexPattern + { name: 'Memory: Allocated Bytes/sec' } as unknown as IndexPatternField, + { id: 'id' } as unknown as IndexPattern ) ).toMatchInlineSnapshot(`"/patterns/id/field/Memory%3A%20Allocated%20Bytes%2Fsec"`); }); diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/help_flyout.test.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/help_flyout.test.tsx index 79bd2fdf353e..3eeb97351eb3 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/help_flyout.test.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/help_flyout.test.tsx @@ -30,7 +30,7 @@ describe('ScriptingHelpFlyout', () => { isVisible={true} indexPattern={indexPatternMock} lang="painless" - executeScript={((() => {}) as unknown) as ExecuteScript} + executeScript={(() => {}) as unknown as ExecuteScript} onClose={() => {}} /> ); @@ -44,7 +44,7 @@ describe('ScriptingHelpFlyout', () => { isVisible={true} indexPattern={indexPatternMock} lang="painless" - executeScript={((() => {}) as unknown) as ExecuteScript} + executeScript={(() => {}) as unknown as ExecuteScript} onClose={() => {}} /> ); diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/scripting_syntax.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/scripting_syntax.tsx index 47162d59d883..779dc7822379 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/scripting_syntax.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/scripting_syntax.tsx @@ -14,8 +14,8 @@ import { useKibana } from '../../../../../../../plugins/kibana_react/public'; import { IndexPatternManagmentContext } from '../../../../types'; export const ScriptingSyntax = () => { - const docLinksScriptedFields = useKibana().services.docLinks?.links - .scriptedFields; + const docLinksScriptedFields = + useKibana().services.docLinks?.links.scriptedFields; return ( 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 18c749d448da..584662acbe62 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 @@ -97,22 +97,22 @@ describe('FieldEditor', () => { const mockContext = mockManagementPlugin.createIndexPatternManagmentContext(); mockContext.data.fieldFormats.getDefaultType = jest.fn( - () => (({} as unknown) as FieldFormatInstanceType) + () => ({} as unknown as FieldFormatInstanceType) ); mockContext.data.fieldFormats.getByFieldType = jest.fn((fieldType) => { if (fieldType === 'number') { - return [({} as unknown) as FieldFormatInstanceType]; + return [{} as unknown as FieldFormatInstanceType]; } else { return []; } }); beforeEach(() => { - indexPattern = ({ + indexPattern = { fields, getFormatterForField: () => ({ params: () => ({}) }), getFormatterForFieldNoDefault: () => ({ params: () => ({}) }), - } as unknown) as IndexPattern; + } as unknown as IndexPattern; }); it('should render create new scripted field correctly', async () => { @@ -120,7 +120,7 @@ describe('FieldEditor', () => { FieldEditor, { indexPattern, - spec: (field as unknown) as IndexPatternField, + spec: field as unknown as IndexPatternField, services, }, mockContext @@ -137,19 +137,19 @@ describe('FieldEditor', () => { name: 'test', script: 'doc.test.value', }; - fieldList.push((testField as unknown) as IndexPatternField); + fieldList.push(testField as unknown as IndexPatternField); indexPattern.fields.getByName = (name) => { const flds = { [testField.name]: testField, }; - return (flds[name] as unknown) as IndexPatternField; + return flds[name] as unknown as IndexPatternField; }; const component = createComponentWithContext( FieldEditor, { indexPattern, - spec: (testField as unknown) as IndexPatternField, + spec: testField as unknown as IndexPatternField, services, }, mockContext @@ -161,13 +161,13 @@ describe('FieldEditor', () => { }); it('should display and update a custom label correctly', async () => { - let testField = ({ + let testField = { name: 'test', format: new Format(), lang: undefined, type: 'string', customLabel: 'Test', - } as unknown) as IndexPatternField; + } as unknown as IndexPatternField; fieldList.push(testField); indexPattern.fields.getByName = (name) => { const flds = { @@ -179,7 +179,7 @@ describe('FieldEditor', () => { ...indexPattern.fields, ...{ update: (fld) => { - testField = (fld as unknown) as IndexPatternField; + testField = fld as unknown as IndexPatternField; }, add: jest.fn(), }, @@ -191,12 +191,12 @@ describe('FieldEditor', () => { FieldEditor, { indexPattern, - spec: (testField as unknown) as IndexPatternField, + spec: testField as unknown as IndexPatternField, services: { redirectAway: () => {}, - indexPatternService: ({ + indexPatternService: { updateSavedObject: jest.fn(() => Promise.resolve()), - } as unknown) as IndexPatternsService, + } as unknown as IndexPatternsService, }, }, mockContext @@ -221,19 +221,19 @@ describe('FieldEditor', () => { script: 'doc.test.value', lang: 'testlang', }; - fieldList.push((testField as unknown) as IndexPatternField); + fieldList.push(testField as unknown as IndexPatternField); indexPattern.fields.getByName = (name) => { const flds = { [testField.name]: testField, }; - return (flds[name] as unknown) as IndexPatternField; + return flds[name] as unknown as IndexPatternField; }; const component = createComponentWithContext( FieldEditor, { indexPattern, - spec: (testField as unknown) as IndexPatternField, + spec: testField as unknown as IndexPatternField, services, }, mockContext @@ -250,7 +250,7 @@ describe('FieldEditor', () => { FieldEditor, { indexPattern, - spec: (testField as unknown) as IndexPatternField, + spec: testField as unknown as IndexPatternField, services, }, mockContext @@ -275,7 +275,7 @@ describe('FieldEditor', () => { FieldEditor, { indexPattern, - spec: (testField as unknown) as IndexPatternField, + spec: testField as unknown as IndexPatternField, services, }, mockContext diff --git a/src/plugins/index_pattern_management/public/components/utils.test.ts b/src/plugins/index_pattern_management/public/components/utils.test.ts index 6215a8dd15c4..5e36d1bbc907 100644 --- a/src/plugins/index_pattern_management/public/components/utils.test.ts +++ b/src/plugins/index_pattern_management/public/components/utils.test.ts @@ -8,7 +8,7 @@ import { IndexPatternsContract } from 'src/plugins/data/public'; import { getIndexPatterns } from './utils'; -const indexPatternContractMock = ({ +const indexPatternContractMock = { getIdsWithTitle: jest.fn().mockReturnValue( Promise.resolve([ { @@ -22,7 +22,7 @@ const indexPatternContractMock = ({ ]) ), get: jest.fn().mockReturnValue(Promise.resolve({})), -} as unknown) as jest.Mocked; +} as unknown as jest.Mocked; test('getting index patterns', async () => { const indexPatterns = await getIndexPatterns('test', indexPatternContractMock); diff --git a/src/plugins/index_pattern_management/public/mocks.ts b/src/plugins/index_pattern_management/public/mocks.ts index 5bcca1f09029..ec71c5fa3264 100644 --- a/src/plugins/index_pattern_management/public/mocks.ts +++ b/src/plugins/index_pattern_management/public/mocks.ts @@ -71,8 +71,8 @@ const createIndexPatternManagmentContext = (): { indexPatternManagementStart: createStartContract(), setBreadcrumbs: () => {}, fieldFormatEditors: indexPatternFieldEditor.fieldFormatEditors, - IndexPatternEditor: indexPatternEditorPluginMock.createStartContract() - .IndexPatternEditorComponent, + IndexPatternEditor: + indexPatternEditorPluginMock.createStartContract().IndexPatternEditorComponent, }; }; diff --git a/src/plugins/index_pattern_management/public/plugin.ts b/src/plugins/index_pattern_management/public/plugin.ts index 9527a04a6b0e..ac0e794c2c2c 100644 --- a/src/plugins/index_pattern_management/public/plugin.ts +++ b/src/plugins/index_pattern_management/public/plugin.ts @@ -45,7 +45,8 @@ export class IndexPatternManagementPlugin IndexPatternManagementStart, IndexPatternManagementSetupDependencies, IndexPatternManagementStartDependencies - > { + > +{ constructor(initializerContext: PluginInitializerContext) {} public setup( diff --git a/src/plugins/index_pattern_management/public/types.ts b/src/plugins/index_pattern_management/public/types.ts index b2c77fccf90b..7f21f1b82a05 100644 --- a/src/plugins/index_pattern_management/public/types.ts +++ b/src/plugins/index_pattern_management/public/types.ts @@ -38,4 +38,5 @@ export interface IndexPatternManagmentContext { IndexPatternEditor: IndexPatternEditorStart['IndexPatternEditorComponent']; } -export type IndexPatternManagmentContextValue = KibanaReactContextValue; +export type IndexPatternManagmentContextValue = + KibanaReactContextValue; diff --git a/src/plugins/index_pattern_management/server/routes/preview_scripted_field.test.ts b/src/plugins/index_pattern_management/server/routes/preview_scripted_field.test.ts index 1343b20365a4..19e42c856fba 100644 --- a/src/plugins/index_pattern_management/server/routes/preview_scripted_field.test.ts +++ b/src/plugins/index_pattern_management/server/routes/preview_scripted_field.test.ts @@ -42,7 +42,7 @@ describe('preview_scripted_field route', () => { const mockRouter = mockCoreSetup.http.createRouter.mock.results[0].value; const handler = mockRouter.post.mock.calls[0][1]; - await handler((mockContext as unknown) as RequestHandlerContext, mockRequest, mockResponse); + await handler(mockContext as unknown as RequestHandlerContext, mockRequest, mockResponse); expect(mockClient.search.mock.calls[0][0]).toMatchInlineSnapshot(` Object { @@ -98,7 +98,7 @@ describe('preview_scripted_field route', () => { const mockRouter = mockCoreSetup.http.createRouter.mock.results[0].value; const handler = mockRouter.post.mock.calls[0][1]; - await handler((mockContext as unknown) as RequestHandlerContext, mockRequest, mockResponse); + await handler(mockContext as unknown as RequestHandlerContext, mockRequest, mockResponse); expect(mockClient.search.mock.calls[0][0]).toMatchInlineSnapshot(` Object { @@ -152,7 +152,7 @@ describe('preview_scripted_field route', () => { const mockRouter = mockCoreSetup.http.createRouter.mock.results[0].value; const handler = mockRouter.post.mock.calls[0][1]; - await handler((mockContext as unknown) as RequestHandlerContext, mockRequest, mockResponse); + await handler(mockContext as unknown as RequestHandlerContext, mockRequest, mockResponse); expect(mockClient.search).toBeCalled(); expect(mockResponse.customError).toBeCalled(); diff --git a/src/plugins/input_control_vis/public/components/editor/controls_tab.test.tsx b/src/plugins/input_control_vis/public/components/editor/controls_tab.test.tsx index d84ad6b38b24..3257b7dab082 100644 --- a/src/plugins/input_control_vis/public/components/editor/controls_tab.test.tsx +++ b/src/plugins/input_control_vis/public/components/editor/controls_tab.test.tsx @@ -19,9 +19,9 @@ const indexPatternsMock = { let props: ControlsTabProps; beforeEach(() => { - props = ({ + props = { deps: getDepsMock(), - vis: ({ + vis: { API: { indexPatterns: indexPatternsMock, }, @@ -33,7 +33,7 @@ beforeEach(() => { requiresSearch: false, hidden: false, }, - } as unknown) as Vis, + } as unknown as Vis, stateParams: { controls: [ { @@ -65,7 +65,7 @@ beforeEach(() => { }, setValue: jest.fn(), intl: null as any, - } as unknown) as ControlsTabProps; + } as unknown as ControlsTabProps; }); test('renders ControlsTab', () => { diff --git a/src/plugins/input_control_vis/public/components/editor/index.tsx b/src/plugins/input_control_vis/public/components/editor/index.tsx index 876010af7493..f34bdcf7b63e 100644 --- a/src/plugins/input_control_vis/public/components/editor/index.tsx +++ b/src/plugins/input_control_vis/public/components/editor/index.tsx @@ -14,9 +14,9 @@ import { InputControlVisParams } from '../../types'; const ControlsTab = lazy(() => import('./controls_tab')); const OptionsTab = lazy(() => import('./options_tab')); -export const getControlsTab = (deps: InputControlVisDependencies) => ( - props: VisEditorOptionsProps -) => ; +export const getControlsTab = + (deps: InputControlVisDependencies) => (props: VisEditorOptionsProps) => + ; export const OptionsTabLazy = (props: VisEditorOptionsProps) => ( diff --git a/src/plugins/input_control_vis/public/components/editor/options_tab.test.tsx b/src/plugins/input_control_vis/public/components/editor/options_tab.test.tsx index 5d4b1f3a8ef4..8b886134c117 100644 --- a/src/plugins/input_control_vis/public/components/editor/options_tab.test.tsx +++ b/src/plugins/input_control_vis/public/components/editor/options_tab.test.tsx @@ -17,7 +17,7 @@ describe('OptionsTab', () => { let props: OptionsTabProps; beforeEach(() => { - props = ({ + props = { vis: {} as Vis, stateParams: { updateFiltersOnChange: false, @@ -25,7 +25,7 @@ describe('OptionsTab', () => { pinFilters: false, }, setValue: jest.fn(), - } as unknown) as OptionsTabProps; + } as unknown as OptionsTabProps; }); it('should renders OptionsTab', () => { 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 c9f802666dab..14a616e8a0db 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 @@ -36,9 +36,9 @@ describe('PhraseFilterManager', function () { }, }, } as IndexPattern; - const indexPatternsServiceMock = ({ + const indexPatternsServiceMock = { get: jest.fn().mockReturnValue(Promise.resolve(indexPatternMock)), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; const queryFilterMock: QueryFilterManager = {} as QueryFilterManager; let filterManager: PhraseFilterManager; beforeEach(async () => { 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 ced93e6ad319..f524ac2a0d7e 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 @@ -35,9 +35,9 @@ describe('RangeFilterManager', function () { }, }, } as IndexPattern; - const indexPatternsServiceMock = ({ + const indexPatternsServiceMock = { get: jest.fn().mockReturnValue(Promise.resolve(indexPatternMock)), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; const queryFilterMock: QueryFilterManager = {} as QueryFilterManager; let filterManager: RangeFilterManager; beforeEach(async () => { diff --git a/src/plugins/inspector/public/ui/inspector_panel.test.tsx b/src/plugins/inspector/public/ui/inspector_panel.test.tsx index 879cd3d18195..03b71219b1e9 100644 --- a/src/plugins/inspector/public/ui/inspector_panel.test.tsx +++ b/src/plugins/inspector/public/ui/inspector_panel.test.tsx @@ -18,12 +18,12 @@ import { applicationServiceMock } from '../../../../core/public/mocks'; describe('InspectorPanel', () => { let adapters: Adapters; let views: InspectorViewDescription[]; - const dependencies = ({ + const dependencies = { application: applicationServiceMock.createStartContract(), http: {}, share: {}, uiSettings: {}, - } as unknown) as { + } as unknown as { application: ApplicationStart; http: HttpSetup; share: SharePluginStart; diff --git a/src/plugins/kibana_legacy/public/angular/angular_config.tsx b/src/plugins/kibana_legacy/public/angular/angular_config.tsx index 48ee6d2db269..7eebc9000169 100644 --- a/src/plugins/kibana_legacy/public/angular/angular_config.tsx +++ b/src/plugins/kibana_legacy/public/angular/angular_config.tsx @@ -168,149 +168,143 @@ export const $setupXsrfRequestInterceptor = (version: string) => { * active $http requests on each digest loop and expose the count to * the core.loadingCount api */ -const capture$httpLoadingCount = (newPlatform: CoreStart) => ( - $rootScope: IRootScopeService, - $http: IHttpService -) => { - newPlatform.http.addLoadingCountSource( - new Rx.Observable((observer) => { - const unwatch = $rootScope.$watch(() => { - const reqs = $http.pendingRequests || []; - observer.next(reqs.filter((req) => !isSystemApiRequest(req)).length); - }); - - return unwatch; - }) - ); -}; +const capture$httpLoadingCount = + (newPlatform: CoreStart) => ($rootScope: IRootScopeService, $http: IHttpService) => { + newPlatform.http.addLoadingCountSource( + new Rx.Observable((observer) => { + const unwatch = $rootScope.$watch(() => { + const reqs = $http.pendingRequests || []; + observer.next(reqs.filter((req) => !isSystemApiRequest(req)).length); + }); + + return unwatch; + }) + ); + }; /** * integrates with angular to automatically redirect to home if required * capability is not met */ -const $setupUICapabilityRedirect = (newPlatform: CoreStart) => ( - $rootScope: IRootScopeService, - $injector: any -) => { - const isKibanaAppRoute = window.location.pathname.endsWith('/app/kibana'); - // this feature only works within kibana app for now after everything is - // switched to the application service, this can be changed to handle all - // apps. - if (!isKibanaAppRoute) { - return; - } - $rootScope.$on( - '$routeChangeStart', - (event, { $$route: route }: { $$route?: RouteConfiguration } = {}) => { - if (!route || !route.requireUICapability) { - return; - } - - if (!get(newPlatform.application.capabilities, route.requireUICapability)) { - $injector.get('$location').url('/home'); - event.preventDefault(); - } +const $setupUICapabilityRedirect = + (newPlatform: CoreStart) => ($rootScope: IRootScopeService, $injector: any) => { + const isKibanaAppRoute = window.location.pathname.endsWith('/app/kibana'); + // this feature only works within kibana app for now after everything is + // switched to the application service, this can be changed to handle all + // apps. + if (!isKibanaAppRoute) { + return; } - ); -}; + $rootScope.$on( + '$routeChangeStart', + (event, { $$route: route }: { $$route?: RouteConfiguration } = {}) => { + if (!route || !route.requireUICapability) { + return; + } + + if (!get(newPlatform.application.capabilities, route.requireUICapability)) { + $injector.get('$location').url('/home'); + event.preventDefault(); + } + } + ); + }; /** * internal angular run function that will be called when angular bootstraps and * lets us integrate with the angular router so that we can automatically clear * the breadcrumbs if we switch to a Kibana app that does not use breadcrumbs correctly */ -const $setupBreadcrumbsAutoClear = (newPlatform: CoreStart, isLocalAngular: boolean) => ( - $rootScope: IRootScopeService, - $injector: any -) => { - // A flag used to determine if we should automatically - // clear the breadcrumbs between angular route changes. - let breadcrumbSetSinceRouteChange = false; - const $route = $injector.has('$route') ? $injector.get('$route') : {}; - - // reset breadcrumbSetSinceRouteChange any time the breadcrumbs change, even - // if it was done directly through the new platform - newPlatform.chrome.getBreadcrumbs$().subscribe({ - next() { - breadcrumbSetSinceRouteChange = true; - }, - }); +const $setupBreadcrumbsAutoClear = + (newPlatform: CoreStart, isLocalAngular: boolean) => + ($rootScope: IRootScopeService, $injector: any) => { + // A flag used to determine if we should automatically + // clear the breadcrumbs between angular route changes. + let breadcrumbSetSinceRouteChange = false; + const $route = $injector.has('$route') ? $injector.get('$route') : {}; + + // reset breadcrumbSetSinceRouteChange any time the breadcrumbs change, even + // if it was done directly through the new platform + newPlatform.chrome.getBreadcrumbs$().subscribe({ + next() { + breadcrumbSetSinceRouteChange = true; + }, + }); - $rootScope.$on('$routeChangeStart', () => { - breadcrumbSetSinceRouteChange = false; - }); + $rootScope.$on('$routeChangeStart', () => { + breadcrumbSetSinceRouteChange = false; + }); - $rootScope.$on('$routeChangeSuccess', () => { - if (isDummyRoute($route, isLocalAngular)) { - return; - } - const current = $route.current || {}; + $rootScope.$on('$routeChangeSuccess', () => { + if (isDummyRoute($route, isLocalAngular)) { + return; + } + const current = $route.current || {}; - if (breadcrumbSetSinceRouteChange || (current.$$route && current.$$route.redirectTo)) { - return; - } + if (breadcrumbSetSinceRouteChange || (current.$$route && current.$$route.redirectTo)) { + return; + } - const k7BreadcrumbsProvider = current.k7Breadcrumbs; - if (!k7BreadcrumbsProvider) { - newPlatform.chrome.setBreadcrumbs([]); - return; - } + const k7BreadcrumbsProvider = current.k7Breadcrumbs; + if (!k7BreadcrumbsProvider) { + newPlatform.chrome.setBreadcrumbs([]); + return; + } - try { - newPlatform.chrome.setBreadcrumbs($injector.invoke(k7BreadcrumbsProvider)); - } catch (error) { - if (isAngularHttpError(error)) { - error = formatAngularHttpError(error); + try { + newPlatform.chrome.setBreadcrumbs($injector.invoke(k7BreadcrumbsProvider)); + } catch (error) { + if (isAngularHttpError(error)) { + error = formatAngularHttpError(error); + } + newPlatform.fatalErrors.add(error, 'location'); } - newPlatform.fatalErrors.add(error, 'location'); - } - }); -}; + }); + }; /** * internal angular run function that will be called when angular bootstraps and * lets us integrate with the angular router so that we can automatically clear * the badge if we switch to a Kibana app that does not use the badge correctly */ -const $setupBadgeAutoClear = (newPlatform: CoreStart, isLocalAngular: boolean) => ( - $rootScope: IRootScopeService, - $injector: any -) => { - // A flag used to determine if we should automatically - // clear the badge between angular route changes. - let badgeSetSinceRouteChange = false; - const $route = $injector.has('$route') ? $injector.get('$route') : {}; - - $rootScope.$on('$routeChangeStart', () => { - badgeSetSinceRouteChange = false; - }); +const $setupBadgeAutoClear = + (newPlatform: CoreStart, isLocalAngular: boolean) => + ($rootScope: IRootScopeService, $injector: any) => { + // A flag used to determine if we should automatically + // clear the badge between angular route changes. + let badgeSetSinceRouteChange = false; + const $route = $injector.has('$route') ? $injector.get('$route') : {}; + + $rootScope.$on('$routeChangeStart', () => { + badgeSetSinceRouteChange = false; + }); - $rootScope.$on('$routeChangeSuccess', () => { - if (isDummyRoute($route, isLocalAngular)) { - return; - } - const current = $route.current || {}; + $rootScope.$on('$routeChangeSuccess', () => { + if (isDummyRoute($route, isLocalAngular)) { + return; + } + const current = $route.current || {}; - if (badgeSetSinceRouteChange || (current.$$route && current.$$route.redirectTo)) { - return; - } + if (badgeSetSinceRouteChange || (current.$$route && current.$$route.redirectTo)) { + return; + } - const badgeProvider = current.badge; - if (!badgeProvider) { - newPlatform.chrome.setBadge(undefined); - return; - } + const badgeProvider = current.badge; + if (!badgeProvider) { + newPlatform.chrome.setBadge(undefined); + return; + } - try { - newPlatform.chrome.setBadge($injector.invoke(badgeProvider)); - } catch (error) { - if (isAngularHttpError(error)) { - error = formatAngularHttpError(error); + try { + newPlatform.chrome.setBadge($injector.invoke(badgeProvider)); + } catch (error) { + if (isAngularHttpError(error)) { + error = formatAngularHttpError(error); + } + newPlatform.fatalErrors.add(error, 'location'); } - newPlatform.fatalErrors.add(error, 'location'); - } - }); -}; + }); + }; /** * internal angular run function that will be called when angular bootstraps and @@ -318,40 +312,39 @@ const $setupBadgeAutoClear = (newPlatform: CoreStart, isLocalAngular: boolean) = * the helpExtension if we switch to a Kibana app that does not set its own * helpExtension */ -const $setupHelpExtensionAutoClear = (newPlatform: CoreStart, isLocalAngular: boolean) => ( - $rootScope: IRootScopeService, - $injector: any -) => { - /** - * reset helpExtensionSetSinceRouteChange any time the helpExtension changes, even - * if it was done directly through the new platform - */ - let helpExtensionSetSinceRouteChange = false; - newPlatform.chrome.getHelpExtension$().subscribe({ - next() { - helpExtensionSetSinceRouteChange = true; - }, - }); +const $setupHelpExtensionAutoClear = + (newPlatform: CoreStart, isLocalAngular: boolean) => + ($rootScope: IRootScopeService, $injector: any) => { + /** + * reset helpExtensionSetSinceRouteChange any time the helpExtension changes, even + * if it was done directly through the new platform + */ + let helpExtensionSetSinceRouteChange = false; + newPlatform.chrome.getHelpExtension$().subscribe({ + next() { + helpExtensionSetSinceRouteChange = true; + }, + }); - const $route = $injector.has('$route') ? $injector.get('$route') : {}; + const $route = $injector.has('$route') ? $injector.get('$route') : {}; - $rootScope.$on('$routeChangeStart', () => { - if (isDummyRoute($route, isLocalAngular)) { - return; - } - helpExtensionSetSinceRouteChange = false; - }); + $rootScope.$on('$routeChangeStart', () => { + if (isDummyRoute($route, isLocalAngular)) { + return; + } + helpExtensionSetSinceRouteChange = false; + }); - $rootScope.$on('$routeChangeSuccess', () => { - if (isDummyRoute($route, isLocalAngular)) { - return; - } - const current = $route.current || {}; + $rootScope.$on('$routeChangeSuccess', () => { + if (isDummyRoute($route, isLocalAngular)) { + return; + } + const current = $route.current || {}; - if (helpExtensionSetSinceRouteChange || (current.$$route && current.$$route.redirectTo)) { - return; - } + if (helpExtensionSetSinceRouteChange || (current.$$route && current.$$route.redirectTo)) { + return; + } - newPlatform.chrome.setHelpExtension(current.helpExtension); - }); -}; + newPlatform.chrome.setHelpExtension(current.helpExtension); + }); + }; 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 5d7008480e66..afdb7fedef99 100644 --- a/src/plugins/kibana_legacy/public/angular/kbn_top_nav.js +++ b/src/plugins/kibana_legacy/public/angular/kbn_top_nav.js @@ -60,50 +60,52 @@ export function createTopNavDirective() { }; } -export const createTopNavHelper = ({ TopNavMenu }) => (reactDirective) => { - return reactDirective(TopNavMenu, [ - ['config', { watchDepth: 'value' }], - ['setMenuMountPoint', { watchDepth: 'reference' }], - ['disabledButtons', { watchDepth: 'reference' }], - - ['query', { watchDepth: 'reference' }], - ['savedQuery', { watchDepth: 'reference' }], - ['intl', { watchDepth: 'reference' }], - - ['onQuerySubmit', { watchDepth: 'reference' }], - ['onFiltersUpdated', { watchDepth: 'reference' }], - ['onRefreshChange', { watchDepth: 'reference' }], - ['onClearSavedQuery', { watchDepth: 'reference' }], - ['onSaved', { watchDepth: 'reference' }], - ['onSavedQueryUpdated', { watchDepth: 'reference' }], - ['onSavedQueryIdChange', { watchDepth: 'reference' }], - - ['indexPatterns', { watchDepth: 'collection' }], - ['filters', { watchDepth: 'collection' }], - - // All modifiers default to true. - // Set to false to hide subcomponents. - 'showSearchBar', - 'showQueryBar', - 'showQueryInput', - 'showSaveQuery', - 'showDatePicker', - 'showFilterBar', - - 'appName', - 'screenTitle', - 'dateRangeFrom', - 'dateRangeTo', - 'savedQueryId', - 'isRefreshPaused', - 'refreshInterval', - 'disableAutoFocus', - 'showAutoRefreshOnly', - - // temporary flag to use the stateful components - 'useDefaultBehaviors', - ]); -}; +export const createTopNavHelper = + ({ TopNavMenu }) => + (reactDirective) => { + return reactDirective(TopNavMenu, [ + ['config', { watchDepth: 'value' }], + ['setMenuMountPoint', { watchDepth: 'reference' }], + ['disabledButtons', { watchDepth: 'reference' }], + + ['query', { watchDepth: 'reference' }], + ['savedQuery', { watchDepth: 'reference' }], + ['intl', { watchDepth: 'reference' }], + + ['onQuerySubmit', { watchDepth: 'reference' }], + ['onFiltersUpdated', { watchDepth: 'reference' }], + ['onRefreshChange', { watchDepth: 'reference' }], + ['onClearSavedQuery', { watchDepth: 'reference' }], + ['onSaved', { watchDepth: 'reference' }], + ['onSavedQueryUpdated', { watchDepth: 'reference' }], + ['onSavedQueryIdChange', { watchDepth: 'reference' }], + + ['indexPatterns', { watchDepth: 'collection' }], + ['filters', { watchDepth: 'collection' }], + + // All modifiers default to true. + // Set to false to hide subcomponents. + 'showSearchBar', + 'showQueryBar', + 'showQueryInput', + 'showSaveQuery', + 'showDatePicker', + 'showFilterBar', + + 'appName', + 'screenTitle', + 'dateRangeFrom', + 'dateRangeTo', + 'savedQueryId', + 'isRefreshPaused', + 'refreshInterval', + 'disableAutoFocus', + 'showAutoRefreshOnly', + + // temporary flag to use the stateful components + 'useDefaultBehaviors', + ]); + }; let isLoaded = false; diff --git a/src/plugins/kibana_overview/public/plugin.ts b/src/plugins/kibana_overview/public/plugin.ts index 5e27ce0392be..3cb34e11b90d 100644 --- a/src/plugins/kibana_overview/public/plugin.ts +++ b/src/plugins/kibana_overview/public/plugin.ts @@ -34,7 +34,8 @@ export class KibanaOverviewPlugin KibanaOverviewPluginStart, AppPluginSetupDependencies, AppPluginStartDependencies - > { + > +{ public setup( core: CoreSetup, { home, usageCollection }: AppPluginSetupDependencies diff --git a/src/plugins/kibana_react/common/eui_styled_components.tsx b/src/plugins/kibana_react/common/eui_styled_components.tsx index b66f4b3a0a6c..4f680d944b95 100644 --- a/src/plugins/kibana_react/common/eui_styled_components.tsx +++ b/src/plugins/kibana_react/common/eui_styled_components.tsx @@ -51,6 +51,6 @@ const { createGlobalStyle, keyframes, withTheme, -} = (styledComponents as unknown) as ThemedStyledComponentsModule; +} = styledComponents as unknown as ThemedStyledComponentsModule; export { css, euiStyled, EuiThemeProvider, createGlobalStyle, keyframes, withTheme }; diff --git a/src/plugins/kibana_react/public/adapters/react_to_ui_component.ts b/src/plugins/kibana_react/public/adapters/react_to_ui_component.ts index 8936a3775449..038e39a0060f 100644 --- a/src/plugins/kibana_react/public/adapters/react_to_ui_component.ts +++ b/src/plugins/kibana_react/public/adapters/react_to_ui_component.ts @@ -15,24 +15,24 @@ import { UiComponent, UiComponentInstance } from '../../../kibana_utils/public'; * * @param ReactComp A React component. */ -export const reactToUiComponent = ( - ReactComp: ComponentType -): UiComponent => () => { - let lastEl: HTMLElement | undefined; +export const reactToUiComponent = + (ReactComp: ComponentType): UiComponent => + () => { + let lastEl: HTMLElement | undefined; - const render: UiComponentInstance['render'] = (el, props) => { - lastEl = el; - renderReact(h(ReactComp, props), el); - }; + const render: UiComponentInstance['render'] = (el, props) => { + lastEl = el; + renderReact(h(ReactComp, props), el); + }; - const unmount: UiComponentInstance['unmount'] = () => { - if (lastEl) unmountComponentAtNode(lastEl); - }; + const unmount: UiComponentInstance['unmount'] = () => { + if (lastEl) unmountComponentAtNode(lastEl); + }; - const comp: UiComponentInstance = { - render, - unmount, - }; + const comp: UiComponentInstance = { + render, + unmount, + }; - return comp; -}; + return comp; + }; 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 2e0a816f55e8..c85366e4bc4f 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 @@ -12,26 +12,25 @@ import { UiComponent, UiComponentInstance } from '../../../kibana_utils/public'; /** * Transforms `UiComponent` into a React component. */ -export const uiToReactComponent = ( - Comp: UiComponent, - as: string = 'div' -): FC => (props) => { - const ref = useRef(); - const comp = useMemo>(() => Comp(), [Comp]); +export const uiToReactComponent = + (Comp: UiComponent, as: string = 'div'): FC => + (props) => { + const ref = useRef(); + const comp = useMemo>(() => Comp(), [Comp]); - useLayoutEffect(() => { - if (!ref.current) return; - comp.render(ref.current, props); - }); + useLayoutEffect(() => { + if (!ref.current) return; + comp.render(ref.current, props); + }); - useLayoutEffect(() => { - if (!comp.unmount) return; - return () => { - if (comp.unmount) comp.unmount(); - }; - }, [comp]); + useLayoutEffect(() => { + if (!comp.unmount) return; + return () => { + if (comp.unmount) comp.unmount(); + }; + }, [comp]); - return h(as, { - ref, - }); -}; + return h(as, { + ref, + }); + }; diff --git a/src/plugins/kibana_react/public/app_links/click_handler.test.ts b/src/plugins/kibana_react/public/app_links/click_handler.test.ts index 9bb6263f2262..1569203c394d 100644 --- a/src/plugins/kibana_react/public/app_links/click_handler.test.ts +++ b/src/plugins/kibana_react/public/app_links/click_handler.test.ts @@ -33,13 +33,13 @@ const createEvent = ({ defaultPrevented?: boolean; modifierKey?: boolean; }): MouseEvent => { - return ({ + return { target, button, defaultPrevented, ctrlKey: modifierKey, preventDefault: jest.fn(), - } as unknown) as MouseEvent; + } as unknown as MouseEvent; }; describe('createNavigateToUrlClickHandler', () => { diff --git a/src/plugins/kibana_react/public/code_editor/code_editor.stories.tsx b/src/plugins/kibana_react/public/code_editor/code_editor.stories.tsx index 09c46bf7a327..c85e03c433d6 100644 --- a/src/plugins/kibana_react/public/code_editor/code_editor.stories.tsx +++ b/src/plugins/kibana_react/public/code_editor/code_editor.stories.tsx @@ -106,8 +106,7 @@ storiesOf('CodeEditor', module) ), { info: { - text: - 'Custom language example. Language definition taken from [here](https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-custom-languages)', + text: 'Custom language example. Language definition taken from [here](https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-custom-languages)', }, } ) diff --git a/src/plugins/kibana_react/public/context/context.test.tsx b/src/plugins/kibana_react/public/context/context.test.tsx index 4b381722c717..a806f3eb66f7 100644 --- a/src/plugins/kibana_react/public/context/context.test.tsx +++ b/src/plugins/kibana_react/public/context/context.test.tsx @@ -184,19 +184,19 @@ test('notifications wrapper uses the closest notifications service', () => { }; const core1 = { - notifications: ({ + notifications: { toasts: { add: jest.fn(), }, - } as unknown) as CoreStart['notifications'], + } as unknown as CoreStart['notifications'], } as Partial; const core2 = { - notifications: ({ + notifications: { toasts: { add: jest.fn(), }, - } as unknown) as CoreStart['notifications'], + } as unknown as CoreStart['notifications'], } as Partial; ReactDOM.render( @@ -221,19 +221,19 @@ test('overlays wrapper uses available overlays service, higher up in ; const core2 = { - notifications: ({ + notifications: { toasts: { add: jest.fn(), }, - } as unknown) as CoreStart['notifications'], + } as unknown as CoreStart['notifications'], } as Partial; expect(core1.overlays!.openFlyout).toHaveBeenCalledTimes(0); diff --git a/src/plugins/kibana_react/public/context/context.tsx b/src/plugins/kibana_react/public/context/context.tsx index dae0093a6f1c..974bd4e89479 100644 --- a/src/plugins/kibana_react/public/context/context.tsx +++ b/src/plugins/kibana_react/public/context/context.tsx @@ -24,9 +24,7 @@ export const context = createContext>(de export const useKibana = (): KibanaReactContextValue< KibanaServices & Extra > => - useContext( - (context as unknown) as React.Context> - ); + useContext(context as unknown as React.Context>); export const withKibana = }>( type: React.ComponentType @@ -69,7 +67,7 @@ export const createKibanaReactContext = ( return { value, Provider, - Consumer: (context.Consumer as unknown) as React.Consumer>, + Consumer: context.Consumer as unknown as React.Consumer>, }; }; diff --git a/src/plugins/kibana_react/public/exit_full_screen_button/exit_full_screen_button.test.tsx b/src/plugins/kibana_react/public/exit_full_screen_button/exit_full_screen_button.test.tsx index 430eae9f1234..273f0209da99 100644 --- a/src/plugins/kibana_react/public/exit_full_screen_button/exit_full_screen_button.test.tsx +++ b/src/plugins/kibana_react/public/exit_full_screen_button/exit_full_screen_button.test.tsx @@ -13,9 +13,9 @@ import { keys } from '@elastic/eui'; import { mount } from 'enzyme'; import type { ChromeStart } from '../../../../core/public'; -const MockChrome = ({ +const MockChrome = { setIsVisible: () => {}, -} as unknown) as ChromeStart; +} as unknown as ChromeStart; test('is rendered', () => { const component = mount( diff --git a/src/plugins/kibana_react/public/overview_page/overview_page_actions/overview_page_actions.test.tsx b/src/plugins/kibana_react/public/overview_page/overview_page_actions/overview_page_actions.test.tsx index 34abf9439c1c..389cccd08da8 100644 --- a/src/plugins/kibana_react/public/overview_page/overview_page_actions/overview_page_actions.test.tsx +++ b/src/plugins/kibana_react/public/overview_page/overview_page_actions/overview_page_actions.test.tsx @@ -15,9 +15,9 @@ jest.mock('../../app_links', () => ({ afterAll(() => jest.clearAllMocks()); -const applicationStartMock = ({ +const applicationStartMock = { capabilities: { navLinks: { management: true, dev_tools: true } }, -} as unknown) as ApplicationStart; +} as unknown as ApplicationStart; describe('overviewPageActions', () => { test('only add data button', () => { diff --git a/src/plugins/kibana_react/public/overview_page/overview_page_actions/overview_page_actions.tsx b/src/plugins/kibana_react/public/overview_page/overview_page_actions/overview_page_actions.tsx index 5903a51ae317..19a3a0e9a760 100644 --- a/src/plugins/kibana_react/public/overview_page/overview_page_actions/overview_page_actions.tsx +++ b/src/plugins/kibana_react/public/overview_page/overview_page_actions/overview_page_actions.tsx @@ -31,10 +31,8 @@ export const overviewPageActions = ({ showDevToolsLink, showManagementLink, }: Props) => { - const { - management: isManagementEnabled, - dev_tools: isDevToolsEnabled, - } = application.capabilities.navLinks; + const { management: isManagementEnabled, dev_tools: isDevToolsEnabled } = + application.capabilities.navLinks; const actionAddData = ( diff --git a/src/plugins/kibana_react/public/page_template/solution_nav/solution_nav.tsx b/src/plugins/kibana_react/public/page_template/solution_nav/solution_nav.tsx index 2165cb1cc101..0f23e64a73a5 100644 --- a/src/plugins/kibana_react/public/page_template/solution_nav/solution_nav.tsx +++ b/src/plugins/kibana_react/public/page_template/solution_nav/solution_nav.tsx @@ -53,113 +53,107 @@ const setTabIndex = (items: Array>, isHidden: boolean) => /** * A wrapper around EuiSideNav but also creates the appropriate title with optional solution logo */ -export const KibanaPageTemplateSolutionNav: FunctionComponent = ({ - name, - icon, - items, - isOpenOnDesktop = false, - onCollapse, - ...rest -}) => { - // The EuiShowFor and EuiHideFor components are not in sync with the euiBreakpoint() function :( - const isSmallerBreakpoint = useIsWithinBreakpoints(['xs', 's']); - const isMediumBreakpoint = useIsWithinBreakpoints(['m']); - const isLargerBreakpoint = useIsWithinBreakpoints(['l', 'xl']); +export const KibanaPageTemplateSolutionNav: FunctionComponent = + ({ name, icon, items, isOpenOnDesktop = false, onCollapse, ...rest }) => { + // The EuiShowFor and EuiHideFor components are not in sync with the euiBreakpoint() function :( + const isSmallerBreakpoint = useIsWithinBreakpoints(['xs', 's']); + const isMediumBreakpoint = useIsWithinBreakpoints(['m']); + const isLargerBreakpoint = useIsWithinBreakpoints(['l', 'xl']); - // This is used for both the EuiSideNav and EuiFlyout toggling - const [isSideNavOpenOnMobile, setIsSideNavOpenOnMobile] = useState(false); - const toggleOpenOnMobile = () => { - setIsSideNavOpenOnMobile(!isSideNavOpenOnMobile); - }; + // This is used for both the EuiSideNav and EuiFlyout toggling + const [isSideNavOpenOnMobile, setIsSideNavOpenOnMobile] = useState(false); + const toggleOpenOnMobile = () => { + setIsSideNavOpenOnMobile(!isSideNavOpenOnMobile); + }; - const isHidden = isLargerBreakpoint && !isOpenOnDesktop; + const isHidden = isLargerBreakpoint && !isOpenOnDesktop; - /** - * Create the avatar - */ - let solutionAvatar; - if (icon) { - solutionAvatar = ; - } + /** + * Create the avatar + */ + let solutionAvatar; + if (icon) { + solutionAvatar = ; + } - /** - * Create the titles - */ - const titleText = ( - - {solutionAvatar} - {name} - - ); - const mobileTitleText = ( - - ); + /** + * Create the titles + */ + const titleText = ( + + {solutionAvatar} + {name} + + ); + const mobileTitleText = ( + + ); - /** - * Create the side nav component - */ - let sideNav; - if (items) { - const sideNavClasses = classNames('kbnPageTemplateSolutionNav', { - 'kbnPageTemplateSolutionNav--hidden': isHidden, - }); + /** + * Create the side nav component + */ + let sideNav; + if (items) { + const sideNavClasses = classNames('kbnPageTemplateSolutionNav', { + 'kbnPageTemplateSolutionNav--hidden': isHidden, + }); + + sideNav = ( + + {solutionAvatar} + {mobileTitleText} + + } + toggleOpenOnMobile={toggleOpenOnMobile} + isOpenOnMobile={isSideNavOpenOnMobile} + items={setTabIndex(items, isHidden)} + {...rest} + /> + ); + } - sideNav = ( - + {isSmallerBreakpoint && sideNav} + {isMediumBreakpoint && ( - {solutionAvatar} - {mobileTitleText} + {isSideNavOpenOnMobile && ( + setIsSideNavOpenOnMobile(false)} + side="left" + size={248} + closeButtonPosition="outside" + className="kbnPageTemplateSolutionNav__flyout" + > + {sideNav} + + )} + - } - toggleOpenOnMobile={toggleOpenOnMobile} - isOpenOnMobile={isSideNavOpenOnMobile} - items={setTabIndex(items, isHidden)} - {...rest} - /> + )} + {isLargerBreakpoint && ( + + {sideNav} + + + )} + ); - } - - return ( - - {isSmallerBreakpoint && sideNav} - {isMediumBreakpoint && ( - - {isSideNavOpenOnMobile && ( - setIsSideNavOpenOnMobile(false)} - side="left" - size={248} - closeButtonPosition="outside" - className="kbnPageTemplateSolutionNav__flyout" - > - {sideNav} - - )} - - - )} - {isLargerBreakpoint && ( - - {sideNav} - - - )} - - ); -}; + }; diff --git a/src/plugins/kibana_react/public/page_template/solution_nav/solution_nav_avatar.tsx b/src/plugins/kibana_react/public/page_template/solution_nav/solution_nav_avatar.tsx index 135c0d598651..6b286edee0ff 100644 --- a/src/plugins/kibana_react/public/page_template/solution_nav/solution_nav_avatar.tsx +++ b/src/plugins/kibana_react/public/page_template/solution_nav/solution_nav_avatar.tsx @@ -22,25 +22,22 @@ export type KibanaPageTemplateSolutionNavAvatarProps = DistributiveOmit = ({ - className, - size, - ...rest -}) => { - return ( - // @ts-ignore Complains about ExclusiveUnion between `iconSize` and `iconType`, but works fine - - ); -}; +export const KibanaPageTemplateSolutionNavAvatar: FunctionComponent = + ({ className, size, ...rest }) => { + return ( + // @ts-ignore Complains about ExclusiveUnion between `iconSize` and `iconType`, but works fine + + ); + }; diff --git a/src/plugins/kibana_react/public/page_template/solution_nav/solution_nav_collapse_button.tsx b/src/plugins/kibana_react/public/page_template/solution_nav/solution_nav_collapse_button.tsx index 65e36d781f82..f56f720dcd52 100644 --- a/src/plugins/kibana_react/public/page_template/solution_nav/solution_nav_collapse_button.tsx +++ b/src/plugins/kibana_react/public/page_template/solution_nav/solution_nav_collapse_button.tsx @@ -13,46 +13,44 @@ import classNames from 'classnames'; import { EuiButtonIcon, EuiButtonIconPropsForButton } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -export type KibanaPageTemplateSolutionNavCollapseButtonProps = Partial & { - /** - * Boolean state of current collapsed status - */ - isCollapsed: boolean; -}; +export type KibanaPageTemplateSolutionNavCollapseButtonProps = + Partial & { + /** + * Boolean state of current collapsed status + */ + isCollapsed: boolean; + }; /** * Creates the styled icon button for showing/hiding solution nav */ -export const KibanaPageTemplateSolutionNavCollapseButton: FunctionComponent = ({ - className, - isCollapsed, - ...rest -}) => { - const classes = classNames( - 'kbnPageTemplateSolutionNavCollapseButton', - { - 'kbnPageTemplateSolutionNavCollapseButton-isCollapsed': isCollapsed, - }, - className - ); +export const KibanaPageTemplateSolutionNavCollapseButton: FunctionComponent = + ({ className, isCollapsed, ...rest }) => { + const classes = classNames( + 'kbnPageTemplateSolutionNavCollapseButton', + { + 'kbnPageTemplateSolutionNavCollapseButton-isCollapsed': isCollapsed, + }, + className + ); - const collapseLabel = i18n.translate('kibana-react.solutionNav.collapsibleLabel', { - defaultMessage: 'Collapse side navigation', - }); + const collapseLabel = i18n.translate('kibana-react.solutionNav.collapsibleLabel', { + defaultMessage: 'Collapse side navigation', + }); - const openLabel = i18n.translate('kibana-react.solutionNav.openLabel', { - defaultMessage: 'Open side navigation', - }); + const openLabel = i18n.translate('kibana-react.solutionNav.openLabel', { + defaultMessage: 'Open side navigation', + }); - return ( - - ); -}; + return ( + + ); + }; diff --git a/src/plugins/kibana_react/public/react_router_navigate/react_router_navigate.tsx b/src/plugins/kibana_react/public/react_router_navigate/react_router_navigate.tsx index ebfd0e51fbf0..db122d034371 100644 --- a/src/plugins/kibana_react/public/react_router_navigate/react_router_navigate.tsx +++ b/src/plugins/kibana_react/public/react_router_navigate/react_router_navigate.tsx @@ -32,28 +32,26 @@ export const reactRouterNavigate = ( onClick: reactRouterOnClickHandler(history, toLocationObject(to), onClickCallback), }); -export const reactRouterOnClickHandler = ( - history: ScopedHistory | History, - to: string | LocationObject, - onClickCallback?: Function -) => (event: any) => { - if (onClickCallback) { - onClickCallback(event); - } - - if (event.defaultPrevented) { - return; - } - - if (event.target.getAttribute('target')) { - return; - } - - if (isModifiedEvent(event) || !isLeftClickEvent(event)) { - return; - } - - // prevents page reload - event.preventDefault(); - history.push(toLocationObject(to)); -}; +export const reactRouterOnClickHandler = + (history: ScopedHistory | History, to: string | LocationObject, onClickCallback?: Function) => + (event: any) => { + if (onClickCallback) { + onClickCallback(event); + } + + if (event.defaultPrevented) { + return; + } + + if (event.target.getAttribute('target')) { + return; + } + + if (isModifiedEvent(event) || !isLeftClickEvent(event)) { + return; + } + + // prevents page reload + event.preventDefault(); + history.push(toLocationObject(to)); + }; diff --git a/src/plugins/kibana_react/public/ui_settings/use_ui_setting.test.tsx b/src/plugins/kibana_react/public/ui_settings/use_ui_setting.test.tsx index 8117699b95ca..44dea2aa420a 100644 --- a/src/plugins/kibana_react/public/ui_settings/use_ui_setting.test.tsx +++ b/src/plugins/kibana_react/public/ui_settings/use_ui_setting.test.tsx @@ -17,7 +17,7 @@ import { coreMock } from '../../../../core/public/mocks'; import useObservable from 'react-use/lib/useObservable'; jest.mock('react-use/lib/useObservable'); -const useObservableSpy = (useObservable as any) as jest.SpyInstance; +const useObservableSpy = useObservable as any as jest.SpyInstance; useObservableSpy.mockImplementation((observable, def) => def); const mock = (): [KibanaServices, Subject] => { diff --git a/src/plugins/kibana_react/public/ui_settings/use_ui_setting.ts b/src/plugins/kibana_react/public/ui_settings/use_ui_setting.ts index 234fd6de517c..d73b8721c7f4 100644 --- a/src/plugins/kibana_react/public/ui_settings/use_ui_setting.ts +++ b/src/plugins/kibana_react/public/ui_settings/use_ui_setting.ts @@ -51,11 +51,10 @@ export const useUiSetting$ = (key: string, defaultValue?: T): [T, Setter] throw new TypeError('uiSettings service not available in kibana-react context.'); } - const observable$ = useMemo(() => services.uiSettings!.get$(key, defaultValue), [ - key, - defaultValue, - services.uiSettings, - ]); + const observable$ = useMemo( + () => services.uiSettings!.get$(key, defaultValue), + [key, defaultValue, services.uiSettings] + ); const value = useObservable(observable$, services.uiSettings!.get(key, defaultValue)); const set = useCallback((newValue: T) => services.uiSettings!.set(key, newValue), [key]); diff --git a/src/plugins/kibana_usage_collection/server/collectors/application_usage/rollups/daily.ts b/src/plugins/kibana_usage_collection/server/collectors/application_usage/rollups/daily.ts index a7873c7d5dfe..4a0081833608 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/application_usage/rollups/daily.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/application_usage/rollups/daily.ts @@ -46,12 +46,11 @@ export async function rollDailyData( let toCreate: Map; do { toCreate = new Map(); - const { - saved_objects: rawApplicationUsageTransactional, - } = await savedObjectsClient.find({ - type: SAVED_OBJECTS_TRANSACTIONAL_TYPE, - perPage: 1000, // Process 1000 at a time as a compromise of speed and overload - }); + const { saved_objects: rawApplicationUsageTransactional } = + await savedObjectsClient.find({ + type: SAVED_OBJECTS_TRANSACTIONAL_TYPE, + perPage: 1000, // Process 1000 at a time as a compromise of speed and overload + }); for (const doc of rawApplicationUsageTransactional) { const { diff --git a/src/plugins/kibana_usage_collection/server/collectors/cloud/detector/cloud_detector.test.ts b/src/plugins/kibana_usage_collection/server/collectors/cloud/detector/cloud_detector.test.ts index f0b54046565c..f5a94a2a9021 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/cloud/detector/cloud_detector.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/cloud/detector/cloud_detector.test.ts @@ -44,12 +44,12 @@ describe('CloudDetector', () => { }; }, }; - const cloudServices = ([ + const cloudServices = [ cloudService1, cloudService2, cloudService3, cloudService4, - ] as unknown) as CloudService[]; + ] as unknown as CloudService[]; describe('getCloudDetails', () => { it('returns undefined by default', () => { @@ -70,7 +70,7 @@ describe('CloudDetector', () => { }); it('returns null if none match', async () => { - const services = ([cloudService1, cloudService2] as unknown) as CloudService[]; + const services = [cloudService1, cloudService2] as unknown as CloudService[]; const detector1 = new CloudDetector({ cloudServices: services }); await detector1.detectCloudService(); @@ -83,7 +83,7 @@ describe('CloudDetector', () => { // this is already tested above, but this just tests it explicitly it('ignores exceptions from cloud services', async () => { - const services = ([cloudService2] as unknown) as CloudService[]; + const services = [cloudService2] as unknown as CloudService[]; const detector = new CloudDetector({ cloudServices: services }); await detector.detectCloudService(); diff --git a/src/plugins/kibana_usage_collection/server/collectors/config_usage/register_config_usage_collector.test.ts b/src/plugins/kibana_usage_collection/server/collectors/config_usage/register_config_usage_collector.test.ts index bc6f8c956b66..8f78bc962dd2 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/config_usage/register_config_usage_collector.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/config_usage/register_config_usage_collector.test.ts @@ -28,7 +28,7 @@ describe('kibana_config_usage', () => { const collectorFetchContext = createCollectorFetchContextMock(); const coreUsageDataStart = coreUsageDataServiceMock.createStartContract(); - const mockConfigUsage = (Symbol('config usage telemetry') as unknown) as ConfigUsageData; + const mockConfigUsage = Symbol('config usage telemetry') as unknown as ConfigUsageData; coreUsageDataStart.getConfigsUsageData.mockResolvedValue(mockConfigUsage); beforeAll(() => registerConfigUsageCollector(usageCollectionMock, () => coreUsageDataStart)); diff --git a/src/plugins/kibana_usage_collection/server/collectors/core/core_usage_collector.test.ts b/src/plugins/kibana_usage_collection/server/collectors/core/core_usage_collector.test.ts index 5410e491a85f..0bb3b2ff923f 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/core/core_usage_collector.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/core/core_usage_collector.test.ts @@ -28,7 +28,7 @@ describe('telemetry_core', () => { const collectorFetchContext = createCollectorFetchContextMock(); const coreUsageDataStart = coreUsageDataServiceMock.createStartContract(); - const getCoreUsageDataReturnValue = (Symbol('core telemetry') as unknown) as CoreUsageData; + const getCoreUsageDataReturnValue = Symbol('core telemetry') as unknown as CoreUsageData; coreUsageDataStart.getCoreUsageData.mockResolvedValue(getCoreUsageDataReturnValue); beforeAll(() => registerCoreUsageCollector(usageCollectionMock, () => coreUsageDataStart)); diff --git a/src/plugins/kibana_usage_collection/server/collectors/event_loop_delays/event_loop_delays_usage_collector.test.ts b/src/plugins/kibana_usage_collection/server/collectors/event_loop_delays/event_loop_delays_usage_collector.test.ts index 06c51f6afa3a..96d5240c935f 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/event_loop_delays/event_loop_delays_usage_collector.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/event_loop_delays/event_loop_delays_usage_collector.test.ts @@ -55,9 +55,9 @@ describe('registerEventLoopDelaysCollector', () => { }); it('returns objects from event_loop_delays_daily from fetch function', async () => { - const mockFind = jest.fn().mockResolvedValue(({ + const mockFind = jest.fn().mockResolvedValue({ saved_objects: [{ attributes: { test: 1 } }], - } as unknown) as SavedObjectsFindResponse); + } as unknown as SavedObjectsFindResponse); mockInternalRepository.find = mockFind; const fetchResult = await collector.fetch(collectorFetchContext); diff --git a/src/plugins/kibana_usage_collection/server/collectors/event_loop_delays/rollups/integration_tests/daily_rollups.test.ts b/src/plugins/kibana_usage_collection/server/collectors/event_loop_delays/rollups/integration_tests/daily_rollups.test.ts index 64668a5f23de..dafd4414db19 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/event_loop_delays/rollups/integration_tests/daily_rollups.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/event_loop_delays/rollups/integration_tests/daily_rollups.test.ts @@ -85,10 +85,8 @@ describe('daily rollups integration test', () => { it('deletes documents older that 3 days from the saved objects repository', async () => { await rollDailyData(logger, internalRepository); - const { - total, - saved_objects: savedObjects, - } = await internalRepository.find({ type: SAVED_OBJECTS_DAILY_TYPE }); + const { total, saved_objects: savedObjects } = + await internalRepository.find({ type: SAVED_OBJECTS_DAILY_TYPE }); expect(total).toBe(rawEventLoopDelaysDaily.length); expect(savedObjects.map(({ id, type, attributes }) => ({ id, type, attributes }))).toEqual( rawEventLoopDelaysDaily diff --git a/src/plugins/kibana_usage_collection/server/collectors/localization/telemetry_localization_collector.test.ts b/src/plugins/kibana_usage_collection/server/collectors/localization/telemetry_localization_collector.test.ts index 0b2650cd5ebb..80605b6caee2 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/localization/telemetry_localization_collector.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/localization/telemetry_localization_collector.test.ts @@ -11,13 +11,13 @@ interface TranslationsMock { } const createI18nLoaderMock = (translations: TranslationsMock) => { - return ({ + return { getTranslationsByLocale() { return { messages: translations, }; }, - } as unknown) as typeof i18nLoader; + } as unknown as typeof i18nLoader; }; import { getTranslationCount } from './telemetry_localization_collector'; diff --git a/src/plugins/kibana_usage_collection/server/collectors/management/telemetry_management_collector.ts b/src/plugins/kibana_usage_collection/server/collectors/management/telemetry_management_collector.ts index 7dd1a4dc4410..3c29824d96f9 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/management/telemetry_management_collector.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/management/telemetry_management_collector.ts @@ -28,7 +28,7 @@ export function createCollectorFetch(getUiSettingsClient: () => IUiSettingsClien return obj; }, {}); // TODO: It would be Partial, but the telemetry-tools for the schema extraction still does not support it. We need to fix it before setting the right Partial type - return (modifiedEntries as unknown) as UsageStats; + return modifiedEntries as unknown as UsageStats; }; } diff --git a/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/kibana_usage_collector.ts b/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/kibana_usage_collector.ts index 13b9d0ca2104..75d5af273777 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/kibana_usage_collector.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/kibana_usage_collector.ts @@ -33,9 +33,9 @@ export async function getKibanaSavedObjectCounts( ): Promise { const buckets = await getSavedObjectsCounts(esClient, kibanaIndex, TYPES); - const allZeros = (Object.fromEntries( + const allZeros = Object.fromEntries( TYPES.map((type) => [snakeCase(type), { total: 0 }]) - ) as unknown) as KibanaSavedObjectCounts; + ) as unknown as KibanaSavedObjectCounts; return buckets.reduce((acc, { key, doc_count: total = 0 }) => { const type = snakeCase(key) as keyof KibanaSavedObjectCounts; diff --git a/src/plugins/kibana_usage_collection/server/collectors/ui_counters/register_ui_counters_collector.ts b/src/plugins/kibana_usage_collection/server/collectors/ui_counters/register_ui_counters_collector.ts index 19190de45d96..12c0a21f5353 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/ui_counters/register_ui_counters_collector.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/ui_counters/register_ui_counters_collector.ts @@ -95,14 +95,13 @@ export function transformRawUsageCounterObject( export const createFetchUiCounters = (stopUsingUiCounterIndicies$: Subject) => async function fetchUiCounters({ soClient }: CollectorFetchContext) { - const { - saved_objects: rawUsageCounters, - } = await soClient.find({ - type: USAGE_COUNTERS_SAVED_OBJECT_TYPE, - fields: ['count', 'counterName', 'counterType', 'domainId'], - filter: `${USAGE_COUNTERS_SAVED_OBJECT_TYPE}.attributes.domainId: uiCounter`, - perPage: 10000, - }); + const { saved_objects: rawUsageCounters } = + await soClient.find({ + type: USAGE_COUNTERS_SAVED_OBJECT_TYPE, + fields: ['count', 'counterName', 'counterType', 'domainId'], + filter: `${USAGE_COUNTERS_SAVED_OBJECT_TYPE}.attributes.domainId: uiCounter`, + perPage: 10000, + }); const skipFetchingUiCounters = stopUsingUiCounterIndicies$.isStopped; const result = 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 31cb869d14e5..cbc848bb5af4 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 @@ -79,8 +79,7 @@ describe('telemetry_ui_metric', () => { }, { ...commonSavedObjectsAttributes, - id: - 'kibana-user_agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:80.0) Gecko/20100101 Firefox/80.0', + id: 'kibana-user_agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:80.0) Gecko/20100101 Firefox/80.0', attributes: { count: 1 }, }, ], diff --git a/src/plugins/kibana_usage_collection/server/collectors/usage_counters/register_usage_counters_collector.ts b/src/plugins/kibana_usage_collection/server/collectors/usage_counters/register_usage_counters_collector.ts index 9c6db00fb359..ad940c825c43 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/usage_counters/register_usage_counters_collector.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/usage_counters/register_usage_counters_collector.ts @@ -86,14 +86,13 @@ export function registerUsageCountersUsageCollector(usageCollection: UsageCollec }, }, fetch: async ({ soClient }: CollectorFetchContext) => { - const { - saved_objects: rawUsageCounters, - } = await soClient.find({ - type: USAGE_COUNTERS_SAVED_OBJECT_TYPE, - fields: ['count', 'counterName', 'counterType', 'domainId'], - filter: `NOT ${USAGE_COUNTERS_SAVED_OBJECT_TYPE}.attributes.domainId: uiCounter`, - perPage: 10000, - }); + const { saved_objects: rawUsageCounters } = + await soClient.find({ + type: USAGE_COUNTERS_SAVED_OBJECT_TYPE, + fields: ['count', 'counterName', 'counterType', 'domainId'], + filter: `NOT ${USAGE_COUNTERS_SAVED_OBJECT_TYPE}.attributes.domainId: uiCounter`, + perPage: 10000, + }); return { dailyEvents: rawUsageCounters.reduce((acc, rawUsageCounter) => { diff --git a/src/plugins/kibana_usage_collection/server/collectors/usage_counters/rollups/rollups.ts b/src/plugins/kibana_usage_collection/server/collectors/usage_counters/rollups/rollups.ts index c07ea37536f2..99bbcee368d1 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/usage_counters/rollups/rollups.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/usage_counters/rollups/rollups.ts @@ -48,12 +48,11 @@ export async function rollUsageCountersIndices( const now = moment(); try { - const { - saved_objects: rawUiCounterDocs, - } = await savedObjectsClient.find({ - type: USAGE_COUNTERS_SAVED_OBJECT_TYPE, - perPage: 1000, // Process 1000 at a time as a compromise of speed and overload - }); + const { saved_objects: rawUiCounterDocs } = + await savedObjectsClient.find({ + type: USAGE_COUNTERS_SAVED_OBJECT_TYPE, + perPage: 1000, // Process 1000 at a time as a compromise of speed and overload + }); const docsToDelete = rawUiCounterDocs.filter((doc) => isSavedObjectOlderThan({ diff --git a/src/plugins/kibana_utils/common/abort_utils.ts b/src/plugins/kibana_utils/common/abort_utils.ts index 051f947b68c1..70f3881acc3d 100644 --- a/src/plugins/kibana_utils/common/abort_utils.ts +++ b/src/plugins/kibana_utils/common/abort_utils.ts @@ -25,9 +25,10 @@ export class AbortError extends Error { * * @param signal The `AbortSignal` to generate the `Promise` from */ -export function abortSignalToPromise( - signal: AbortSignal -): { promise: Promise; cleanup: () => void } { +export function abortSignalToPromise(signal: AbortSignal): { + promise: Promise; + cleanup: () => void; +} { let abortHandler: () => void; const cleanup = () => { if (abortHandler) { diff --git a/src/plugins/kibana_utils/common/persistable_state/migrate_to_latest.test.ts b/src/plugins/kibana_utils/common/persistable_state/migrate_to_latest.test.ts index 2a857b821ace..7f863b603bbf 100644 --- a/src/plugins/kibana_utils/common/persistable_state/migrate_to_latest.test.ts +++ b/src/plugins/kibana_utils/common/persistable_state/migrate_to_latest.test.ts @@ -57,7 +57,7 @@ test('returns the same object if there are no migrations to be applied', () => { test('applies a single migration', () => { const newState = migrateToLatest( { - '0.0.2': (migrationV2 as unknown) as MigrateFunction, + '0.0.2': migrationV2 as unknown as MigrateFunction, }, { state: { name: 'Foo' }, @@ -74,7 +74,7 @@ test('applies a single migration', () => { test('does not apply migration if it has the same version as state', () => { const newState = migrateToLatest( { - '0.0.54': (migrationV2 as unknown) as MigrateFunction, + '0.0.54': migrationV2 as unknown as MigrateFunction, }, { state: { name: 'Foo' }, @@ -90,7 +90,7 @@ test('does not apply migration if it has the same version as state', () => { test('does not apply migration if it has lower version', () => { const newState = migrateToLatest( { - '0.2.2': (migrationV2 as unknown) as MigrateFunction, + '0.2.2': migrationV2 as unknown as MigrateFunction, }, { state: { name: 'Foo' }, @@ -106,8 +106,8 @@ test('does not apply migration if it has lower version', () => { test('applies two migrations consecutively', () => { const newState = migrateToLatest( { - '7.14.0': (migrationV2 as unknown) as MigrateFunction, - '7.14.2': (migrationV3 as unknown) as MigrateFunction, + '7.14.0': migrationV2 as unknown as MigrateFunction, + '7.14.2': migrationV3 as unknown as MigrateFunction, }, { state: { name: 'Foo' }, @@ -126,9 +126,9 @@ test('applies two migrations consecutively', () => { test('applies only migrations which are have higher semver version', () => { const newState = migrateToLatest( { - '7.14.0': (migrationV2 as unknown) as MigrateFunction, // not applied + '7.14.0': migrationV2 as unknown as MigrateFunction, // not applied '7.14.1': (() => ({})) as MigrateFunction, // not applied - '7.14.2': (migrationV3 as unknown) as MigrateFunction, + '7.14.2': migrationV3 as unknown as MigrateFunction, }, { state: { firstName: 'FooBar', lastName: 'Baz' }, 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 37d3ae4ad573..997a3710c58c 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 @@ -182,9 +182,8 @@ describe('hooks', () => { } ); - const { Provider, useState, useTransitions } = createStateContainerReactHelpers< - typeof stateContainer - >(); + const { Provider, useState, useTransitions } = + createStateContainerReactHelpers(); const Demo: React.FC<{}> = () => { const { cnt } = useState(); const { increment } = useTransitions(); diff --git a/src/plugins/kibana_utils/common/state_containers/types.ts b/src/plugins/kibana_utils/common/state_containers/types.ts index 988a28ad3990..16571e341912 100644 --- a/src/plugins/kibana_utils/common/state_containers/types.ts +++ b/src/plugins/kibana_utils/common/state_containers/types.ts @@ -132,16 +132,14 @@ export type Reducer = ( * Utility type for inferring state shape from {@link StateContainer} * @public */ -export type UnboxState< - Container extends StateContainer -> = Container extends StateContainer ? T : never; +export type UnboxState> = + Container extends StateContainer ? T : never; /** * Utility type for inferring transitions type from {@link StateContainer} * @public */ -export type UnboxTransitions< - Container extends StateContainer -> = Container extends StateContainer ? T : never; +export type UnboxTransitions> = + Container extends StateContainer ? T : never; /** * @public diff --git a/src/plugins/kibana_utils/public/state_management/state_encoder/encode_decode_state.ts b/src/plugins/kibana_utils/public/state_management/state_encoder/encode_decode_state.ts index a53bf104228b..3fa11164fad2 100644 --- a/src/plugins/kibana_utils/public/state_management/state_encoder/encode_decode_state.ts +++ b/src/plugins/kibana_utils/public/state_management/state_encoder/encode_decode_state.ts @@ -17,7 +17,7 @@ export function decodeState(expandedOrHashedState: string): State { if (isStateHash(expandedOrHashedState)) { return retrieveState(expandedOrHashedState); } else { - return (rison.decode(expandedOrHashedState) as unknown) as State; + return rison.decode(expandedOrHashedState) as unknown as State; } } @@ -29,7 +29,7 @@ export function encodeState(state: State, useHash: boolean): string { if (useHash) { return persistState(state); } else { - return rison.encode((state as unknown) as RisonValue); + return rison.encode(state as unknown as RisonValue); } } diff --git a/src/plugins/management/common/locator.ts b/src/plugins/management/common/locator.ts index f56b2885be09..bff90cea5d11 100644 --- a/src/plugins/management/common/locator.ts +++ b/src/plugins/management/common/locator.ts @@ -20,7 +20,8 @@ export interface ManagementAppLocatorParams extends SerializableRecord { export type ManagementAppLocator = LocatorPublic; export class ManagementAppLocatorDefinition - implements LocatorDefinition { + implements LocatorDefinition +{ public readonly id = MANAGEMENT_APP_LOCATOR; public readonly getLocation = async (params: ManagementAppLocatorParams) => { diff --git a/src/plugins/management/public/management_sections_service.ts b/src/plugins/management/public/management_sections_service.ts index 9d939df46a5d..219de9b0d8a7 100644 --- a/src/plugins/management/public/management_sections_service.ts +++ b/src/plugins/management/public/management_sections_service.ts @@ -25,10 +25,8 @@ import { } from './types'; import { createGetterSetter } from '../../kibana_utils/public'; -const [ - getSectionsServiceStartPrivate, - setSectionsServiceStartPrivate, -] = createGetterSetter('SectionsServiceStartPrivate'); +const [getSectionsServiceStartPrivate, setSectionsServiceStartPrivate] = + createGetterSetter('SectionsServiceStartPrivate'); export { getSectionsServiceStartPrivate }; diff --git a/src/plugins/management/public/mocks/index.ts b/src/plugins/management/public/mocks/index.ts index 6714e2e0894b..bf9a7ff0b821 100644 --- a/src/plugins/management/public/mocks/index.ts +++ b/src/plugins/management/public/mocks/index.ts @@ -11,25 +11,25 @@ import { ManagementSection } from '../index'; import { sharePluginMock } from '../../../share/public/mocks'; export const createManagementSectionMock = () => - (({ + ({ disable: jest.fn(), enable: jest.fn(), registerApp: jest.fn(), getApp: jest.fn(), getEnabledItems: jest.fn().mockReturnValue([]), - } as unknown) as ManagementSection); + } as unknown as ManagementSection); const createSetupContract = (): ManagementSetup => ({ sections: { register: jest.fn(() => createManagementSectionMock()), - section: ({ + section: { ingest: createManagementSectionMock(), data: createManagementSectionMock(), insightsAndAlerting: createManagementSectionMock(), security: createManagementSectionMock(), kibana: createManagementSectionMock(), stack: createManagementSectionMock(), - } as unknown) as DefinedSections, + } as unknown as DefinedSections, }, locator: { ...sharePluginMock.createLocator(), diff --git a/src/plugins/management/public/plugin.ts b/src/plugins/management/public/plugin.ts index 34719fb5070e..acec140fd652 100644 --- a/src/plugins/management/public/plugin.ts +++ b/src/plugins/management/public/plugin.ts @@ -48,7 +48,8 @@ export class ManagementPlugin ManagementStart, ManagementSetupDependencies, ManagementStartDependencies - > { + > +{ private readonly managementSections = new ManagementSectionsService(); private readonly appUpdater = new BehaviorSubject(() => { diff --git a/src/plugins/management/server/plugin.ts b/src/plugins/management/server/plugin.ts index cc3798d855c5..13471ad73083 100644 --- a/src/plugins/management/server/plugin.ts +++ b/src/plugins/management/server/plugin.ts @@ -21,7 +21,8 @@ export interface ManagementSetup { } export class ManagementServerPlugin - implements Plugin { + implements Plugin +{ private readonly logger: Logger; constructor(initializerContext: PluginInitializerContext) { diff --git a/src/plugins/maps_ems/public/service_settings/service_settings.test.js b/src/plugins/maps_ems/public/service_settings/service_settings.test.js index eb67997c253b..997bf5de599d 100644 --- a/src/plugins/maps_ems/public/service_settings/service_settings.test.js +++ b/src/plugins/maps_ems/public/service_settings/service_settings.test.js @@ -125,8 +125,7 @@ describe('service_settings (FKA tile_map test)', function () { { id: 'road_map', name: 'Road Map - Bright', - url: - 'https://tiles.foobar/raster/styles/osm-bright/{z}/{x}/{y}.png?elastic_tile_service_tos=agree&my_app_name=kibana&my_app_version=1.2.3&license=sspl', + url: 'https://tiles.foobar/raster/styles/osm-bright/{z}/{x}/{y}.png?elastic_tile_service_tos=agree&my_app_name=kibana&my_app_version=1.2.3&license=sspl', minZoom: 0, maxZoom: 10, attribution: diff --git a/src/plugins/navigation/public/plugin.ts b/src/plugins/navigation/public/plugin.ts index 436390c630ea..e9a95312cba9 100644 --- a/src/plugins/navigation/public/plugin.ts +++ b/src/plugins/navigation/public/plugin.ts @@ -15,8 +15,10 @@ import { import { TopNavMenuExtensionsRegistry, createTopNav } from './top_nav_menu'; export class NavigationPublicPlugin - implements Plugin { - private readonly topNavMenuExtensionsRegistry: TopNavMenuExtensionsRegistry = new TopNavMenuExtensionsRegistry(); + implements Plugin +{ + private readonly topNavMenuExtensionsRegistry: TopNavMenuExtensionsRegistry = + new TopNavMenuExtensionsRegistry(); constructor(initializerContext: PluginInitializerContext) {} diff --git a/src/plugins/newsfeed/public/plugin.tsx b/src/plugins/newsfeed/public/plugin.tsx index 656fc2ef00bb..babfb1dbeeb9 100644 --- a/src/plugins/newsfeed/public/plugin.tsx +++ b/src/plugins/newsfeed/public/plugin.tsx @@ -21,7 +21,8 @@ export type NewsfeedPublicPluginSetup = ReturnType; export class NewsfeedPublicPlugin - implements Plugin { + implements Plugin +{ private readonly kibanaVersion: string; private readonly config: NewsfeedPluginBrowserConfig; private readonly stop$ = new Rx.ReplaySubject(1); diff --git a/src/plugins/presentation_util/common/lib/test_helpers/test_styles.ts b/src/plugins/presentation_util/common/lib/test_helpers/test_styles.ts index 99b7ce6c38d2..a2282c8d5cc9 100644 --- a/src/plugins/presentation_util/common/lib/test_helpers/test_styles.ts +++ b/src/plugins/presentation_util/common/lib/test_helpers/test_styles.ts @@ -18,6 +18,5 @@ export const fontStyle = { fontSize: '14px', lineHeight: '21px', }, - css: - 'font-family:Chalkboard, serif;font-weight:bolder;font-style:normal;text-decoration:underline;color:pink;text-align:center;font-size:14px;line-height:21px', + css: 'font-family:Chalkboard, serif;font-weight:bolder;font-style:normal;text-decoration:underline;color:pink;text-align:center;font-size:14px;line-height:21px', }; diff --git a/src/plugins/presentation_util/public/__stories__/wait_for.tsx b/src/plugins/presentation_util/public/__stories__/wait_for.tsx index b6421ec7adf5..7dd8d8514b84 100644 --- a/src/plugins/presentation_util/public/__stories__/wait_for.tsx +++ b/src/plugins/presentation_util/public/__stories__/wait_for.tsx @@ -12,30 +12,29 @@ import { Story } from '@storybook/react'; import { StoryFnReactReturnType } from '@storybook/react/dist/client/preview/types'; import { EuiLoadingSpinner } from '@elastic/eui'; -export const waitFor = ( - waitTarget: Promise, - spinner: ReactElement | null = -) => (CurrentStory: Story) => { - const [storyComponent, setStory] = useState(); - const componentIsMounted = useRef(false); +export const waitFor = + (waitTarget: Promise, spinner: ReactElement | null = ) => + (CurrentStory: Story) => { + const [storyComponent, setStory] = useState(); + const componentIsMounted = useRef(false); - useEffect(() => { - componentIsMounted.current = true; - return () => { - componentIsMounted.current = false; - }; - }, []); + useEffect(() => { + componentIsMounted.current = true; + return () => { + componentIsMounted.current = false; + }; + }, []); - useEffect(() => { - if (!storyComponent) { - waitTarget.then((waitedTarget: any) => { - if (!componentIsMounted.current) return; - act(() => { - setStory(); + useEffect(() => { + if (!storyComponent) { + waitTarget.then((waitedTarget: any) => { + if (!componentIsMounted.current) return; + act(() => { + setStory(); + }); }); - }); - } - }, [CurrentStory, storyComponent]); + } + }, [CurrentStory, storyComponent]); - return storyComponent ?? spinner; -}; + return storyComponent ?? spinner; + }; diff --git a/src/plugins/presentation_util/public/plugin.ts b/src/plugins/presentation_util/public/plugin.ts index 00931c5730fe..f34bd2f1f8af 100644 --- a/src/plugins/presentation_util/public/plugin.ts +++ b/src/plugins/presentation_util/public/plugin.ts @@ -23,7 +23,8 @@ export class PresentationUtilPlugin PresentationUtilPluginStart, PresentationUtilPluginSetupDeps, PresentationUtilPluginStartDeps - > { + > +{ public setup( _coreSetup: CoreSetup, _setupPlugins: PresentationUtilPluginSetupDeps diff --git a/src/plugins/region_map/public/components/index.tsx b/src/plugins/region_map/public/components/index.tsx index 55e26ec311c4..908e1a497bac 100644 --- a/src/plugins/region_map/public/components/index.tsx +++ b/src/plugins/region_map/public/components/index.tsx @@ -13,6 +13,7 @@ import { RegionMapVisParams } from '../region_map_types'; const RegionMapOptions = lazy(() => import('./region_map_options')); -export const createRegionMapOptions = (getServiceSettings: () => Promise) => ( - props: VisEditorOptionsProps -) => ; +export const createRegionMapOptions = + (getServiceSettings: () => Promise) => + (props: VisEditorOptionsProps) => + ; diff --git a/src/plugins/region_map/public/kibana_services.ts b/src/plugins/region_map/public/kibana_services.ts index 030d021006d9..cd79d73e1a7e 100644 --- a/src/plugins/region_map/public/kibana_services.ts +++ b/src/plugins/region_map/public/kibana_services.ts @@ -16,23 +16,19 @@ import { VectorLayer, TmsLayer } from '../../maps_ems/public'; export const [getCoreService, setCoreService] = createGetterSetter('Core'); -export const [getFormatService, setFormatService] = createGetterSetter< - DataPublicPluginStart['fieldFormats'] ->('data.fieldFormats'); +export const [getFormatService, setFormatService] = + createGetterSetter('data.fieldFormats'); -export const [getNotifications, setNotifications] = createGetterSetter( - 'Notifications' -); +export const [getNotifications, setNotifications] = + createGetterSetter('Notifications'); -export const [getQueryService, setQueryService] = createGetterSetter< - DataPublicPluginStart['query'] ->('Query'); +export const [getQueryService, setQueryService] = + createGetterSetter('Query'); export const [getShareService, setShareService] = createGetterSetter('Share'); -export const [getKibanaLegacy, setKibanaLegacy] = createGetterSetter( - 'KibanaLegacy' -); +export const [getKibanaLegacy, setKibanaLegacy] = + createGetterSetter('KibanaLegacy'); export const [getTmsLayers, setTmsLayers] = createGetterSetter('TmsLayers'); 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 c589908ea7a2..758ae14db8e1 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 @@ -53,7 +53,7 @@ describe('SavedObjectsFinder', () => { it('should call saved object client on startup', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [doc] }) ); core.uiSettings.get.mockImplementation(() => 10); @@ -80,7 +80,7 @@ describe('SavedObjectsFinder', () => { it('should list initial items', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [doc] }) ); core.uiSettings.get.mockImplementation(() => 10); @@ -103,7 +103,7 @@ describe('SavedObjectsFinder', () => { it('should call onChoose on item click', async () => { const chooseStub = sinon.stub(); const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [doc] }) ); core.uiSettings.get.mockImplementation(() => 10); @@ -128,7 +128,7 @@ describe('SavedObjectsFinder', () => { describe('sorting', () => { it('should list items ascending', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [doc, doc2] }) ); core.uiSettings.get.mockImplementation(() => 10); @@ -149,7 +149,7 @@ describe('SavedObjectsFinder', () => { it('should list items descending', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [doc, doc2] }) ); core.uiSettings.get.mockImplementation(() => 10); @@ -173,7 +173,7 @@ describe('SavedObjectsFinder', () => { it('should not show the saved objects which get filtered by showSavedObject', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [doc, doc2] }) ); core.uiSettings.get.mockImplementation(() => 10); @@ -203,7 +203,7 @@ describe('SavedObjectsFinder', () => { describe('search', () => { it('should request filtered list on search input', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [doc, doc2] }) ); core.uiSettings.get.mockImplementation(() => 10); @@ -278,7 +278,7 @@ describe('SavedObjectsFinder', () => { it('should respect response order on search input', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [doc, doc2] }) ); core.uiSettings.get.mockImplementation(() => 10); @@ -306,7 +306,7 @@ describe('SavedObjectsFinder', () => { it('should request multiple saved object types at once', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [doc, doc2] }) ); core.uiSettings.get.mockImplementation(() => 10); @@ -358,7 +358,7 @@ describe('SavedObjectsFinder', () => { it('should not render filter buttons if disabled', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [doc, doc2, doc3], }) @@ -383,7 +383,7 @@ describe('SavedObjectsFinder', () => { it('should not render filter buttons if there is only one type in the list', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [doc, doc2], }) @@ -408,7 +408,7 @@ describe('SavedObjectsFinder', () => { it('should apply filter if selected', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [doc, doc2, doc3], }) @@ -438,7 +438,7 @@ describe('SavedObjectsFinder', () => { it('should display no items message if there are no items', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [] }) ); core.uiSettings.get.mockImplementation(() => 10); @@ -469,7 +469,7 @@ describe('SavedObjectsFinder', () => { it('should show a table pagination with initial per page', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: longItemList }) ); core.uiSettings.get.mockImplementation(() => 10); @@ -491,7 +491,7 @@ describe('SavedObjectsFinder', () => { it('should allow switching the page size', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: longItemList }) ); core.uiSettings.get.mockImplementation(() => 10); @@ -513,7 +513,7 @@ describe('SavedObjectsFinder', () => { it('should switch page correctly', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: longItemList }) ); core.uiSettings.get.mockImplementation(() => 10); @@ -535,7 +535,7 @@ describe('SavedObjectsFinder', () => { it('should show an ordinary pagination for fixed page sizes', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: longItemList }) ); core.uiSettings.get.mockImplementation(() => 10); @@ -557,7 +557,7 @@ describe('SavedObjectsFinder', () => { it('should switch page correctly for fixed page sizes', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: longItemList }) ); core.uiSettings.get.mockImplementation(() => 10); @@ -596,7 +596,7 @@ describe('SavedObjectsFinder', () => { it('should hide the spinner if data is shown', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [doc] }) ); @@ -621,7 +621,7 @@ describe('SavedObjectsFinder', () => { it('should not show the spinner if there are already items', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [doc] }) ); @@ -648,7 +648,7 @@ describe('SavedObjectsFinder', () => { it('should render with children', async () => { const core = coreMock.createStart(); - ((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() => + (core.savedObjects.client.find as any as jest.SpyInstance).mockImplementation(() => Promise.resolve({ savedObjects: [doc, doc2] }) ); core.uiSettings.get.mockImplementation(() => 10); diff --git a/src/plugins/saved_objects/public/plugin.ts b/src/plugins/saved_objects/public/plugin.ts index c8e62efc1a86..d1b9f0f57fcf 100644 --- a/src/plugins/saved_objects/public/plugin.ts +++ b/src/plugins/saved_objects/public/plugin.ts @@ -39,7 +39,8 @@ export interface SavedObjectsStartDeps { } export class SavedObjectsPublicPlugin - implements Plugin { + implements Plugin +{ private decoratorRegistry = new SavedObjectDecoratorRegistry(); public setup(): SavedObjectSetup { diff --git a/src/plugins/saved_objects/public/saved_object/helpers/serialize_saved_object.ts b/src/plugins/saved_objects/public/saved_object/helpers/serialize_saved_object.ts index efe7a85f8f1e..c5e6e158a2cb 100644 --- a/src/plugins/saved_objects/public/saved_object/helpers/serialize_saved_object.ts +++ b/src/plugins/saved_objects/public/saved_object/helpers/serialize_saved_object.ts @@ -31,10 +31,8 @@ export function serializeSavedObject(savedObject: SavedObject, config: SavedObje }); if (savedObject.searchSource) { - const { - searchSourceJSON, - references: searchSourceReferences, - } = savedObject.searchSource.serialize(); + const { searchSourceJSON, references: searchSourceReferences } = + savedObject.searchSource.serialize(); attributes.kibanaSavedObjectMeta = { searchSourceJSON }; references.push(...searchSourceReferences); } 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 6d35f94eec51..2f45ee211c8c 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 @@ -93,7 +93,7 @@ describe('Saved Object', () => { const initSavedObjectClass = () => { SavedObjectClass = createSavedObjectClass( - ({ + { savedObjectsClient: savedObjectsClientStub, indexPatterns: dataStartMock.indexPatterns, search: { @@ -104,7 +104,7 @@ describe('Saved Object', () => { createEmpty: createSearchSourceMock, }, }, - } as unknown) as SavedObjectKibanaServices, + } as unknown as SavedObjectKibanaServices, decoratorRegistry ); }; @@ -653,13 +653,13 @@ describe('Saved Object', () => { it('passes references to search source parsing function', async () => { SavedObjectClass = createSavedObjectClass( - ({ + { savedObjectsClient: savedObjectsClientStub, indexPatterns: dataStartMock.indexPatterns, search: { ...dataStartMock.search, }, - } as unknown) as SavedObjectKibanaServices, + } as unknown as SavedObjectKibanaServices, decoratorRegistry ); const savedObject = new SavedObjectClass({ type: 'dashboard', searchSource: true }); diff --git a/src/plugins/saved_objects_management/public/lib/resolve_saved_objects.test.ts b/src/plugins/saved_objects_management/public/lib/resolve_saved_objects.test.ts index b1c052e56ef2..d5ec2ad9739a 100644 --- a/src/plugins/saved_objects_management/public/lib/resolve_saved_objects.test.ts +++ b/src/plugins/saved_objects_management/public/lib/resolve_saved_objects.test.ts @@ -57,7 +57,7 @@ describe('resolveSavedObjects', () => { }, ]; - const indexPatterns = ({ + const indexPatterns = { get: async () => { return { create: () => '2', @@ -69,9 +69,9 @@ describe('resolveSavedObjects', () => { cache: { clear: () => {}, }, - } as unknown) as IndexPatternsContract; + } as unknown as IndexPatternsContract; - const services = ([ + const services = [ { type: 'search', get: async () => { @@ -111,7 +111,7 @@ describe('resolveSavedObjects', () => { }; }, }, - ] as unknown) as SavedObjectLoader[]; + ] as unknown as SavedObjectLoader[]; const overwriteAll = false; @@ -149,7 +149,7 @@ describe('resolveSavedObjects', () => { }, ]; - const indexPatterns = ({ + const indexPatterns = { get: async () => { return { create: () => '2', @@ -161,9 +161,9 @@ describe('resolveSavedObjects', () => { cache: { clear: () => {}, }, - } as unknown) as IndexPatternsContract; + } as unknown as IndexPatternsContract; - const services = ([ + const services = [ { type: 'search', get: async () => { @@ -204,7 +204,7 @@ describe('resolveSavedObjects', () => { }; }, }, - ] as unknown) as SavedObjectLoader[]; + ] as unknown as SavedObjectLoader[]; const overwriteAll = false; @@ -229,9 +229,9 @@ describe('resolveSavedObjects', () => { const search = dataPluginMock.createStartContract().search; dependencies = { - indexPatterns: ({ + indexPatterns: { get: (id: string) => Promise.resolve({ id }), - } as unknown) as IndexPatternsContract, + } as unknown as IndexPatternsContract, search, }; }); @@ -239,7 +239,7 @@ describe('resolveSavedObjects', () => { it('should resave resolutions', async () => { const save = jest.fn(); - const conflictedIndexPatterns = ([ + const conflictedIndexPatterns = [ { obj: { save, @@ -268,7 +268,7 @@ describe('resolveSavedObjects', () => { }, }, }, - ] as unknown) as Array<{ obj: SavedObject; doc: any }>; + ] as unknown as Array<{ obj: SavedObject; doc: any }>; const resolutions = [ { @@ -301,7 +301,7 @@ describe('resolveSavedObjects', () => { it('should resolve filter index conflicts', async () => { const save = jest.fn(); - const conflictedIndexPatterns = ([ + const conflictedIndexPatterns = [ { obj: { save, @@ -331,7 +331,7 @@ describe('resolveSavedObjects', () => { }, }, }, - ] as unknown) as Array<{ obj: SavedObject; doc: any }>; + ] as unknown as Array<{ obj: SavedObject; doc: any }>; const resolutions = [ { 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 95bd41745553..7b97c71f38cf 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 @@ -64,15 +64,8 @@ async function importIndexPattern( openConfirm: OverlayStart['openConfirm'] ) { // TODO: consolidate this is the code in create_index_pattern_wizard.js - const { - title, - timeFieldName, - fields, - fieldFormatMap, - sourceFilters, - type, - typeMeta, - } = doc._source; + const { title, timeFieldName, fields, fieldFormatMap, sourceFilters, type, typeMeta } = + doc._source; const indexPatternSpec: IndexPatternSpec = { id: doc._id, title, diff --git a/src/plugins/saved_objects_management/public/management_section/mount_section.tsx b/src/plugins/saved_objects_management/public/management_section/mount_section.tsx index 6e5a30b046e6..6974707cb6dd 100644 --- a/src/plugins/saved_objects_management/public/management_section/mount_section.tsx +++ b/src/plugins/saved_objects_management/public/management_section/mount_section.tsx @@ -37,11 +37,8 @@ export const mountManagementSection = async ({ mountParams, serviceRegistry, }: MountParams) => { - const [ - coreStart, - { data, savedObjectsTaggingOss, spaces: spacesApi }, - pluginStart, - ] = await core.getStartServices(); + const [coreStart, { data, savedObjectsTaggingOss, spaces: spacesApi }, pluginStart] = + await core.getStartServices(); const { element, history, setBreadcrumbs } = mountParams; if (allowedObjectTypes === undefined) { allowedObjectTypes = await getAllowedTypes(coreStart.http); 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 3bf70de1abda..079a1c07da19 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 @@ -86,14 +86,8 @@ export class SavedObjectEdition extends Component< } render() { - const { - capabilities, - notFoundType, - serviceRegistry, - http, - serviceName, - savedObjectsClient, - } = this.props; + const { capabilities, notFoundType, serviceRegistry, http, serviceName, savedObjectsClient } = + this.props; const { type } = this.state; const { object } = this.state; const { edit: canEdit, delete: canDelete } = capabilities.savedObjectsManagement as Record< 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 a1eb94ab55cf..7b4dfa0182df 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 @@ -24,20 +24,20 @@ import { Flyout, FlyoutProps, FlyoutState } from './flyout'; import { ShallowWrapper } from 'enzyme'; import { dataPluginMock } from '../../../../../data/public/mocks'; -const mockFile = ({ +const mockFile = { name: 'foo.ndjson', path: '/home/foo.ndjson', -} as unknown) as File; -const legacyMockFile = ({ +} as unknown as File; +const legacyMockFile = { name: 'foo.json', path: '/home/foo.json', -} as unknown) as File; +} as unknown as File; describe('Flyout', () => { let defaultProps: FlyoutProps; const shallowRender = (props: FlyoutProps) => { - return (shallowWithI18nProvider() as unknown) as ShallowWrapper< + return shallowWithI18nProvider() as unknown as ShallowWrapper< FlyoutProps, FlyoutState, Flyout @@ -318,7 +318,8 @@ describe('Flyout', () => { importLegacyFileMock.mockImplementation(() => mockData); resolveSavedObjectsMock.mockImplementation(() => ({ conflictedIndexPatterns: mockConflictedIndexPatterns, - conflictedSavedObjectsLinkedToSavedSearches: mockConflictedSavedObjectsLinkedToSavedSearches, + conflictedSavedObjectsLinkedToSavedSearches: + mockConflictedSavedObjectsLinkedToSavedSearches, conflictedSearchDocs: mockConflictedSearchDocs, importedObjectCount: 2, confirmModalPromise: () => {}, @@ -348,7 +349,8 @@ describe('Flyout', () => { expect(component.state()).toMatchObject({ conflictedIndexPatterns: mockConflictedIndexPatterns, - conflictedSavedObjectsLinkedToSavedSearches: mockConflictedSavedObjectsLinkedToSavedSearches, + conflictedSavedObjectsLinkedToSavedSearches: + mockConflictedSavedObjectsLinkedToSavedSearches, conflictedSearchDocs: mockConflictedSearchDocs, importCount: 2, status: 'idle', 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 f823011dd888..dca64ffe943b 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 @@ -81,9 +81,9 @@ describe('SavedObjectsTable', () => { let search: ReturnType['search']; const shallowRender = (overrides: Partial = {}) => { - return (shallowWithI18nProvider( + return shallowWithI18nProvider( - ) as unknown) as ShallowWrapper< + ) as unknown as ShallowWrapper< SavedObjectsTableProps, SavedObjectsTableState, SavedObjectsTable diff --git a/src/plugins/saved_objects_management/public/plugin.ts b/src/plugins/saved_objects_management/public/plugin.ts index cc6bd8300546..9f0a7aa35254 100644 --- a/src/plugins/saved_objects_management/public/plugin.ts +++ b/src/plugins/saved_objects_management/public/plugin.ts @@ -60,7 +60,8 @@ export class SavedObjectsManagementPlugin SavedObjectsManagementPluginStart, SetupDependencies, StartDependencies - > { + > +{ private actionService = new SavedObjectsManagementActionService(); private columnService = new SavedObjectsManagementColumnService(); private serviceRegistry = new SavedObjectsManagementServiceRegistry(); diff --git a/src/plugins/saved_objects_management/public/services/columns/share_saved_objects_to_space_column.tsx b/src/plugins/saved_objects_management/public/services/columns/share_saved_objects_to_space_column.tsx index 736b656f15d9..6971021a81e8 100644 --- a/src/plugins/saved_objects_management/public/services/columns/share_saved_objects_to_space_column.tsx +++ b/src/plugins/saved_objects_management/public/services/columns/share_saved_objects_to_space_column.tsx @@ -25,7 +25,8 @@ const Wrapper = ({ spacesApiUi, props }: WrapperProps) => { }; export class ShareToSpaceSavedObjectsManagementColumn - implements SavedObjectsManagementColumn { + implements SavedObjectsManagementColumn +{ public id: string = 'share_saved_objects_to_space'; public euiColumn = { diff --git a/src/plugins/saved_objects_management/public/services/service_registry.ts b/src/plugins/saved_objects_management/public/services/service_registry.ts index 0b4c33a63ea7..9e4ed5a48993 100644 --- a/src/plugins/saved_objects_management/public/services/service_registry.ts +++ b/src/plugins/saved_objects_management/public/services/service_registry.ts @@ -15,7 +15,8 @@ export interface SavedObjectsManagementServiceRegistryEntry { title: string; } -export type ISavedObjectsManagementServiceRegistry = PublicMethodsOf; +export type ISavedObjectsManagementServiceRegistry = + PublicMethodsOf; export class SavedObjectsManagementServiceRegistry { private readonly registry = new Map(); diff --git a/src/plugins/saved_objects_management/server/plugin.ts b/src/plugins/saved_objects_management/server/plugin.ts index cc0fb068a7a7..c84f7b627720 100644 --- a/src/plugins/saved_objects_management/server/plugin.ts +++ b/src/plugins/saved_objects_management/server/plugin.ts @@ -15,7 +15,8 @@ import { registerRoutes } from './routes'; import { capabilitiesProvider } from './capabilities_provider'; export class SavedObjectsManagementPlugin - implements Plugin { + implements Plugin +{ private readonly logger: Logger; private managementService$ = new Subject(); diff --git a/src/plugins/saved_objects_tagging_oss/public/decorator/factory.ts b/src/plugins/saved_objects_tagging_oss/public/decorator/factory.ts index e3f4353d9cb1..ebd490a8761e 100644 --- a/src/plugins/saved_objects_tagging_oss/public/decorator/factory.ts +++ b/src/plugins/saved_objects_tagging_oss/public/decorator/factory.ts @@ -13,10 +13,11 @@ import { decorateObject } from './decorate_object'; export const decoratorId = 'tag'; -export const tagDecoratorFactory: SavedObjectDecoratorFactory = () => { - return { - getId: () => decoratorId, - decorateConfig, - decorateObject, +export const tagDecoratorFactory: SavedObjectDecoratorFactory = + () => { + return { + getId: () => decoratorId, + decorateConfig, + decorateObject, + }; }; -}; diff --git a/src/plugins/saved_objects_tagging_oss/public/decorator/inject_tag_references.ts b/src/plugins/saved_objects_tagging_oss/public/decorator/inject_tag_references.ts index bcaf03e60783..a73b70dd87c0 100644 --- a/src/plugins/saved_objects_tagging_oss/public/decorator/inject_tag_references.ts +++ b/src/plugins/saved_objects_tagging_oss/public/decorator/inject_tag_references.ts @@ -18,7 +18,7 @@ export const injectTagReferences: Required['injectReferences' object, references = [] ) => { - ((object as unknown) as InternalTagDecoratedSavedObject).__tags = references + (object as unknown as InternalTagDecoratedSavedObject).__tags = references .filter(({ type }) => type === 'tag') .map(({ id }) => id); }; diff --git a/src/plugins/saved_objects_tagging_oss/public/plugin.ts b/src/plugins/saved_objects_tagging_oss/public/plugin.ts index 82592dca296f..f923a08eb0b0 100644 --- a/src/plugins/saved_objects_tagging_oss/public/plugin.ts +++ b/src/plugins/saved_objects_tagging_oss/public/plugin.ts @@ -18,7 +18,8 @@ interface SetupDeps { export class SavedObjectTaggingOssPlugin implements - Plugin { + Plugin +{ private apiRegistered = false; private api?: SavedObjectsTaggingApi; diff --git a/src/plugins/screenshot_mode/common/get_set_browser_screenshot_mode.ts b/src/plugins/screenshot_mode/common/get_set_browser_screenshot_mode.ts index 7714f88cebee..ff79ccf0126f 100644 --- a/src/plugins/screenshot_mode/common/get_set_browser_screenshot_mode.ts +++ b/src/plugins/screenshot_mode/common/get_set_browser_screenshot_mode.ts @@ -21,7 +21,7 @@ export const KBN_SCREENSHOT_MODE_ENABLED_KEY = '__KBN_SCREENSHOT_MODE_ENABLED_KE */ export const getScreenshotMode = (): boolean => { return ( - ((window as unknown) as Record)[KBN_SCREENSHOT_MODE_ENABLED_KEY] === true || + (window as unknown as Record)[KBN_SCREENSHOT_MODE_ENABLED_KEY] === true || window.localStorage.getItem(KBN_SCREENSHOT_MODE_ENABLED_KEY) === 'true' ); }; diff --git a/src/plugins/screenshot_mode/server/plugin.ts b/src/plugins/screenshot_mode/server/plugin.ts index 9ef410d999ea..9295451f640c 100644 --- a/src/plugins/screenshot_mode/server/plugin.ts +++ b/src/plugins/screenshot_mode/server/plugin.ts @@ -15,7 +15,8 @@ import { import { isScreenshotMode } from './is_screenshot_mode'; export class ScreenshotModePlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup): ScreenshotModePluginSetup { core.http.registerRouteHandlerContext( 'screenshotMode', diff --git a/src/plugins/security_oss/public/insecure_cluster_service/components/default_alert.tsx b/src/plugins/security_oss/public/insecure_cluster_service/components/default_alert.tsx index 288d49457a64..192be5188041 100644 --- a/src/plugins/security_oss/public/insecure_cluster_service/components/default_alert.tsx +++ b/src/plugins/security_oss/public/insecure_cluster_service/components/default_alert.tsx @@ -25,63 +25,62 @@ export const defaultAlertTitle = i18n.translate('security.checkup.insecureCluste defaultMessage: 'Your data is not secure', }); -export const defaultAlertText: (onDismiss: (persist: boolean) => void) => MountPoint = ( - onDismiss -) => (e) => { - const AlertText = () => { - const [persist, setPersist] = useState(false); +export const defaultAlertText: (onDismiss: (persist: boolean) => void) => MountPoint = + (onDismiss) => (e) => { + const AlertText = () => { + const [persist, setPersist] = useState(false); - return ( - -
- - +
+ + + + + setPersist(changeEvent.target.checked)} + label={i18n.translate('security.checkup.dontShowAgain', { + defaultMessage: `Don't show again`, + })} /> - - - setPersist(changeEvent.target.checked)} - label={i18n.translate('security.checkup.dontShowAgain', { - defaultMessage: `Don't show again`, - })} - /> - - - - - {i18n.translate('security.checkup.learnMoreButtonText', { - defaultMessage: `Learn more`, - })} - - - - onDismiss(persist)} - data-test-subj="defaultDismissAlertButton" - > - {i18n.translate('security.checkup.dismissButtonText', { - defaultMessage: `Dismiss`, - })} - - - -
- - ); - }; + + + + + {i18n.translate('security.checkup.learnMoreButtonText', { + defaultMessage: `Learn more`, + })} + + + + onDismiss(persist)} + data-test-subj="defaultDismissAlertButton" + > + {i18n.translate('security.checkup.dismissButtonText', { + defaultMessage: `Dismiss`, + })} + + + +
+
+ ); + }; - render(, e); + render(, e); - return () => unmountComponentAtNode(e); -}; + return () => unmountComponentAtNode(e); + }; diff --git a/src/plugins/security_oss/public/plugin.mock.ts b/src/plugins/security_oss/public/plugin.mock.ts index 324e0cdfd852..23a6050a0e50 100644 --- a/src/plugins/security_oss/public/plugin.mock.ts +++ b/src/plugins/security_oss/public/plugin.mock.ts @@ -20,7 +20,8 @@ export const mockSecurityOssPlugin = { }, createStart: () => { return { - insecureCluster: mockInsecureClusterService.createStart() as jest.Mocked, + insecureCluster: + mockInsecureClusterService.createStart() as jest.Mocked, anonymousAccess: { getAccessURLParameters: jest.fn().mockResolvedValue(null), getCapabilities: jest.fn().mockResolvedValue({}), diff --git a/src/plugins/security_oss/public/plugin.ts b/src/plugins/security_oss/public/plugin.ts index 0104950f2236..c26323b01f35 100644 --- a/src/plugins/security_oss/public/plugin.ts +++ b/src/plugins/security_oss/public/plugin.ts @@ -35,7 +35,8 @@ export interface SecurityOssPluginStart { } export class SecurityOssPlugin - implements Plugin { + implements Plugin +{ private readonly config = this.initializerContext.config.get(); private readonly insecureClusterService = new InsecureClusterService(this.config, localStorage); private readonly appStateService = new AppStateService(); diff --git a/src/plugins/share/public/components/url_panel_content.test.tsx b/src/plugins/share/public/components/url_panel_content.test.tsx index 422cd0573a42..5d99609cd0e0 100644 --- a/src/plugins/share/public/components/url_panel_content.test.tsx +++ b/src/plugins/share/public/components/url_panel_content.test.tsx @@ -73,9 +73,9 @@ describe('share url panel content', () => { /> ); await act(async () => { - component.find(EuiSwitch).prop('onChange')!(({ + component.find(EuiSwitch).prop('onChange')!({ target: { checked: true }, - } as unknown) as EuiSwitchEvent); + } as unknown as EuiSwitchEvent); }); expect(shortenUrlMock).toHaveBeenCalledWith( 'http://localhost:5601/app/myapp#/?_g=()&_a=()', @@ -164,9 +164,9 @@ describe('share url panel content', () => { /> ); await act(async () => { - component.find(EuiSwitch).prop('onChange')!(({ + component.find(EuiSwitch).prop('onChange')!({ target: { checked: true }, - } as unknown) as EuiSwitchEvent); + } as unknown as EuiSwitchEvent); }); expect(shortenUrlMock).toHaveBeenCalledWith( 'http://localhost:5601/app/myapp#/?embed=true&_g=()&_a=()', diff --git a/src/plugins/share/public/components/url_panel_content.tsx b/src/plugins/share/public/components/url_panel_content.tsx index 009d70befca6..80c29f10b57d 100644 --- a/src/plugins/share/public/components/url_panel_content.tsx +++ b/src/plugins/share/public/components/url_panel_content.tsx @@ -104,7 +104,8 @@ export class UrlPanelContent extends Component { if (this.props.anonymousAccess) { (async () => { - const anonymousAccessParameters = await this.props.anonymousAccess!.getAccessURLParameters(); + const anonymousAccessParameters = + await this.props.anonymousAccess!.getAccessURLParameters(); if (!this.mounted) { return; @@ -542,19 +543,19 @@ export class UrlPanelContent extends Component { return; } - const setParamValue = (paramName: string) => ( - values: { [queryParam: string]: boolean } = {} - ): void => { - const stateUpdate = { - urlParams: { - ...this.state.urlParams, - [paramName]: { - ...values, + const setParamValue = + (paramName: string) => + (values: { [queryParam: string]: boolean } = {}): void => { + const stateUpdate = { + urlParams: { + ...this.state.urlParams, + [paramName]: { + ...values, + }, }, - }, + }; + this.setState(stateUpdate, this.state.useShortUrl ? this.createShortUrl : this.setUrl); }; - this.setState(stateUpdate, this.state.useShortUrl ? this.createShortUrl : this.setUrl); - }; return ( diff --git a/src/plugins/share/public/lib/url_shortener.test.ts b/src/plugins/share/public/lib/url_shortener.test.ts index 83db0e84a4a5..865fbc6f7e90 100644 --- a/src/plugins/share/public/lib/url_shortener.test.ts +++ b/src/plugins/share/public/lib/url_shortener.test.ts @@ -96,8 +96,7 @@ describe('Url shortener', () => { }); expect(shortUrl).toBe(`http://localhost${basePath}/goto/${shareId}`); expect(postStub).toHaveBeenCalledWith(`/api/shorten_url`, { - body: - '{"url":"/app/discover#/?_g=(refreshInterval:(pause:!f,value:0),time:(from:now-15m,mode:quick,to:now))&_a=(columns:!(_source),index:%27logstash-*%27,interval:auto,query:(query_string:(analyze_wildcard:!t,query:%27*%27)),sort:!(%27@timestamp%27,desc))"}', + body: '{"url":"/app/discover#/?_g=(refreshInterval:(pause:!f,value:0),time:(from:now-15m,mode:quick,to:now))&_a=(columns:!(_source),index:%27logstash-*%27,interval:auto,query:(query_string:(analyze_wildcard:!t,query:%27*%27)),sort:!(%27@timestamp%27,desc))"}', }); }); }); diff --git a/src/plugins/share/public/url_generators/url_generator_contract.ts b/src/plugins/share/public/url_generators/url_generator_contract.ts index b66ba02bde8d..b21e0f2a35c8 100644 --- a/src/plugins/share/public/url_generators/url_generator_contract.ts +++ b/src/plugins/share/public/url_generators/url_generator_contract.ts @@ -12,9 +12,7 @@ export interface UrlGeneratorContract { id: Id; createUrl(state: UrlGeneratorStateMapping[Id]['State']): Promise; isDeprecated: boolean; - migrate( - state: UrlGeneratorStateMapping[Id]['State'] - ): Promise<{ + migrate(state: UrlGeneratorStateMapping[Id]['State']): Promise<{ state: UrlGeneratorStateMapping[Id]['MigratedState']; id: UrlGeneratorStateMapping[Id]['MigratedId']; }>; diff --git a/src/plugins/share/public/url_generators/url_generator_definition.ts b/src/plugins/share/public/url_generators/url_generator_definition.ts index 5456550c16b3..32fe51a16d19 100644 --- a/src/plugins/share/public/url_generators/url_generator_definition.ts +++ b/src/plugins/share/public/url_generators/url_generator_definition.ts @@ -31,9 +31,7 @@ export interface UrlGeneratorsDefinition { id: Id; createUrl?: (state: UrlGeneratorStateMapping[Id]['State']) => Promise; isDeprecated?: boolean; - migrate?: ( - state: UrlGeneratorStateMapping[Id]['State'] - ) => Promise<{ + migrate?: (state: UrlGeneratorStateMapping[Id]['State']) => Promise<{ state: UrlGeneratorStateMapping[Id]['MigratedState']; id: UrlGeneratorStateMapping[Id]['MigratedId']; }>; diff --git a/src/plugins/share/public/url_service/redirect/redirect_manager.test.ts b/src/plugins/share/public/url_service/redirect/redirect_manager.test.ts index f610268f529b..7296ef6d0c13 100644 --- a/src/plugins/share/public/url_service/redirect/redirect_manager.test.ts +++ b/src/plugins/share/public/url_service/redirect/redirect_manager.test.ts @@ -22,7 +22,7 @@ const setup = () => { }; }, migrations: { - '0.0.2': ((({ num }: { num: number }) => ({ num: num * 2 })) as unknown) as MigrateFunction, + '0.0.2': (({ num }: { num: number }) => ({ num: num * 2 })) as unknown as MigrateFunction, }, }); const manager = new RedirectManager({ diff --git a/src/plugins/telemetry/server/collectors/telemetry_plugin/telemetry_plugin_collector.ts b/src/plugins/telemetry/server/collectors/telemetry_plugin/telemetry_plugin_collector.ts index 95bcb8553a45..6d1266b7f27a 100644 --- a/src/plugins/telemetry/server/collectors/telemetry_plugin/telemetry_plugin_collector.ts +++ b/src/plugins/telemetry/server/collectors/telemetry_plugin/telemetry_plugin_collector.ts @@ -32,9 +32,11 @@ export function createCollectorFetch({ getSavedObjectsClient, }: TelemetryPluginUsageCollectorOptions) { return async function fetchUsageStats(): Promise { - const { sendUsageFrom, allowChangingOptInStatus, optIn = null } = await config$ - .pipe(take(1)) - .toPromise(); + const { + sendUsageFrom, + allowChangingOptInStatus, + optIn = null, + } = await config$.pipe(take(1)).toPromise(); const configTelemetrySendUsageFrom = sendUsageFrom; const configTelemetryOptIn = optIn; diff --git a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts index bacfa5e77107..1a00d0e42801 100644 --- a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts +++ b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts @@ -114,13 +114,13 @@ describe('get_local_stats', () => { }, }, ]; - const clusterStats = ({ + const clusterStats = { _nodes: { failed: 123 }, cluster_name: 'real-cool', indices: { totally: 456 }, nodes: { yup: 'abc' }, random: 123, - } as unknown) as estypes.ClusterStatsResponse; + } as unknown as estypes.ClusterStatsResponse; const kibana = { kibana: { diff --git a/src/plugins/telemetry_collection_manager/server/encryption/telemetry_jwks.ts b/src/plugins/telemetry_collection_manager/server/encryption/telemetry_jwks.ts index bf4c2a952c43..b7f4c8a064ac 100644 --- a/src/plugins/telemetry_collection_manager/server/encryption/telemetry_jwks.ts +++ b/src/plugins/telemetry_collection_manager/server/encryption/telemetry_jwks.ts @@ -16,8 +16,7 @@ export const telemetryJWKS: PublicJWKS = { use: 'enc', alg: 'RSA-OAEP', e: 'AQAB', - n: - 'gjwVNVkOqbTZ6QrxdeYbKDnBzhCZGXM97Iq0dXJlpa-7UegcBemI1ALZkbX6AaDrCmqzetsnxJbVz2gr-uzkc97zzjTvPAn-jM-9cfjfsb-nd70qLY7ru3qdyOLb5-ho8cjmjnAp7VaEPuiNOjZ6V6tXq8Cn5LHH8G6K8oZLU1N4RWqkcAvEIlfaLusfMnl15fe7aZkYaKfVFjD-pti_2JGRV9XZ0knRI2oIRMaroBYpfYJxbpR0NLhR7ND6U5WlvxfnaVvRK4c_plVLOtcROqZVn98Z8yZ6GU14vCcvkIBox2D_xd1gSkpMammTQ3tVAEAvoq_wEn_qEbls1Uucgw', + n: 'gjwVNVkOqbTZ6QrxdeYbKDnBzhCZGXM97Iq0dXJlpa-7UegcBemI1ALZkbX6AaDrCmqzetsnxJbVz2gr-uzkc97zzjTvPAn-jM-9cfjfsb-nd70qLY7ru3qdyOLb5-ho8cjmjnAp7VaEPuiNOjZ6V6tXq8Cn5LHH8G6K8oZLU1N4RWqkcAvEIlfaLusfMnl15fe7aZkYaKfVFjD-pti_2JGRV9XZ0knRI2oIRMaroBYpfYJxbpR0NLhR7ND6U5WlvxfnaVvRK4c_plVLOtcROqZVn98Z8yZ6GU14vCcvkIBox2D_xd1gSkpMammTQ3tVAEAvoq_wEn_qEbls1Uucgw', }, { kty: 'RSA', @@ -25,8 +24,7 @@ export const telemetryJWKS: PublicJWKS = { use: 'enc', alg: 'RSA-OAEP', e: 'AQAB', - n: - 'rEi54h-9hCbqy9Mj_tJmx-dJdtrMmMzkhX5Wd63Pp3dABHpnLJSy--y8QoEa9K9ACaRfExSxgYQ-3K17Yy-UYj3ChAl3hrqZcP2AT3O18Lr2BN7EBjy88lTM0oeck9KLL_iGf8wz8_jeqQFIo3AWrBBuR3VFE0_k-_N1KCenSVm_fE3Nk_ZXm1ByFbgxWUFrYgLfEQn2v0FQYVpfTlbV_awtqoZLYGtuHmaLZhErzJFh6W8zrx8oSpGn8VlVLjF-AR3ugfw2F_HM8ZR8zY1dHVxvoLGz13F5aY8DHn0_ao9t0Yz2Y_SUNviyxMx0eIEJeo2njM2vMzYQNaT1Ghgc-w', + n: 'rEi54h-9hCbqy9Mj_tJmx-dJdtrMmMzkhX5Wd63Pp3dABHpnLJSy--y8QoEa9K9ACaRfExSxgYQ-3K17Yy-UYj3ChAl3hrqZcP2AT3O18Lr2BN7EBjy88lTM0oeck9KLL_iGf8wz8_jeqQFIo3AWrBBuR3VFE0_k-_N1KCenSVm_fE3Nk_ZXm1ByFbgxWUFrYgLfEQn2v0FQYVpfTlbV_awtqoZLYGtuHmaLZhErzJFh6W8zrx8oSpGn8VlVLjF-AR3ugfw2F_HM8ZR8zY1dHVxvoLGz13F5aY8DHn0_ao9t0Yz2Y_SUNviyxMx0eIEJeo2njM2vMzYQNaT1Ghgc-w', }, ], }; diff --git a/src/plugins/telemetry_collection_manager/server/plugin.ts b/src/plugins/telemetry_collection_manager/server/plugin.ts index 0efdde5eeafd..9770395e0ec0 100644 --- a/src/plugins/telemetry_collection_manager/server/plugin.ts +++ b/src/plugins/telemetry_collection_manager/server/plugin.ts @@ -40,7 +40,8 @@ interface TelemetryCollectionPluginsDepsSetup { } export class TelemetryCollectionManagerPlugin - implements Plugin { + implements Plugin +{ private readonly logger: Logger; private collectionStrategy: CollectionStrategy | undefined; private usageGetterMethodPriority = -1; diff --git a/src/plugins/telemetry_management_section/public/plugin.tsx b/src/plugins/telemetry_management_section/public/plugin.tsx index 2e3b1beb64d3..8f2d85f9107b 100644 --- a/src/plugins/telemetry_management_section/public/plugin.tsx +++ b/src/plugins/telemetry_management_section/public/plugin.tsx @@ -28,7 +28,8 @@ export interface TelemetryManagementSectionPluginSetup { } export class TelemetryManagementSectionPlugin - implements Plugin { + implements Plugin +{ private showSecuritySolutionExample = false; private shouldShowSecuritySolutionExample = () => { return this.showSecuritySolutionExample; diff --git a/src/plugins/tile_map/public/services.ts b/src/plugins/tile_map/public/services.ts index cef4fbae03f3..127d33a8a1a6 100644 --- a/src/plugins/tile_map/public/services.ts +++ b/src/plugins/tile_map/public/services.ts @@ -19,14 +19,12 @@ export const [getFormatService, setFormatService] = createGetterSetter< DataPublicPluginStart['fieldFormats'] >('vislib data.fieldFormats'); -export const [getQueryService, setQueryService] = createGetterSetter< - DataPublicPluginStart['query'] ->('Query'); +export const [getQueryService, setQueryService] = + createGetterSetter('Query'); export const [getShareService, setShareService] = createGetterSetter('Share'); -export const [getKibanaLegacy, setKibanaLegacy] = createGetterSetter( - 'KibanaLegacy' -); +export const [getKibanaLegacy, setKibanaLegacy] = + createGetterSetter('KibanaLegacy'); export const [getTmsLayers, setTmsLayers] = createGetterSetter('TmsLayers'); diff --git a/src/plugins/ui_actions/public/actions/action_internal.ts b/src/plugins/ui_actions/public/actions/action_internal.ts index 1b7d57e35f43..9abddf392983 100644 --- a/src/plugins/ui_actions/public/actions/action_internal.ts +++ b/src/plugins/ui_actions/public/actions/action_internal.ts @@ -16,7 +16,8 @@ import { uiToReactComponent } from '../../../kibana_react/public'; * @internal */ export class ActionInternal - implements Action>, Presentable> { + implements Action>, Presentable> +{ constructor(public readonly definition: A) {} public readonly id: string = this.definition.id; 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 03ce6dd9d1f8..f389a2fac8a7 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 @@ -43,23 +43,23 @@ type PanelDescriptor = EuiContextMenuPanelDescriptor & { items: ItemDescriptor[]; }; -const onClick = (action: Action, context: ActionExecutionContext, close: () => void) => ( - event: React.MouseEvent -) => { - if (event.currentTarget instanceof HTMLAnchorElement) { - // from react-router's - if ( - !event.defaultPrevented && // onClick prevented default - event.button === 0 && // ignore everything but left clicks - (!event.currentTarget.target || event.currentTarget.target === '_self') && // let browser handle "target=_blank" etc. - !(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey) // ignore clicks with modifier keys - ) { - event.preventDefault(); - action.execute(context); - } - } else action.execute(context); - close(); -}; +const onClick = + (action: Action, context: ActionExecutionContext, close: () => void) => + (event: React.MouseEvent) => { + if (event.currentTarget instanceof HTMLAnchorElement) { + // from react-router's + if ( + !event.defaultPrevented && // onClick prevented default + event.button === 0 && // ignore everything but left clicks + (!event.currentTarget.target || event.currentTarget.target === '_self') && // let browser handle "target=_blank" etc. + !(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey) // ignore clicks with modifier keys + ) { + event.preventDefault(); + action.execute(context); + } + } else action.execute(context); + close(); + }; /** * This method adds "More" item to panels, which have more than 4 items; and diff --git a/src/plugins/ui_actions/public/service/ui_actions_service.test.ts b/src/plugins/ui_actions/public/service/ui_actions_service.test.ts index 41fc6546b7ca..8d89b62ec208 100644 --- a/src/plugins/ui_actions/public/service/ui_actions_service.test.ts +++ b/src/plugins/ui_actions/public/service/ui_actions_service.test.ts @@ -162,7 +162,7 @@ describe('UiActionsService', () => { test('can register and get actions', async () => { const actions: ActionRegistry = new Map(); const service = new UiActionsService({ actions }); - const helloWorldAction = createHelloWorldAction(({} as unknown) as OverlayStart); + const helloWorldAction = createHelloWorldAction({} as unknown as OverlayStart); const length = actions.size; service.registerAction(helloWorldAction); @@ -173,7 +173,7 @@ describe('UiActionsService', () => { test('getTriggerCompatibleActions returns attached actions', async () => { const service = new UiActionsService(); - const helloWorldAction = createHelloWorldAction(({} as unknown) as OverlayStart); + const helloWorldAction = createHelloWorldAction({} as unknown as OverlayStart); service.registerAction(helloWorldAction); @@ -373,10 +373,10 @@ describe('UiActionsService', () => { const actions: ActionRegistry = new Map(); const service = new UiActionsService({ actions }); - service.registerAction(({ + service.registerAction({ id: ACTION_HELLO_WORLD, order: 13, - } as unknown) as ActionDefinition); + } as unknown as ActionDefinition); expect(actions.get(ACTION_HELLO_WORLD)).toMatchObject({ id: ACTION_HELLO_WORLD, @@ -390,10 +390,10 @@ describe('UiActionsService', () => { const trigger: Trigger = { id: MY_TRIGGER, }; - const action = ({ + const action = { id: ACTION_HELLO_WORLD, order: 25, - } as unknown) as ActionDefinition; + } as unknown as ActionDefinition; service.registerTrigger(trigger); service.addTriggerAction(MY_TRIGGER, action); @@ -410,10 +410,10 @@ describe('UiActionsService', () => { const trigger: Trigger = { id: MY_TRIGGER, }; - const action = ({ + const action = { id: ACTION_HELLO_WORLD, order: 25, - } as unknown) as ActionDefinition; + } as unknown as ActionDefinition; service.registerTrigger(trigger); service.registerAction(action); @@ -427,10 +427,10 @@ describe('UiActionsService', () => { test('detaching an invalid action from a trigger throws an error', async () => { const service = new UiActionsService(); - const action = ({ + const action = { id: ACTION_HELLO_WORLD, order: 25, - } as unknown) as ActionDefinition; + } as unknown as ActionDefinition; service.registerAction(action); expect(() => service.detachAction('i do not exist', ACTION_HELLO_WORLD)).toThrowError( @@ -441,10 +441,10 @@ describe('UiActionsService', () => { test('attaching an invalid action to a trigger throws an error', async () => { const service = new UiActionsService(); - const action = ({ + const action = { id: ACTION_HELLO_WORLD, order: 25, - } as unknown) as ActionDefinition; + } as unknown as ActionDefinition; service.registerAction(action); expect(() => service.addTriggerAction('i do not exist', action)).toThrowError( @@ -455,10 +455,10 @@ describe('UiActionsService', () => { test('cannot register another action with the same ID', async () => { const service = new UiActionsService(); - const action = ({ + const action = { id: ACTION_HELLO_WORLD, order: 25, - } as unknown) as ActionDefinition; + } as unknown as ActionDefinition; service.registerAction(action); expect(() => service.registerAction(action)).toThrowError( @@ -469,7 +469,7 @@ describe('UiActionsService', () => { test('cannot register another trigger with the same ID', async () => { const service = new UiActionsService(); - const trigger = ({ id: 'MY-TRIGGER' } as unknown) as Trigger; + const trigger = { id: 'MY-TRIGGER' } as unknown as Trigger; service.registerTrigger(trigger); expect(() => service.registerTrigger(trigger)).toThrowError( 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 4aba3a9c6810..3c87857591e6 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 @@ -15,7 +15,7 @@ import { waitFor } from '@testing-library/dom'; jest.mock('../context_menu'); const executeFn = jest.fn(); -const openContextMenuSpy = (openContextMenu as unknown) as jest.SpyInstance; +const openContextMenuSpy = openContextMenu as unknown as jest.SpyInstance; const CONTACT_USER_TRIGGER = 'CONTACT_USER_TRIGGER'; diff --git a/src/plugins/ui_actions/public/tests/get_trigger_actions.test.ts b/src/plugins/ui_actions/public/tests/get_trigger_actions.test.ts index 9a5de81b1854..b0a8ccaecb0d 100644 --- a/src/plugins/ui_actions/public/tests/get_trigger_actions.test.ts +++ b/src/plugins/ui_actions/public/tests/get_trigger_actions.test.ts @@ -9,16 +9,16 @@ import { ActionInternal, Action } from '../actions'; import { uiActionsPluginMock } from '../mocks'; -const action1: Action = ({ +const action1: Action = { id: 'action1', order: 1, type: 'type1', -} as unknown) as Action; -const action2: Action = ({ +} as unknown as Action; +const action2: Action = { id: 'action2', order: 2, type: 'type2', -} as unknown) as Action; +} as unknown as Action; test('returns actions set on trigger', () => { const { setup, doStart } = uiActionsPluginMock.createPlugin(); diff --git a/src/plugins/ui_actions/public/tests/get_trigger_compatible_actions.test.ts b/src/plugins/ui_actions/public/tests/get_trigger_compatible_actions.test.ts index 2d1c284e66ad..d372064c9ad3 100644 --- a/src/plugins/ui_actions/public/tests/get_trigger_compatible_actions.test.ts +++ b/src/plugins/ui_actions/public/tests/get_trigger_compatible_actions.test.ts @@ -32,14 +32,14 @@ beforeEach(() => { test('can register action', async () => { const { setup } = uiActions; - const helloWorldAction = createHelloWorldAction(({} as unknown) as OverlayStart); + const helloWorldAction = createHelloWorldAction({} as unknown as OverlayStart); setup.registerAction(helloWorldAction); }); test('getTriggerCompatibleActions returns attached actions', async () => { const { setup, doStart } = uiActions; - const helloWorldAction = createHelloWorldAction(({} as unknown) as OverlayStart); + const helloWorldAction = createHelloWorldAction({} as unknown as OverlayStart); setup.registerAction(helloWorldAction); diff --git a/src/plugins/usage_collection/server/collector/collector.ts b/src/plugins/usage_collection/server/collector/collector.ts index 21f8229718c8..74373d44a359 100644 --- a/src/plugins/usage_collection/server/collector/collector.ts +++ b/src/plugins/usage_collection/server/collector/collector.ts @@ -15,7 +15,8 @@ import type { } from './types'; export class Collector - implements ICollector { + implements ICollector +{ public readonly extendFetchContext: CollectorOptionsFetchExtendedContext; public readonly type: CollectorOptions['type']; public readonly fetch: CollectorFetchMethod; diff --git a/src/plugins/usage_collection/server/collector/types.ts b/src/plugins/usage_collection/server/collector/types.ts index 4258d5e4dd2e..bf1e9f4644b1 100644 --- a/src/plugins/usage_collection/server/collector/types.ts +++ b/src/plugins/usage_collection/server/collector/types.ts @@ -122,12 +122,11 @@ export interface ICollectorOptionsFetchExtendedContext = ICollectorOptionsFetchExtendedContext & - (WithKibanaRequest extends true // If enforced to true via Types, the config must be expected - ? Required, 'kibanaRequest'>> - : {}); +export type CollectorOptionsFetchExtendedContext = + ICollectorOptionsFetchExtendedContext & + (WithKibanaRequest extends true // If enforced to true via Types, the config must be expected + ? Required, 'kibanaRequest'>> + : {}); /** * Options to instantiate a collector diff --git a/src/plugins/usage_collection/server/mocks.ts b/src/plugins/usage_collection/server/mocks.ts index ca3bdfe1e752..5505e816532a 100644 --- a/src/plugins/usage_collection/server/mocks.ts +++ b/src/plugins/usage_collection/server/mocks.ts @@ -25,10 +25,8 @@ export const createUsageCollectionSetupMock = () => { logger: loggingSystemMock.createLogger(), maximumWaitTimeForAllCollectorsInS: 1, }); - const { - createUsageCounter, - getUsageCounterByType, - } = usageCountersServiceMock.createSetupContract(); + const { createUsageCounter, getUsageCounterByType } = + usageCountersServiceMock.createSetupContract(); const usageCollectionSetupMock: jest.Mocked = { createUsageCounter, diff --git a/src/plugins/usage_collection/server/usage_counters/usage_counters_service.mock.ts b/src/plugins/usage_collection/server/usage_counters/usage_counters_service.mock.ts index beb67d1eb260..0d96def54054 100644 --- a/src/plugins/usage_collection/server/usage_counters/usage_counters_service.mock.ts +++ b/src/plugins/usage_collection/server/usage_counters/usage_counters_service.mock.ts @@ -16,9 +16,9 @@ const createSetupContractMock = () => { getUsageCounterByType: jest.fn(), }; - setupContract.createUsageCounter.mockReturnValue(({ + setupContract.createUsageCounter.mockReturnValue({ incrementCounter: jest.fn(), - } as unknown) as jest.Mocked); + } as unknown as jest.Mocked); return setupContract; }; 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 483ad4486218..d82a91620bd7 100644 --- a/src/plugins/vis_default_editor/public/components/agg.test.tsx +++ b/src/plugins/vis_default_editor/public/components/agg.test.tsx @@ -249,9 +249,10 @@ describe('DefaultEditorAgg component', () => { expect(compHistogram.find(DefaultEditorAggParams).props()).toHaveProperty('disabledParams', [ 'min_doc_count', ]); - expect( - compDateHistogram.find(DefaultEditorAggParams).props() - ).toHaveProperty('disabledParams', ['min_doc_count']); + expect(compDateHistogram.find(DefaultEditorAggParams).props()).toHaveProperty( + 'disabledParams', + ['min_doc_count'] + ); }); it('should set error when agg is not histogram or date_histogram', () => { diff --git a/src/plugins/vis_default_editor/public/components/agg_params.test.tsx b/src/plugins/vis_default_editor/public/components/agg_params.test.tsx index 973f9167d308..2f71ae3b7ecd 100644 --- a/src/plugins/vis_default_editor/public/components/agg_params.test.tsx +++ b/src/plugins/vis_default_editor/public/components/agg_params.test.tsx @@ -84,7 +84,7 @@ describe('DefaultEditorAggParams component', () => { intervalDeserialize = jest.fn(() => 'deserialized'); defaultProps = { - agg: ({ + agg: { type: { params: [{ name: 'interval', deserialize: intervalDeserialize }], }, @@ -92,7 +92,7 @@ describe('DefaultEditorAggParams component', () => { schema: { title: '', }, - } as any) as IAggConfig, + } as any as IAggConfig, groupName: AggGroupNames.Metrics, formIsTouched: false, indexPattern: {} as IndexPattern, 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 39de530dab72..03c4823d22c8 100644 --- a/src/plugins/vis_default_editor/public/components/agg_params.tsx +++ b/src/plugins/vis_default_editor/public/components/agg_params.tsx @@ -75,14 +75,15 @@ function DefaultEditorAggParams({ hideCustomLabel = false, }: DefaultEditorAggParamsProps) { const schema = useMemo(() => getSchemaByName(schemas, agg.schema), [agg.schema, schemas]); - const aggFilter = useMemo(() => [...allowedAggs, ...(schema.aggFilter || [])], [ - allowedAggs, - schema.aggFilter, - ]); + const aggFilter = useMemo( + () => [...allowedAggs, ...(schema.aggFilter || [])], + [allowedAggs, schema.aggFilter] + ); const { services } = useKibana(); - const aggTypes = useMemo(() => services.data.search.aggs.types.getAll(), [ - services.data.search.aggs.types, - ]); + const aggTypes = useMemo( + () => services.data.search.aggs.types.getAll(), + [services.data.search.aggs.types] + ); const groupedAggTypeOptions = useMemo( () => getAggTypeOptions(aggTypes, agg, indexPattern, groupName, aggFilter), [aggTypes, agg, indexPattern, groupName, aggFilter] @@ -96,11 +97,10 @@ function DefaultEditorAggParams({ : ''; const aggTypeName = agg.type?.name; const fieldName = agg.params?.field?.name; - const editorConfig = useMemo(() => getEditorConfig(indexPattern, aggTypeName, fieldName), [ - indexPattern, - aggTypeName, - fieldName, - ]); + const editorConfig = useMemo( + () => getEditorConfig(indexPattern, aggTypeName, fieldName), + [indexPattern, aggTypeName, fieldName] + ); const params = useMemo( () => getAggParamsToRender({ agg, editorConfig, metricAggs, state, schemas, hideCustomLabel }), [agg, editorConfig, metricAggs, state, schemas, hideCustomLabel] diff --git a/src/plugins/vis_default_editor/public/components/agg_params_helper.test.ts b/src/plugins/vis_default_editor/public/components/agg_params_helper.test.ts index fb071e224b4b..c38af0364621 100644 --- a/src/plugins/vis_default_editor/public/components/agg_params_helper.test.ts +++ b/src/plugins/vis_default_editor/public/components/agg_params_helper.test.ts @@ -85,12 +85,12 @@ describe('DefaultEditorAggParams helpers', () => { }); it('should skip customLabel param if it is hidden', () => { - agg = ({ + agg = { type: { params: [{ name: 'customLabel' }], }, schema: 'metric2', - } as any) as IAggConfig; + } as any as IAggConfig; const params = getAggParamsToRender({ agg, editorConfig, metricAggs, state, schemas }); expect(params).toEqual(emptyParams); @@ -98,7 +98,7 @@ describe('DefaultEditorAggParams helpers', () => { it('should create a basic params field and orderBy', () => { const filterFieldTypes = ['number', 'boolean', 'date']; - agg = ({ + agg = { type: { type: AggGroupNames.Buckets, name: BUCKET_TYPES.TERMS, @@ -130,7 +130,7 @@ describe('DefaultEditorAggParams helpers', () => { orderBy: 'orderBy', field: 'field', }, - } as any) as IAggConfig; + } as any as IAggConfig; const params = getAggParamsToRender({ agg, editorConfig, metricAggs, state, schemas }); expect(params).toEqual({ 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 7a8737a8d918..fd88659f472f 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 @@ -74,10 +74,10 @@ function DateRangesParamEditor({ [setValue] ); - const onAddRange = useCallback(() => updateRanges([...ranges, { id: generateId() }]), [ - ranges, - updateRanges, - ]); + const onAddRange = useCallback( + () => updateRanges([...ranges, { id: generateId() }]), + [ranges, updateRanges] + ); useMount(() => { // set up an initial range when there is no default range diff --git a/src/plugins/vis_default_editor/public/components/controls/field.test.tsx b/src/plugins/vis_default_editor/public/components/controls/field.test.tsx index 277804567c2b..55ea1dbfc56a 100644 --- a/src/plugins/vis_default_editor/public/components/controls/field.test.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/field.test.tsx @@ -55,10 +55,10 @@ describe('FieldParamEditor component', () => { agg: { type: { params: [ - ({ + { name: 'field', filterFieldTypes: ['bytes'], - } as unknown) as AggParam, + } as unknown as AggParam, ], }, } as IAggConfig, diff --git a/src/plugins/vis_default_editor/public/components/controls/palette_picker.tsx b/src/plugins/vis_default_editor/public/components/controls/palette_picker.tsx index 9249edef8af9..ee6ee405c479 100644 --- a/src/plugins/vis_default_editor/public/components/controls/palette_picker.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/palette_picker.tsx @@ -8,10 +8,12 @@ import React from 'react'; import { PaletteOutput, PaletteRegistry } from 'src/plugins/charts/public'; -import { EuiColorPalettePicker } from '@elastic/eui'; +import { EuiColorPalettePicker, EuiColorPalettePickerPaletteProps } from '@elastic/eui'; import { EuiFormRow } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; +const DEFAULT_PALETTE = 'default'; + export interface PalettePickerProps { activePalette?: PaletteOutput; palettes: PaletteRegistry; @@ -25,6 +27,21 @@ export function PalettePicker({ paramName, setPalette, }: PalettePickerProps) { + const palettesList: EuiColorPalettePickerPaletteProps[] = palettes + .getAll() + .filter(({ internal }) => !internal) + .map(({ id, title, getCategoricalColors }) => { + return { + value: id, + title, + type: 'fixed', + palette: getCategoricalColors( + 10, + id === activePalette?.name ? activePalette?.params : undefined + ), + }; + }); + return ( ({ fullWidth data-test-subj="visEditorPalettePicker" compressed - palettes={palettes - .getAll() - .filter(({ internal }) => !internal) - .map(({ id, title, getCategoricalColors }) => { - return { - value: id, - title, - type: 'fixed', - palette: getCategoricalColors( - 10, - id === activePalette?.name ? activePalette?.params : undefined - ), - }; - })} + palettes={palettesList} onChange={(newPalette) => { + const palette = palettesList.find((item) => item.value === newPalette); setPalette(paramName, { type: 'palette', - name: newPalette, + name: palette?.value ?? DEFAULT_PALETTE, }); }} - valueOfSelected={activePalette?.name || 'default'} + valueOfSelected={activePalette?.name || DEFAULT_PALETTE} selectionDisplay={'palette'} /> diff --git a/src/plugins/vis_default_editor/public/components/controls/top_aggregate.test.tsx b/src/plugins/vis_default_editor/public/components/controls/top_aggregate.test.tsx index 9b004b657473..9c83403c60cb 100644 --- a/src/plugins/vis_default_editor/public/components/controls/top_aggregate.test.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/top_aggregate.test.tsx @@ -51,14 +51,14 @@ describe('TopAggregateParamEditor', () => { aggParam = { options, }; - agg = ({ + agg = { params: { field: { type: 'number', }, }, getAggParams: jest.fn(() => [{ name: 'aggregate', options }]), - } as any) as IAggConfig; + } as any as IAggConfig; defaultProps = { ...aggParamCommonPropsMock, agg, diff --git a/src/plugins/vis_default_editor/public/components/controls/utils/inline_comp_wrapper.tsx b/src/plugins/vis_default_editor/public/components/controls/utils/inline_comp_wrapper.tsx index bea25b2d5900..5afd51b58d65 100644 --- a/src/plugins/vis_default_editor/public/components/controls/utils/inline_comp_wrapper.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/utils/inline_comp_wrapper.tsx @@ -9,10 +9,11 @@ import React, { ComponentType } from 'react'; import { AggParamEditorProps } from '../../agg_param_props'; -export const wrapWithInlineComp = ( - WrapComponent: ComponentType> -) => (props: AggParamEditorProps) => ( -
- -
-); +export const wrapWithInlineComp = + (WrapComponent: ComponentType>) => + (props: AggParamEditorProps) => + ( +
+ +
+ ); diff --git a/src/plugins/vis_default_editor/public/components/options/color_ranges.tsx b/src/plugins/vis_default_editor/public/components/options/color_ranges.tsx index ad2bd7c003a9..67a6c9c6e8f4 100644 --- a/src/plugins/vis_default_editor/public/components/options/color_ranges.tsx +++ b/src/plugins/vis_default_editor/public/components/options/color_ranges.tsx @@ -53,9 +53,10 @@ function ColorRanges({ [colorsRange] ); - const setColorRanges = useCallback((value: RangeValues[]) => setValue('colorsRange', value), [ - setValue, - ]); + const setColorRanges = useCallback( + (value: RangeValues[]) => setValue('colorsRange', value), + [setValue] + ); return ( { it('should call setValue when value is changes in the number input', () => { component = mountWithIntl(); const numberField = component.find(EuiFieldNumber); - numberField.props().onChange!(({ + numberField.props().onChange!({ target: { value: 3, }, - } as unknown) as React.ChangeEvent); + } as unknown as React.ChangeEvent); expect(props.setValue).toHaveBeenCalledWith('maxLegendLines', 3); }); 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 5eb0266bc1e1..15169500aad6 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 @@ -73,9 +73,10 @@ function DefaultEditorDataTab({ [dispatch, schemas] ); - const onReorderAggs: ReorderAggs = useCallback((...props) => dispatch(reorderAggs(...props)), [ - dispatch, - ]); + const onReorderAggs: ReorderAggs = useCallback( + (...props) => dispatch(reorderAggs(...props)), + [dispatch] + ); const onAggParamValueChange: DefaultEditorAggCommonProps['setAggParamValue'] = useCallback( (...props) => dispatch(setAggParamValue(...props)), 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 52d8109b352a..dab982e5a807 100644 --- a/src/plugins/vis_default_editor/public/components/sidebar/sidebar.tsx +++ b/src/plugins/vis_default_editor/public/components/sidebar/sidebar.tsx @@ -62,17 +62,19 @@ function DefaultEditorSideBarComponent({ const { formState, setTouched, setValidity, resetValidity } = useEditorFormState(); const [optionTabs, setSelectedTab] = useOptionTabs(vis); - const responseAggs = useMemo(() => (state.data.aggs ? state.data.aggs.getResponseAggs() : []), [ - state.data.aggs, - ]); + const responseAggs = useMemo( + () => (state.data.aggs ? state.data.aggs.getResponseAggs() : []), + [state.data.aggs] + ); const metricSchemas = (vis.type.schemas.metrics || []).map((s: Schema) => s.name); const metricAggs = useMemo( () => responseAggs.filter((agg) => agg.schema && metricSchemas.includes(agg.schema)), [responseAggs, metricSchemas] ); - const hasHistogramAgg = useMemo(() => responseAggs.some((agg) => agg.type.name === 'histogram'), [ - responseAggs, - ]); + const hasHistogramAgg = useMemo( + () => responseAggs.some((agg) => agg.type.name === 'histogram'), + [responseAggs] + ); const setStateValidity = useCallback( (value: boolean) => { 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 48ac8ac1d28f..ee2b715fad25 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 @@ -22,185 +22,182 @@ function initEditorState(vis: Vis) { export type EditorVisState = Pick; -const createEditorStateReducer = ({ - aggs: { createAggConfigs }, -}: DataPublicPluginStart['search']) => ( - state: EditorVisState, - action: EditorAction -): EditorVisState => { - switch (action.type) { - case EditorStateActionTypes.ADD_NEW_AGG: { - const { schema } = action.payload; - const defaultConfig = - !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, { - addToAggConfigs: false, - }); - aggConfig.brandNew = true; - const newAggs = [...state.data.aggs!.aggs, aggConfig]; - - return { - ...state, - data: { - ...state.data, - aggs: createAggConfigs(state.data.indexPattern!, newAggs), - }, - }; - } +const createEditorStateReducer = + ({ aggs: { createAggConfigs } }: DataPublicPluginStart['search']) => + (state: EditorVisState, action: EditorAction): EditorVisState => { + switch (action.type) { + case EditorStateActionTypes.ADD_NEW_AGG: { + const { schema } = action.payload; + const defaultConfig = + !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, { + addToAggConfigs: false, + }); + aggConfig.brandNew = true; + const newAggs = [...state.data.aggs!.aggs, aggConfig]; + + return { + ...state, + data: { + ...state.data, + aggs: createAggConfigs(state.data.indexPattern!, newAggs), + }, + }; + } - case EditorStateActionTypes.DISCARD_CHANGES: { - return initEditorState(action.payload); - } + case EditorStateActionTypes.DISCARD_CHANGES: { + return initEditorState(action.payload); + } - case EditorStateActionTypes.CHANGE_AGG_TYPE: { - const { aggId, value } = action.payload; + case EditorStateActionTypes.CHANGE_AGG_TYPE: { + const { aggId, value } = action.payload; - const newAggs = state.data.aggs!.aggs.map((agg) => { - if (agg.id === aggId) { - agg.type = value; + const newAggs = state.data.aggs!.aggs.map((agg) => { + if (agg.id === aggId) { + agg.type = value; - return agg.toJSON(); - } + return agg.toJSON(); + } - return agg; - }); + return agg; + }); - return { - ...state, - data: { - ...state.data, - aggs: createAggConfigs(state.data.indexPattern!, newAggs), - }, - }; - } + return { + ...state, + data: { + ...state.data, + aggs: createAggConfigs(state.data.indexPattern!, newAggs), + }, + }; + } - case EditorStateActionTypes.SET_AGG_PARAM_VALUE: { - const { aggId, paramName, value } = action.payload; + case EditorStateActionTypes.SET_AGG_PARAM_VALUE: { + const { aggId, paramName, value } = action.payload; - const newAggs = state.data.aggs!.aggs.map((agg) => { - if (agg.id === aggId) { - const parsedAgg = agg.toJSON(); + const newAggs = state.data.aggs!.aggs.map((agg) => { + if (agg.id === aggId) { + const parsedAgg = agg.toJSON(); - return { - ...parsedAgg, - params: { - ...parsedAgg.params, - [paramName]: value, - }, - }; - } + return { + ...parsedAgg, + params: { + ...parsedAgg.params, + [paramName]: value, + }, + }; + } - return agg; - }); + return agg; + }); - return { - ...state, - data: { - ...state.data, - aggs: createAggConfigs(state.data.indexPattern!, newAggs), - }, - }; - } + return { + ...state, + data: { + ...state.data, + aggs: createAggConfigs(state.data.indexPattern!, newAggs), + }, + }; + } - case EditorStateActionTypes.SET_STATE_PARAM_VALUE: { - const { paramName, value } = action.payload; + case EditorStateActionTypes.SET_STATE_PARAM_VALUE: { + const { paramName, value } = action.payload; - return { - ...state, - params: { - ...state.params, - [paramName]: value, - }, - }; - } + return { + ...state, + params: { + ...state.params, + [paramName]: value, + }, + }; + } - case EditorStateActionTypes.REMOVE_AGG: { - 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); - if (schemaDef && schemaDef.group === AggGroupNames.Metrics) { - isMetric = true; - } + case EditorStateActionTypes.REMOVE_AGG: { + 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); + if (schemaDef && schemaDef.group === AggGroupNames.Metrics) { + isMetric = true; + } - return false; - } + return false; + } - return true; - }); + return true; + }); - if (isMetric && getEnabledMetricAggsCount(newAggs) === 0) { - const aggToEnable = newAggs.find((agg) => agg.schema === 'metric'); + if (isMetric && getEnabledMetricAggsCount(newAggs) === 0) { + const aggToEnable = newAggs.find((agg) => agg.schema === 'metric'); - if (aggToEnable) { - aggToEnable.enabled = true; + if (aggToEnable) { + aggToEnable.enabled = true; + } } - } - return { - ...state, - data: { - ...state.data, - aggs: createAggConfigs(state.data.indexPattern!, newAggs), - }, - }; - } + return { + ...state, + data: { + ...state.data, + aggs: createAggConfigs(state.data.indexPattern!, newAggs), + }, + }; + } - case EditorStateActionTypes.REORDER_AGGS: { - const { sourceAgg, destinationAgg } = action.payload; - const destinationIndex = state.data.aggs!.aggs.indexOf(destinationAgg); - const newAggs = [...state.data.aggs!.aggs]; - newAggs.splice( - destinationIndex, - 0, - newAggs.splice(state.data.aggs!.aggs.indexOf(sourceAgg), 1)[0] - ); - - return { - ...state, - data: { - ...state.data, - aggs: createAggConfigs(state.data.indexPattern!, newAggs), - }, - }; - } + case EditorStateActionTypes.REORDER_AGGS: { + const { sourceAgg, destinationAgg } = action.payload; + const destinationIndex = state.data.aggs!.aggs.indexOf(destinationAgg); + const newAggs = [...state.data.aggs!.aggs]; + newAggs.splice( + destinationIndex, + 0, + newAggs.splice(state.data.aggs!.aggs.indexOf(sourceAgg), 1)[0] + ); + + return { + ...state, + data: { + ...state.data, + aggs: createAggConfigs(state.data.indexPattern!, newAggs), + }, + }; + } - case EditorStateActionTypes.TOGGLE_ENABLED_AGG: { - const { aggId, enabled } = action.payload; + case EditorStateActionTypes.TOGGLE_ENABLED_AGG: { + const { aggId, enabled } = action.payload; - const newAggs = state.data.aggs!.aggs.map((agg) => { - if (agg.id === aggId) { - const parsedAgg = agg.toJSON(); + const newAggs = state.data.aggs!.aggs.map((agg) => { + if (agg.id === aggId) { + const parsedAgg = agg.toJSON(); - return { - ...parsedAgg, - enabled, - }; - } + return { + ...parsedAgg, + enabled, + }; + } - return agg; - }); + return agg; + }); - return { - ...state, - data: { - ...state.data, - aggs: createAggConfigs(state.data.indexPattern!, newAggs), - }, - }; - } + return { + ...state, + data: { + ...state.data, + aggs: createAggConfigs(state.data.indexPattern!, newAggs), + }, + }; + } - case EditorStateActionTypes.UPDATE_STATE_PARAMS: { - const { params } = action.payload; + case EditorStateActionTypes.UPDATE_STATE_PARAMS: { + const { params } = action.payload; - return { - ...state, - params: cloneDeep(params), - }; + return { + ...state, + params: cloneDeep(params), + }; + } } - } -}; + }; export { createEditorStateReducer, initEditorState }; diff --git a/src/plugins/vis_default_editor/public/plugin.ts b/src/plugins/vis_default_editor/public/plugin.ts index 637ea53e6b2d..fd0d69bf297b 100644 --- a/src/plugins/vis_default_editor/public/plugin.ts +++ b/src/plugins/vis_default_editor/public/plugin.ts @@ -16,7 +16,8 @@ export interface VisDefaultEditorSetupDependencies { } export class VisDefaultEditorPlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, { visualize }: VisDefaultEditorSetupDependencies) { if (visualize) { visualize.visEditorsRegistry.registerDefault(DefaultEditorController); diff --git a/src/plugins/vis_type_markdown/public/markdown_options.test.tsx b/src/plugins/vis_type_markdown/public/markdown_options.test.tsx index f86cc44a4391..93e00bf2bada 100644 --- a/src/plugins/vis_type_markdown/public/markdown_options.test.tsx +++ b/src/plugins/vis_type_markdown/public/markdown_options.test.tsx @@ -14,14 +14,14 @@ import { MarkdownVisParams } from './types'; import { MarkdownOptions } from './markdown_options'; describe('MarkdownOptions', () => { - const props = ({ + const props = { stateParams: { fontSize: 12, markdown: 'hello from 2020 🥳', openLinksInNewTab: false, }, setValue: jest.fn(), - } as unknown) as VisEditorOptionsProps; + } as unknown as VisEditorOptionsProps; it('should match snapshot', () => { const comp = shallow(); diff --git a/src/plugins/vis_type_timeseries/common/calculate_label.test.ts b/src/plugins/vis_type_timeseries/common/calculate_label.test.ts index 1d1acb55df58..7083711246e7 100644 --- a/src/plugins/vis_type_timeseries/common/calculate_label.test.ts +++ b/src/plugins/vis_type_timeseries/common/calculate_label.test.ts @@ -36,71 +36,71 @@ describe('calculateLabel(metric, metrics)', () => { }); test('returns formatted label for pipeline aggs', () => { - const metric = ({ id: 2, type: 'derivative', field: 1 } as unknown) as Metric; - const metrics = ([ + const metric = { id: 2, type: 'derivative', field: 1 } as unknown as Metric; + const metrics = [ { id: 1, type: 'max', field: 'network.out.bytes' }, metric, - ] as unknown) as Metric[]; + ] as unknown as Metric[]; const label = calculateLabel(metric, metrics); expect(label).toEqual('Derivative of Max of network.out.bytes'); }); test('returns formatted label for derivative of percentile', () => { - const metric = ({ + const metric = { id: 2, type: 'derivative', field: '1[50.0]', - } as unknown) as Metric; - const metrics = ([ + } as unknown as Metric; + const metrics = [ { id: 1, type: 'percentile', field: 'network.out.bytes' }, metric, - ] as unknown) as Metric[]; + ] as unknown as Metric[]; const label = calculateLabel(metric, metrics); expect(label).toEqual('Derivative of Percentile of network.out.bytes (50.0)'); }); test('returns formatted label for pipeline aggs (deep)', () => { - const metric = ({ id: 3, type: 'derivative', field: 2 } as unknown) as Metric; - const metrics = ([ + const metric = { id: 3, type: 'derivative', field: 2 } as unknown as Metric; + const metrics = [ { id: 1, type: 'max', field: 'network.out.bytes' }, { id: 2, type: 'moving_average', field: 1 }, metric, - ] as unknown) as Metric[]; + ] as unknown as Metric[]; const label = calculateLabel(metric, metrics); expect(label).toEqual('Derivative of Moving Average of Max of network.out.bytes'); }); test('returns formatted label for pipeline aggs uses alias for field metric', () => { - const metric = ({ id: 2, type: 'derivative', field: 1 } as unknown) as Metric; - const metrics = ([ + const metric = { id: 2, type: 'derivative', field: 1 } as unknown as Metric; + const metrics = [ { id: 1, type: 'max', field: 'network.out.bytes', alias: 'Outbound Traffic' }, metric, - ] as unknown) as Metric[]; + ] as unknown as Metric[]; const label = calculateLabel(metric, metrics); expect(label).toEqual('Derivative of Outbound Traffic'); }); test('should throw an error if field not found', () => { - const metric = ({ id: 2, type: 'max', field: 3 } as unknown) as Metric; - const metrics = ([ + const metric = { id: 2, type: 'max', field: 3 } as unknown as Metric; + const metrics = [ { id: 1, type: 'max', field: 'network.out.bytes', alias: 'Outbound Traffic' }, metric, - ] as unknown) as Metric[]; + ] as unknown as Metric[]; const fields: SanitizedFieldType[] = [{ name: '2', label: '2', type: 'field' }]; expect(() => calculateLabel(metric, metrics, fields)).toThrowError('Field "3" not found'); }); test('should not throw an error if field not found (isThrowErrorOnFieldNotFound is false)', () => { - const metric = ({ id: 2, type: 'max', field: 3 } as unknown) as Metric; - const metrics = ([ + const metric = { id: 2, type: 'max', field: 3 } as unknown as Metric; + const metrics = [ { id: 1, type: 'max', field: 'network.out.bytes', alias: 'Outbound Traffic' }, metric, - ] as unknown) as Metric[]; + ] as unknown as Metric[]; const fields: SanitizedFieldType[] = [{ name: '2', label: '2', type: 'field' }]; expect(calculateLabel(metric, metrics, fields, false)).toBe('Max of 3'); diff --git a/src/plugins/vis_type_timeseries/common/index_patterns_utils.test.ts b/src/plugins/vis_type_timeseries/common/index_patterns_utils.test.ts index f8dd206f8f4d..cac607f7c0f9 100644 --- a/src/plugins/vis_type_timeseries/common/index_patterns_utils.test.ts +++ b/src/plugins/vis_type_timeseries/common/index_patterns_utils.test.ts @@ -60,11 +60,11 @@ describe('fetchIndexPattern', () => { beforeEach(() => { mockedIndices = []; - indexPatternsService = ({ + indexPatternsService = { getDefault: jest.fn(() => Promise.resolve({ id: 'default', title: 'index' })), get: jest.fn(() => Promise.resolve(mockedIndices[0])), find: jest.fn(() => Promise.resolve(mockedIndices || [])), - } as unknown) as IndexPatternsService; + } as unknown as IndexPatternsService; }); test('should return default index on no input value', async () => { 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 90a5633926c8..6a3f57e50279 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 @@ -40,14 +40,15 @@ const isFieldHistogram = (fields, indexPattern, field) => { export const FilterRatioAgg = (props) => { const { series, fields, panel } = props; - const handleChange = useMemo(() => createChangeHandler(props.onChange, props.model), [ - props.model, - props.onChange, - ]); + const handleChange = useMemo( + () => createChangeHandler(props.onChange, props.model), + [props.model, props.onChange] + ); const handleSelectChange = createSelectHandler(handleChange); - const handleNumeratorQueryChange = useCallback((query) => handleChange({ numerator: query }), [ - handleChange, - ]); + const handleNumeratorQueryChange = useCallback( + (query) => handleChange({ numerator: query }), + [handleChange] + ); const handleDenominatorQueryChange = useCallback( (query) => handleChange({ denominator: query }), [handleChange] diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/invalid_agg.tsx b/src/plugins/vis_type_timeseries/public/application/components/aggs/invalid_agg.tsx index 7fb4b31c2347..4fd8ea615b6c 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/invalid_agg.tsx +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/invalid_agg.tsx @@ -21,21 +21,20 @@ interface InvalidAggProps { onDelete: () => void; } -export const getInvalidAggComponent = (message: JSX.Element | string) => ( - props: InvalidAggProps -) => { - return ( - - - {message} - - - ); -}; +export const getInvalidAggComponent = + (message: JSX.Element | string) => (props: InvalidAggProps) => { + return ( + + + {message} + + + ); + }; diff --git a/src/plugins/vis_type_timeseries/public/application/components/annotation_row.tsx b/src/plugins/vis_type_timeseries/public/application/components/annotation_row.tsx index cc737561beda..379c74d0d4bb 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/annotation_row.tsx +++ b/src/plugins/vis_type_timeseries/public/application/components/annotation_row.tsx @@ -104,12 +104,11 @@ export const AnnotationRow = ({ ); const handleChange = useCallback( - (name: string) => ( - event: Array> | ChangeEvent - ) => - onChange({ - [name]: Array.isArray(event) ? event?.[0]?.value : event.target.value, - }), + (name: string) => + (event: Array> | ChangeEvent) => + onChange({ + [name]: Array.isArray(event) ? event?.[0]?.value : event.target.value, + }), [onChange] ); diff --git a/src/plugins/vis_type_timeseries/public/application/components/color_rules.test.tsx b/src/plugins/vis_type_timeseries/public/application/components/color_rules.test.tsx index 3b1356d57174..d6009a214941 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/color_rules.test.tsx +++ b/src/plugins/vis_type_timeseries/public/application/components/color_rules.test.tsx @@ -34,37 +34,37 @@ describe('src/legacy/core_plugins/metrics/public/components/color_rules.test.js' onChange: jest.fn(), }); - const defaultProps = (getColorRulesProps([ + const defaultProps = getColorRulesProps([ { gauge: null, value: 0, id: 'unique value', }, - ]) as unknown) as ColorRulesProps; + ]) as unknown as ColorRulesProps; - const emptyColorRuleProps = (getColorRulesProps([ + const emptyColorRuleProps = getColorRulesProps([ { operator: emptyRule?.method, value: emptyRule?.value, id: 'unique value', }, - ]) as unknown) as ColorRulesProps; + ]) as unknown as ColorRulesProps; - const notEmptyColorRuleProps = (getColorRulesProps([ + const notEmptyColorRuleProps = getColorRulesProps([ { operator: notEmptyRule?.method, value: notEmptyRule?.value, id: 'unique value', }, - ]) as unknown) as ColorRulesProps; + ]) as unknown as ColorRulesProps; describe('ColorRules', () => { it('should render empty
node', () => { - const emptyProps = ({ + const emptyProps = { name: 'gauge_color_rules', model: {}, onChange: jest.fn(), - } as unknown) as ColorRulesProps; + } as unknown as ColorRulesProps; const wrapper = mountWithIntl(); const isNode = wrapper.find('div').children().exists(); expect(isNode).toBeFalsy(); diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/collection_actions.test.ts b/src/plugins/vis_type_timeseries/public/application/components/lib/collection_actions.test.ts index e8b2f03b71d1..2b4f6864858f 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/collection_actions.test.ts +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/collection_actions.test.ts @@ -16,11 +16,11 @@ import { describe('collection actions', () => { test('handleChange() calls props.onChange() with updated collection', () => { const fn = jest.fn(); - const props = ({ + const props = { model: { test: [{ id: '1', title: 'foo' }] }, name: 'test', onChange: fn, - } as unknown) as CollectionActionsProps; + } as unknown as CollectionActionsProps; handleChange.call(null, props, { id: '1', type: 'bar' }); expect(fn.mock.calls.length).toEqual(1); expect(fn.mock.calls[0][0]).toEqual({ @@ -31,11 +31,11 @@ describe('collection actions', () => { test('handleAdd() calls props.onChange() with update collection', () => { const newItemFn = jest.fn(() => ({ id: '2', text: 'example' })); const fn = jest.fn(); - const props = ({ + const props = { model: { test: [{ id: '1', text: 'foo' }] }, name: 'test', onChange: fn, - } as unknown) as CollectionActionsProps; + } as unknown as CollectionActionsProps; handleAdd.call(null, props, newItemFn); expect(fn.mock.calls.length).toEqual(1); expect(newItemFn.mock.calls.length).toEqual(1); @@ -49,11 +49,11 @@ describe('collection actions', () => { test('handleDelete() calls props.onChange() with update collection', () => { const fn = jest.fn(); - const props = ({ + const props = { model: { test: [{ id: '1', title: 'foo' }] }, name: 'test', onChange: fn, - } as unknown) as CollectionActionsProps; + } as unknown as CollectionActionsProps; handleDelete.call(null, props, { id: '1' }); expect(fn.mock.calls.length).toEqual(1); expect(fn.mock.calls[0][0]).toEqual({ diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/collection_actions.ts b/src/plugins/vis_type_timeseries/public/application/components/lib/collection_actions.ts index 8307969faa97..e4cb53fd2d74 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/collection_actions.ts +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/collection_actions.ts @@ -23,21 +23,21 @@ export interface CollectionActionsProps { export function handleChange(props: CollectionActionsProps, doc: P) { const { model, name } = props; - const collection = ((model[name] as unknown) as DocType[]) || []; + const collection = (model[name] as unknown as DocType[]) || []; const part = { [name]: collection.map((row) => (row.id === doc.id ? doc : row)) }; props.onChange({ ...model, ...part }); } export function handleDelete(props: CollectionActionsProps, doc: P) { const { model, name } = props; - const collection = ((model[name] as unknown) as DocType[]) || []; + const collection = (model[name] as unknown as DocType[]) || []; const part = { [name]: collection.filter((row) => row.id !== doc.id) }; props.onChange?.({ ...model, ...part }); } export function handleAdd(props: CollectionActionsProps, fn = newFn) { const { model, name } = props; - const collection = ((model[name] as unknown) as DocType[]) || []; + const collection = (model[name] as unknown as DocType[]) || []; const part = { [name]: collection.concat([fn()]) }; props.onChange?.({ ...model, ...part }); } diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/convert_series_to_datatable.test.ts b/src/plugins/vis_type_timeseries/public/application/components/lib/convert_series_to_datatable.test.ts index ff7b2f497fd7..bffc9200c9d6 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/convert_series_to_datatable.test.ts +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/convert_series_to_datatable.test.ts @@ -158,7 +158,7 @@ describe('convert series to datatables', () => { }, ], } as TimeseriesVisParams; - const series = ([ + const series = [ { id: 'series1:0', label: 0, @@ -187,7 +187,7 @@ describe('convert series to datatables', () => { seriesId: 'series1', isSplitByTerms: true, }, - ] as unknown) as PanelData[]; + ] as unknown as PanelData[]; test('creates one table for one layer series with the correct columns', async () => { const tables = await convertSeriesToDataTable(model, series, indexPattern); expect(Object.keys(tables).sort()).toEqual([model.series[0].id].sort()); diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/create_field_formatter.test.ts b/src/plugins/vis_type_timeseries/public/application/components/lib/create_field_formatter.test.ts index 0173ca4db15a..c56c6820fff4 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/create_field_formatter.test.ts +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/create_field_formatter.test.ts @@ -12,17 +12,17 @@ import { setFieldFormats } from '../../../services'; import { FORMATS_UI_SETTINGS } from 'src/plugins/field_formats/common'; import type { CoreSetup } from 'kibana/public'; -const mockUiSettings = ({ +const mockUiSettings = { get: jest.fn((item: keyof typeof mockUiSettings) => mockUiSettings[item]), [FORMATS_UI_SETTINGS.FORMAT_BYTES_DEFAULT_PATTERN]: '0,0.[000]b', [FORMATS_UI_SETTINGS.FORMAT_NUMBER_DEFAULT_PATTERN]: '0,0.[000]', -} as unknown) as CoreSetup['uiSettings']; +} as unknown as CoreSetup['uiSettings']; describe('createFieldFormatter(fieldName, fieldFormatMap?, contextType?, hasColorRules)', () => { setFieldFormats( - getFieldFormatsRegistry(({ + getFieldFormatsRegistry({ uiSettings: mockUiSettings, - } as unknown) as CoreSetup) + } as unknown as CoreSetup) ); const value = 1234567890; const stringValue = 'some string'; diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/create_number_handler.test.ts b/src/plugins/vis_type_timeseries/public/application/components/lib/create_number_handler.test.ts index 10463be82901..ea65c0c24f6d 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/create_number_handler.test.ts +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/create_number_handler.test.ts @@ -16,10 +16,10 @@ describe('createNumberHandler()', () => { beforeEach(() => { handleChange = jest.fn(); changeHandler = createNumberHandler(handleChange); - event = ({ + event = { preventDefault: jest.fn(), target: { value: '1' }, - } as unknown) as React.ChangeEvent; + } as unknown as React.ChangeEvent; const fn = changeHandler('unit'); fn(event); }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/create_select_handler.ts b/src/plugins/vis_type_timeseries/public/application/components/lib/create_select_handler.ts index 7df7feaeb91c..98cd4ba39385 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/create_select_handler.ts +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/create_select_handler.ts @@ -10,9 +10,10 @@ import { EuiComboBoxOptionOption } from '@elastic/eui'; export type HandleChange = (partialModel: Record) => void; -export const createSelectHandler = (handleChange: HandleChange) => (name: string) => ( - selected: EuiComboBoxOptionOption[] = [] -) => - handleChange?.({ - [name]: selected[0]?.value ?? null, - }); +export const createSelectHandler = + (handleChange: HandleChange) => + (name: string) => + (selected: EuiComboBoxOptionOption[] = []) => + handleChange?.({ + [name]: selected[0]?.value ?? null, + }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/create_text_handler.test.ts b/src/plugins/vis_type_timeseries/public/application/components/lib/create_text_handler.test.ts index 367e09c5968e..d97f606f6328 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/create_text_handler.test.ts +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/create_text_handler.test.ts @@ -16,10 +16,10 @@ describe('createTextHandler()', () => { beforeEach(() => { handleChange = jest.fn(); changeHandler = createTextHandler(handleChange); - event = ({ + event = { preventDefault: jest.fn(), target: { value: 'foo' }, - } as unknown) as React.ChangeEvent; + } as unknown as React.ChangeEvent; const fn = changeHandler('axis_scale'); fn(event); }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/create_text_handler.ts b/src/plugins/vis_type_timeseries/public/application/components/lib/create_text_handler.ts index b5b6255d614d..d5893cc07651 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/create_text_handler.ts +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/create_text_handler.ts @@ -12,7 +12,7 @@ import { TimeseriesVisParams } from '../../../types'; export const createTextHandler = ( handleChange: (partialModel: Partial) => void ) => { - return (name: keyof TimeseriesVisParams, defaultValue?: string) => ( - e: React.ChangeEvent - ) => handleChange({ [name]: e.target.value ?? defaultValue }); + return (name: keyof TimeseriesVisParams, defaultValue?: string) => + (e: React.ChangeEvent) => + handleChange({ [name]: e.target.value ?? defaultValue }); }; diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/get_click_filter_data.test.ts b/src/plugins/vis_type_timeseries/public/application/components/lib/get_click_filter_data.test.ts index 2b9a1f930c15..80c84ff12581 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/get_click_filter_data.test.ts +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/get_click_filter_data.test.ts @@ -21,8 +21,7 @@ describe('getClickFilterData', () => { datum: [1620032400000, 72], }, { - key: - 'groupId{yaxis_50589930-ad98-11eb-b6f6-59011d7388b7_main_group}spec{61ca57f1-469d-11e7-af02-69e470af7417}yAccessor{1}splitAccessors{}', + key: 'groupId{yaxis_50589930-ad98-11eb-b6f6-59011d7388b7_main_group}spec{61ca57f1-469d-11e7-af02-69e470af7417}yAccessor{1}splitAccessors{}', specId: '61ca57f1-469d-11e7-af02-69e470af7417', yAccessor: 1, }, @@ -102,8 +101,7 @@ describe('getClickFilterData', () => { datum: [1619481600000, 3], }, { - key: - 'groupId{yaxis_6e0353a0-ad9b-11eb-b112-89cce8e43380_main_group}spec{61ca57f1-469d-11e7-af02-69e470af7417:1}yAccessor{1}splitAccessors{}', + key: 'groupId{yaxis_6e0353a0-ad9b-11eb-b112-89cce8e43380_main_group}spec{61ca57f1-469d-11e7-af02-69e470af7417:1}yAccessor{1}splitAccessors{}', specId: '61ca57f1-469d-11e7-af02-69e470af7417:1', }, ], diff --git a/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.test.tsx b/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.test.tsx index 8b4f5d913416..70c6df9c36ae 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.test.tsx +++ b/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.test.tsx @@ -18,11 +18,11 @@ import { PanelConfigProps } from './types'; describe('GaugePanelConfig', () => { it('call switch tab onChange={handleChange}', () => { - const props = ({ + const props = { fields: {}, model: {}, onChange: jest.fn(), - } as unknown) as PanelConfigProps; + } as unknown as PanelConfigProps; const wrapper = shallow(); wrapper.find('EuiTab').first().simulate('onClick'); @@ -30,11 +30,11 @@ describe('GaugePanelConfig', () => { }); it('call onChange={handleChange}', () => { - const props = ({ + const props = { fields: {}, model: {}, onChange: jest.fn(), - } as unknown) as PanelConfigProps; + } as unknown as PanelConfigProps; const wrapper = shallow(); wrapper.simulate('onClick'); diff --git a/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.tsx b/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.tsx index ac9dd23a2414..8dcb385df9d2 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.tsx +++ b/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.tsx @@ -68,9 +68,9 @@ export class GaugePanelConfig extends Component< this.setState({ selectedTab }); } - handleTextChange = (name: keyof TimeseriesVisParams) => ( - e: React.ChangeEvent - ) => this.props.onChange({ [name]: e.target.value }); + handleTextChange = + (name: keyof TimeseriesVisParams) => (e: React.ChangeEvent) => + this.props.onChange({ [name]: e.target.value }); render() { const { selectedTab } = this.state; diff --git a/src/plugins/vis_type_timeseries/public/application/components/panel_config/table.tsx b/src/plugins/vis_type_timeseries/public/application/components/panel_config/table.tsx index d9d5401fd131..38cbd57b0b51 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/panel_config/table.tsx +++ b/src/plugins/vis_type_timeseries/public/application/components/panel_config/table.tsx @@ -77,9 +77,9 @@ export class TablePanelConfig extends Component< }); }; - handleTextChange = (name: keyof TimeseriesVisParams) => ( - e: React.ChangeEvent - ) => this.props.onChange({ [name]: e.target.value }); + handleTextChange = + (name: keyof TimeseriesVisParams) => (e: React.ChangeEvent) => + this.props.onChange({ [name]: e.target.value }); render() { const { selectedTab } = this.state; diff --git a/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.test.tsx b/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.test.tsx index 02f28f313588..b8af2e7ef853 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.test.tsx +++ b/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.test.tsx @@ -18,13 +18,13 @@ import { PanelConfigProps } from './types'; describe('TimeseriesPanelConfig', () => { it('sets the number input to the given value', () => { - const props = ({ + const props = { fields: {}, model: { max_lines_legend: 2, }, onChange: jest.fn(), - } as unknown) as PanelConfigProps; + } as unknown as PanelConfigProps; const wrapper = shallow(); wrapper.instance().setState({ selectedTab: 'options' }); expect( @@ -33,14 +33,14 @@ describe('TimeseriesPanelConfig', () => { }); it('switches on the truncate legend switch if the prop is set to 1 ', () => { - const props = ({ + const props = { fields: {}, model: { max_lines_legend: 2, truncate_legend: 1, }, onChange: jest.fn(), - } as unknown) as PanelConfigProps; + } as unknown as PanelConfigProps; const wrapper = shallow(); wrapper.instance().setState({ selectedTab: 'options' }); expect( @@ -49,14 +49,14 @@ describe('TimeseriesPanelConfig', () => { }); it('switches off the truncate legend switch if the prop is set to 0', () => { - const props = ({ + const props = { fields: {}, model: { max_lines_legend: 2, truncate_legend: 0, }, onChange: jest.fn(), - } as unknown) as PanelConfigProps; + } as unknown as PanelConfigProps; const wrapper = shallow(); wrapper.instance().setState({ selectedTab: 'options' }); expect( @@ -65,14 +65,14 @@ describe('TimeseriesPanelConfig', () => { }); it('disables the max lines number input if the truncate legend switch is off', () => { - const props = ({ + const props = { fields: {}, model: { max_lines_legend: 2, truncate_legend: 0, }, onChange: jest.fn(), - } as unknown) as PanelConfigProps; + } as unknown as PanelConfigProps; const wrapper = shallow(); wrapper.instance().setState({ selectedTab: 'options' }); expect( diff --git a/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.tsx b/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.tsx index 25e6c7906d83..905b23a49f79 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.tsx +++ b/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.tsx @@ -119,9 +119,9 @@ export class TimeseriesPanelConfig extends Component< this.setState({ selectedTab }); } - handleTextChange = (name: keyof TimeseriesVisParams) => ( - e: React.ChangeEvent - ) => this.props.onChange({ [name]: e.target.value }); + handleTextChange = + (name: keyof TimeseriesVisParams) => (e: React.ChangeEvent) => + this.props.onChange({ [name]: e.target.value }); render() { const defaults = { diff --git a/src/plugins/vis_type_timeseries/public/application/components/panel_config/top_n.tsx b/src/plugins/vis_type_timeseries/public/application/components/panel_config/top_n.tsx index 30d65f6edd84..3cf41aa335eb 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/panel_config/top_n.tsx +++ b/src/plugins/vis_type_timeseries/public/application/components/panel_config/top_n.tsx @@ -57,9 +57,9 @@ export class TopNPanelConfig extends Component< this.setState({ selectedTab }); } - handleTextChange = (name: keyof TimeseriesVisParams) => ( - e: React.ChangeEvent - ) => this.props.onChange({ [name]: e.target.value }); + handleTextChange = + (name: keyof TimeseriesVisParams) => (e: React.ChangeEvent) => + this.props.onChange({ [name]: e.target.value }); render() { const { selectedTab } = this.state; diff --git a/src/plugins/vis_type_timeseries/public/application/lib/get_split_by_terms_color.test.ts b/src/plugins/vis_type_timeseries/public/application/lib/get_split_by_terms_color.test.ts index 1d8153164256..0a78e525796f 100644 --- a/src/plugins/vis_type_timeseries/public/application/lib/get_split_by_terms_color.test.ts +++ b/src/plugins/vis_type_timeseries/public/application/lib/get_split_by_terms_color.test.ts @@ -9,7 +9,7 @@ import { chartPluginMock } from '../../../../charts/public/mocks'; import { getSplitByTermsColor, SplitByTermsColorProps } from './get_split_by_terms_color'; const chartsRegistry = chartPluginMock.createPaletteRegistry(); -const props = ({ +const props = { seriesById: [ { id: '61ca57f1-469d-11e7-af02-69e470af7417', @@ -54,11 +54,11 @@ const props = ({ }, palettesRegistry: chartsRegistry, syncColors: false, -} as unknown) as SplitByTermsColorProps; +} as unknown as SplitByTermsColorProps; describe('getSplitByTermsColor Function', () => { it('Should return null if no palette given', () => { - const newProps = ({ ...props, seriesPalette: null } as unknown) as SplitByTermsColorProps; + const newProps = { ...props, seriesPalette: null } as unknown as SplitByTermsColorProps; const color = getSplitByTermsColor(newProps); expect(color).toEqual(null); }); @@ -83,10 +83,10 @@ describe('getSplitByTermsColor Function', () => { gradient: true, }, }; - const newProps = ({ + const newProps = { ...props, seriesPalette: gradientPalette, - } as unknown) as SplitByTermsColorProps; + } as unknown as SplitByTermsColorProps; getSplitByTermsColor(newProps); expect(spy).toHaveBeenCalledWith('custom'); }); diff --git a/src/plugins/vis_type_timeseries/public/application/visualizations/views/timeseries/index.js b/src/plugins/vis_type_timeseries/public/application/visualizations/views/timeseries/index.js index 35f0118cc852..1edaf38ef403 100644 --- a/src/plugins/vis_type_timeseries/public/application/visualizations/views/timeseries/index.js +++ b/src/plugins/vis_type_timeseries/public/application/visualizations/views/timeseries/index.js @@ -45,7 +45,10 @@ const generateAnnotationData = (values, formatter) => }), })); -const decorateFormatter = (formatter) => ({ value }) => formatter(value); +const decorateFormatter = + (formatter) => + ({ value }) => + formatter(value); /** When displaying the annotation, we must slightly shift the labels for * the x-axis so that they do not overlap the annotations. **/ diff --git a/src/plugins/vis_type_timeseries/public/services.ts b/src/plugins/vis_type_timeseries/public/services.ts index da1fd0fbdc2d..ba7ab4a25c8a 100644 --- a/src/plugins/vis_type_timeseries/public/services.ts +++ b/src/plugins/vis_type_timeseries/public/services.ts @@ -13,9 +13,8 @@ import { DataPublicPluginStart } from '../../data/public'; export const [getUISettings, setUISettings] = createGetterSetter('UISettings'); -export const [getFieldFormats, setFieldFormats] = createGetterSetter< - DataPublicPluginStart['fieldFormats'] ->('FieldFormats'); +export const [getFieldFormats, setFieldFormats] = + createGetterSetter('FieldFormats'); export const [getCoreStart, setCoreStart] = createGetterSetter('CoreStart'); diff --git a/src/plugins/vis_type_timeseries/server/index.ts b/src/plugins/vis_type_timeseries/server/index.ts index a78ddade3096..0890b37e7792 100644 --- a/src/plugins/vis_type_timeseries/server/index.ts +++ b/src/plugins/vis_type_timeseries/server/index.ts @@ -15,7 +15,7 @@ export { VisTypeTimeseriesSetup } from './plugin'; export const config: PluginConfigDescriptor = { deprecations: ({ unused, renameFromRoot }) => [ // In Kibana v7.8 plugin id was renamed from 'metrics' to 'vis_type_timeseries': - renameFromRoot('metrics.enabled', 'vis_type_timeseries.enabled', { silent: true }), + renameFromRoot('metrics.enabled', 'vis_type_timeseries.enabled'), renameFromRoot('metrics.chartResolution', 'vis_type_timeseries.chartResolution', { silent: true, }), 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 b0e85f8e44fb..ef667a574f63 100644 --- a/src/plugins/vis_type_timeseries/server/lib/get_fields.ts +++ b/src/plugins/vis_type_timeseries/server/lib/get_fields.ts @@ -29,14 +29,12 @@ export async function getFields( const fetchedIndex = await cachedIndexPatternFetcher(indexPatternString); - const { - searchStrategy, - capabilities, - } = (await framework.searchStrategyRegistry.getViableStrategy( - requestContext, - request, - fetchedIndex - ))!; + const { searchStrategy, capabilities } = + (await framework.searchStrategyRegistry.getViableStrategy( + requestContext, + request, + fetchedIndex + ))!; const fields = await searchStrategy.getFieldsForWildcard( fetchedIndex, diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/capabilities/rollup_search_capabilities.ts b/src/plugins/vis_type_timeseries/server/lib/search_strategies/capabilities/rollup_search_capabilities.ts index eafd5a0ee1cf..44b0cec4e825 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/capabilities/rollup_search_capabilities.ts +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/capabilities/rollup_search_capabilities.ts @@ -112,9 +112,11 @@ export class RollupSearchCapabilities extends DefaultSearchCapabilities { unit: parsedRollupJobInterval!.unit, }); - const { value, unit } = (isCalendarInterval(parsedRollupJobInterval!) - ? getValidCalendarInterval - : getValidFixedInterval)(); + const { value, unit } = ( + isCalendarInterval(parsedRollupJobInterval!) + ? getValidCalendarInterval + : getValidFixedInterval + )(); return `${value}${unit}`; } diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/lib/cached_index_pattern_fetcher.test.ts b/src/plugins/vis_type_timeseries/server/lib/search_strategies/lib/cached_index_pattern_fetcher.test.ts index 813b0a22c0c3..fe2c4604c48f 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/lib/cached_index_pattern_fetcher.test.ts +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/lib/cached_index_pattern_fetcher.test.ts @@ -22,11 +22,11 @@ describe('CachedIndexPatternFetcher', () => { beforeEach(() => { mockedIndices = []; - const indexPatternsService = ({ + const indexPatternsService = { getDefault: jest.fn(() => Promise.resolve({ id: 'default', title: 'index' })), get: jest.fn(() => Promise.resolve(mockedIndices[0])), find: jest.fn(() => Promise.resolve(mockedIndices || [])), - } as unknown) as IndexPatternsService; + } as unknown as IndexPatternsService; (fetchIndexPattern as jest.Mock).mockClear(); diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/search_strategies_registry.test.ts b/src/plugins/vis_type_timeseries/server/lib/search_strategies/search_strategies_registry.test.ts index 7f5f12602998..47b89178fcd4 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/search_strategies_registry.test.ts +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/search_strategies_registry.test.ts @@ -25,7 +25,7 @@ class MockSearchStrategy extends AbstractSearchStrategy { } describe('SearchStrategyRegister', () => { - const requestContext = ({ + const requestContext = { core: { uiSettings: { client: { @@ -33,7 +33,7 @@ describe('SearchStrategyRegister', () => { }, }, }, - } as unknown) as VisTypeTimeseriesRequestHandlerContext; + } as unknown as VisTypeTimeseriesRequestHandlerContext; let registry: SearchStrategyRegistry; beforeAll(() => { diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.ts b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.ts index 767d5c00d7a3..0a9b3d0047c8 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.ts +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.test.ts @@ -26,7 +26,7 @@ describe('AbstractSearchStrategy', () => { beforeEach(() => { mockedFields = []; - requestContext = ({ + requestContext = { core: { elasticsearch: { client: { @@ -40,7 +40,7 @@ describe('AbstractSearchStrategy', () => { search: { search: jest.fn().mockReturnValue(from(Promise.resolve({}))), }, - } as unknown) as VisTypeTimeseriesRequestHandlerContext; + } as unknown as VisTypeTimeseriesRequestHandlerContext; abstractSearchStrategy = new FooSearchStrategy(); }); @@ -53,10 +53,10 @@ describe('AbstractSearchStrategy', () => { test('should return fields for wildcard', async () => { const fields = await abstractSearchStrategy.getFieldsForWildcard( { indexPatternString: '', indexPattern: undefined }, - ({ + { getDefault: jest.fn(), getFieldsForWildcard: jest.fn(() => Promise.resolve(mockedFields)), - } as unknown) as IndexPatternsService, + } as unknown as IndexPatternsService, (() => Promise.resolve({}) as unknown) as CachedIndexPatternFetcher ); @@ -68,7 +68,7 @@ describe('AbstractSearchStrategy', () => { const responses = await abstractSearchStrategy.search( requestContext, - ({ + { body: { searchSession: { sessionId: '1', @@ -76,7 +76,7 @@ describe('AbstractSearchStrategy', () => { isStored: true, }, }, - } as unknown) as VisTypeTimeseriesVisDataRequest, + } as unknown as VisTypeTimeseriesVisDataRequest, searches ); diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.test.ts b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.test.ts index 3638a438ec73..393271aaa578 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.test.ts +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.test.ts @@ -13,7 +13,7 @@ import { import { DefaultSearchStrategy } from './default_search_strategy'; describe('DefaultSearchStrategy', () => { - const requestContext = ({ + const requestContext = { core: { uiSettings: { client: { @@ -21,17 +21,17 @@ describe('DefaultSearchStrategy', () => { }, }, }, - } as unknown) as VisTypeTimeseriesRequestHandlerContext; + } as unknown as VisTypeTimeseriesRequestHandlerContext; let defaultSearchStrategy: DefaultSearchStrategy; let req: VisTypeTimeseriesVisDataRequest; beforeEach(() => { - req = ({ + req = { body: { panels: [], }, - } as unknown) as VisTypeTimeseriesVisDataRequest; + } as unknown as VisTypeTimeseriesVisDataRequest; defaultSearchStrategy = new DefaultSearchStrategy(); }); diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.test.ts b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.test.ts index c798f58b0b67..85b8bcdf57b9 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.test.ts +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.test.ts @@ -38,7 +38,7 @@ jest.mock('./abstract_search_strategy', () => { describe('Rollup Search Strategy', () => { let rollupResolvedData: Promise; - const requestContext = ({ + const requestContext = { core: { elasticsearch: { client: { @@ -50,7 +50,7 @@ describe('Rollup Search Strategy', () => { }, }, }, - } as unknown) as VisTypeTimeseriesRequestHandlerContext; + } as unknown as VisTypeTimeseriesRequestHandlerContext; const indexPattern = 'indexPattern'; @@ -100,7 +100,7 @@ describe('Rollup Search Strategy', () => { const result = await rollupSearchStrategy.checkForViability( requestContext, {} as VisTypeTimeseriesVisDataRequest, - { indexPatternString: (null as unknown) as string, indexPattern: undefined } + { indexPatternString: null as unknown as string, indexPattern: undefined } ); expect(result).toEqual({ diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.ts b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.ts index 7a1d1574aa7b..f68c877cf7a3 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.ts +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.ts @@ -36,11 +36,10 @@ export class RollupSearchStrategy extends AbstractSearchStrategy { indexPattern: string ) { try { - const { - body, - } = await requestContext.core.elasticsearch.client.asCurrentUser.rollup.getRollupIndexCaps({ - index: indexPattern, - }); + const { body } = + await requestContext.core.elasticsearch.client.asCurrentUser.rollup.getRollupIndexCaps({ + index: indexPattern, + }); return body; } catch (e) { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/get_interval_and_timefield.test.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/get_interval_and_timefield.test.ts index 62220e08b7e1..45e0b410b6a6 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/get_interval_and_timefield.test.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/get_interval_and_timefield.test.ts @@ -29,11 +29,11 @@ describe('getIntervalAndTimefield(panel, series)', () => { test('returns the series interval and timefield', () => { const panel = { time_field: '@timestamp', interval: 'auto' } as Panel; - const series = ({ + const series = { override_index_pattern: true, series_interval: '1m', series_time_field: 'time', - } as unknown) as Series; + } as unknown as Series; expect(getIntervalAndTimefield(panel, index, params, series)).toEqual({ timeField: 'time', diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/handle_error_response.test.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/handle_error_response.test.ts index eeb22a3dc32c..cac84583618f 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/handle_error_response.test.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/handle_error_response.test.ts @@ -10,9 +10,9 @@ import { Panel } from '../../../common/types'; import { handleErrorResponse, ErrorResponse } from './handle_error_response'; describe('handleErrorResponse', () => { - const handleError = handleErrorResponse(({ + const handleError = handleErrorResponse({ id: 'test_panel', - } as unknown) as Panel); + } as unknown as Panel); test('should only handle errors that contain errBody', () => { expect(handleError(new Error('Test Error'))).toMatchInlineSnapshot(`Object {}`); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_bucket_size.test.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_bucket_size.test.ts index b90ae765196d..cb33588bde42 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_bucket_size.test.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_bucket_size.test.ts @@ -21,11 +21,11 @@ describe('getBucketSize', () => { }, } as VisTypeTimeseriesVisDataRequest; - const capabilities = ({ + const capabilities = { timezone: 'UTC', maxBucketsLimit: 200000, getValidTimeInterval: jest.fn((v) => v), - } as unknown) as SearchCapabilities; + } as unknown as SearchCapabilities; test('returns auto calculated buckets', () => { const result = getBucketSize(req, 'auto', capabilities, 100); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_buckets_path.test.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_buckets_path.test.ts index d5a6d25ca60f..230ddcff4ad5 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_buckets_path.test.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_buckets_path.test.ts @@ -10,7 +10,7 @@ import { getBucketsPath } from './get_buckets_path'; import type { Metric } from '../../../../common/types'; describe('getBucketsPath', () => { - const metrics = ([ + const metrics = [ { id: 1, type: 'derivative' }, { id: 2, type: 'percentile', percentiles: [{ value: '50' }] }, { id: 3, type: 'percentile', percentiles: [{ value: '20.0' }, { value: '10.0' }] }, @@ -20,7 +20,7 @@ describe('getBucketsPath', () => { { id: 7, type: 'sum_of_squares' }, { id: 8, type: 'variance' }, { id: 9, type: 'max' }, - ] as unknown) as Metric[]; + ] as unknown as Metric[]; test('return path for derivative', () => { expect(getBucketsPath('1', metrics)).toEqual('1[normalized_value]'); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_last_metric.test.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_last_metric.test.ts index c6c5e0b3c05e..47fe31589e16 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_last_metric.test.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_last_metric.test.ts @@ -11,23 +11,23 @@ import type { Series } from '../../../../common/types'; describe('getLastMetric(series)', () => { test('returns the last metric', () => { - const series = ({ + const series = { metrics: [ { id: 1, type: 'avg' }, { id: 2, type: 'moving_average' }, ], - } as unknown) as Series; + } as unknown as Series; expect(getLastMetric(series)).toEqual({ id: 2, type: 'moving_average' }); }); test('returns the last metric that not a series_agg', () => { - const series = ({ + const series = { metrics: [ { id: 1, type: 'avg' }, { id: 2, type: 'series_agg' }, ], - } as unknown) as Series; + } as unknown as Series; expect(getLastMetric(series)).toEqual({ id: 1, type: 'avg' }); }); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_timerange.test.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_timerange.test.ts index 117cb8c48952..9a71e2b60e6b 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_timerange.test.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_timerange.test.ts @@ -12,14 +12,14 @@ import { getTimerange } from './get_timerange'; describe('getTimerange(req)', () => { test('should return a moment object for to and from', () => { - const req = ({ + const req = { body: { timerange: { min: '2017-01-01T00:00:00Z', max: '2017-01-01T01:00:00Z', }, }, - } as unknown) as VisTypeTimeseriesVisDataRequest; + } as unknown as VisTypeTimeseriesVisDataRequest; const { from, to } = getTimerange(req); expect(moment.isMoment(from)).toEqual(true); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/date_histogram.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/date_histogram.ts index 27470d5868a5..5dee812dd4c5 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/date_histogram.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/date_histogram.ts @@ -16,69 +16,27 @@ import type { TableRequestProcessorsFunction, TableSearchRequestMeta } from './t const { dateHistogramInterval } = search.aggs; -export const dateHistogram: TableRequestProcessorsFunction = ({ - req, - panel, - seriesIndex, - capabilities, - uiSettings, - buildSeriesMetaParams, -}) => (next) => async (doc) => { - const barTargetUiSettings = await uiSettings.get(UI_SETTINGS.HISTOGRAM_BAR_TARGET); - const { timeField, interval } = await buildSeriesMetaParams(); - const { from, to } = getTimerange(req); - - const meta: TableSearchRequestMeta = { - timeField, - index: panel.use_kibana_indexes ? seriesIndex.indexPattern?.id : undefined, - panelId: panel.id, - }; - - const { intervalString } = getBucketSize(req, interval, capabilities, barTargetUiSettings); - const { timezone } = capabilities; - - const overwriteDateHistogramForLastBucketMode = () => { - panel.series.forEach((column) => { - const aggRoot = calculateAggRoot(doc, column); - - overwrite(doc, `${aggRoot}.timeseries.date_histogram`, { - field: timeField, - min_doc_count: 0, - time_zone: timezone, - extended_bounds: { - min: from.valueOf(), - max: to.valueOf(), - }, - ...dateHistogramInterval(intervalString), - }); - - overwrite(doc, aggRoot.replace(/\.aggs$/, '.meta'), { - ...meta, - intervalString, - }); - }); - }; - - const overwriteDateHistogramForEntireTimerangeMode = () => { - const metricAggs = getAggsByType((agg) => agg.id)[AGG_TYPE.METRIC]; - let bucketInterval; - - panel.series.forEach((column) => { - const aggRoot = calculateAggRoot(doc, column); +export const dateHistogram: TableRequestProcessorsFunction = + ({ req, panel, seriesIndex, capabilities, uiSettings, buildSeriesMetaParams }) => + (next) => + async (doc) => { + const barTargetUiSettings = await uiSettings.get(UI_SETTINGS.HISTOGRAM_BAR_TARGET); + const { timeField, interval } = await buildSeriesMetaParams(); + const { from, to } = getTimerange(req); + + const meta: TableSearchRequestMeta = { + timeField, + index: panel.use_kibana_indexes ? seriesIndex.indexPattern?.id : undefined, + panelId: panel.id, + }; + + const { intervalString } = getBucketSize(req, interval, capabilities, barTargetUiSettings); + const { timezone } = capabilities; + + const overwriteDateHistogramForLastBucketMode = () => { + panel.series.forEach((column) => { + const aggRoot = calculateAggRoot(doc, column); - // we should use auto_date_histogram only for metric aggregations and math - if ( - column.metrics.every( - (metric) => metricAggs.includes(metric.type) || metric.type === TSVB_METRIC_TYPES.MATH - ) - ) { - overwrite(doc, `${aggRoot}.timeseries.auto_date_histogram`, { - field: timeField, - buckets: 1, - }); - - bucketInterval = `${to.valueOf() - from.valueOf()}ms`; - } else { overwrite(doc, `${aggRoot}.timeseries.date_histogram`, { field: timeField, min_doc_count: 0, @@ -89,21 +47,59 @@ export const dateHistogram: TableRequestProcessorsFunction = ({ }, ...dateHistogramInterval(intervalString), }); - bucketInterval = intervalString; - } - overwrite(doc, aggRoot.replace(/\.aggs$/, '.meta'), { - ...meta, - intervalString: bucketInterval, + overwrite(doc, aggRoot.replace(/\.aggs$/, '.meta'), { + ...meta, + intervalString, + }); }); - }); - }; + }; + + const overwriteDateHistogramForEntireTimerangeMode = () => { + const metricAggs = getAggsByType((agg) => agg.id)[AGG_TYPE.METRIC]; + let bucketInterval; + + panel.series.forEach((column) => { + const aggRoot = calculateAggRoot(doc, column); + + // we should use auto_date_histogram only for metric aggregations and math + if ( + column.metrics.every( + (metric) => metricAggs.includes(metric.type) || metric.type === TSVB_METRIC_TYPES.MATH + ) + ) { + overwrite(doc, `${aggRoot}.timeseries.auto_date_histogram`, { + field: timeField, + buckets: 1, + }); + + bucketInterval = `${to.valueOf() - from.valueOf()}ms`; + } else { + overwrite(doc, `${aggRoot}.timeseries.date_histogram`, { + field: timeField, + min_doc_count: 0, + time_zone: timezone, + extended_bounds: { + min: from.valueOf(), + max: to.valueOf(), + }, + ...dateHistogramInterval(intervalString), + }); + bucketInterval = intervalString; + } + + overwrite(doc, aggRoot.replace(/\.aggs$/, '.meta'), { + ...meta, + intervalString: bucketInterval, + }); + }); + }; - if (isLastValueTimerangeMode(panel)) { - overwriteDateHistogramForLastBucketMode(); - } else { - overwriteDateHistogramForEntireTimerangeMode(); - } + if (isLastValueTimerangeMode(panel)) { + overwriteDateHistogramForLastBucketMode(); + } else { + overwriteDateHistogramForEntireTimerangeMode(); + } - return next(doc); -}; + return next(doc); + }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/metric_buckets.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/metric_buckets.ts index 511c03d60913..9adcb5f0a59e 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/metric_buckets.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/metric_buckets.ts @@ -12,27 +12,28 @@ import { calculateAggRoot } from './calculate_agg_root'; import type { TableRequestProcessorsFunction } from './types'; -export const metricBuckets: TableRequestProcessorsFunction = ({ req, panel }) => (next) => async ( - doc -) => { - panel.series.forEach((column) => { - const aggRoot = calculateAggRoot(doc, column); - column.metrics - .filter((row) => !/_bucket$/.test(row.type) && !/^series/.test(row.type)) - .forEach((metric) => { - const fn = bucketTransform[metric.type]; - if (fn) { - try { - const intervalString = get(doc, aggRoot.replace(/\.aggs$/, '.meta.intervalString')); - const bucket = fn(metric, column.metrics, intervalString); +export const metricBuckets: TableRequestProcessorsFunction = + ({ req, panel }) => + (next) => + async (doc) => { + panel.series.forEach((column) => { + const aggRoot = calculateAggRoot(doc, column); + column.metrics + .filter((row) => !/_bucket$/.test(row.type) && !/^series/.test(row.type)) + .forEach((metric) => { + const fn = bucketTransform[metric.type]; + if (fn) { + try { + const intervalString = get(doc, aggRoot.replace(/\.aggs$/, '.meta.intervalString')); + const bucket = fn(metric, column.metrics, intervalString); - overwrite(doc, `${aggRoot}.timeseries.aggs.${metric.id}`, bucket); - } catch (e) { - // meh + overwrite(doc, `${aggRoot}.timeseries.aggs.${metric.id}`, bucket); + } catch (e) { + // meh + } } - } - }); - }); + }); + }); - return next(doc); -}; + return next(doc); + }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/normalize_query.test.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/normalize_query.test.ts index 7b42af173441..3d69faed863d 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/normalize_query.test.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/normalize_query.test.ts @@ -20,7 +20,7 @@ describe('normalizeQuery', () => { const panelId = '39d49073-a924-426b-aa32-35acb40a9bb7'; const tableRequestProcessorsParams = {} as TableRequestProcessorsParams; - const next = (jest.fn((x) => x) as unknown) as ReturnType< + const next = jest.fn((x) => x) as unknown as ReturnType< ReturnType >; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/pivot.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/pivot.ts index fad14b8c439c..692d4ea23bc5 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/pivot.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/pivot.ts @@ -13,32 +13,38 @@ import { basicAggs } from '../../../../../common/basic_aggs'; import type { TableRequestProcessorsFunction } from './types'; -export const pivot: TableRequestProcessorsFunction = ({ req, panel }) => (next) => (doc) => { - const { sort } = req.body.state; +export const pivot: TableRequestProcessorsFunction = + ({ req, panel }) => + (next) => + (doc) => { + const { sort } = req.body.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 metric = series && last(series.metrics); - if (metric && metric.type === 'count') { - overwrite(doc, 'aggs.pivot.terms.order', { _count: sort.order }); - } else if (metric && series && basicAggs.includes(metric.type)) { - const sortAggKey = `${metric.id}-SORT`; - const fn = bucketTransform[metric.type]; - const bucketPath = getBucketsPath(metric.id, series.metrics).replace(metric.id, sortAggKey); - overwrite(doc, `aggs.pivot.terms.order`, { [bucketPath]: sort.order }); - overwrite(doc, `aggs.pivot.aggs`, { [sortAggKey]: fn(metric) }); - } else { - overwrite(doc, 'aggs.pivot.terms.order', { - _key: get(sort, 'order', 'asc'), - }); + 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 metric = series && last(series.metrics); + if (metric && metric.type === 'count') { + overwrite(doc, 'aggs.pivot.terms.order', { _count: sort.order }); + } else if (metric && series && basicAggs.includes(metric.type)) { + const sortAggKey = `${metric.id}-SORT`; + const fn = bucketTransform[metric.type]; + const bucketPath = getBucketsPath(metric.id, series.metrics).replace( + metric.id, + sortAggKey + ); + overwrite(doc, `aggs.pivot.terms.order`, { [bucketPath]: sort.order }); + overwrite(doc, `aggs.pivot.aggs`, { [sortAggKey]: fn(metric) }); + } else { + overwrite(doc, 'aggs.pivot.terms.order', { + _key: get(sort, 'order', 'asc'), + }); + } } + } else { + overwrite(doc, 'aggs.pivot.filter.match_all', {}); } - } else { - overwrite(doc, 'aggs.pivot.filter.match_all', {}); - } - return next(doc); -}; + return next(doc); + }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/positive_rate.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/positive_rate.ts index a9f6a7301b1a..85a817e124aa 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/positive_rate.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/positive_rate.ts @@ -15,20 +15,17 @@ import type { TableRequestProcessorsFunction } from './types'; // @ts-expect-error not typed yet import { createPositiveRate, filter } from '../series/positive_rate'; -export const positiveRate: TableRequestProcessorsFunction = ({ - req, - panel, - capabilities, - uiSettings, - buildSeriesMetaParams, -}) => (next) => async (doc) => { - const barTargetUiSettings = await uiSettings.get(UI_SETTINGS.HISTOGRAM_BAR_TARGET); - const { interval } = await buildSeriesMetaParams(); - const { intervalString } = getBucketSize(req, interval, capabilities, barTargetUiSettings); +export const positiveRate: TableRequestProcessorsFunction = + ({ req, panel, capabilities, uiSettings, buildSeriesMetaParams }) => + (next) => + async (doc) => { + const barTargetUiSettings = await uiSettings.get(UI_SETTINGS.HISTOGRAM_BAR_TARGET); + const { interval } = await buildSeriesMetaParams(); + const { intervalString } = getBucketSize(req, interval, capabilities, barTargetUiSettings); - panel.series.forEach((column) => { - const aggRoot = calculateAggRoot(doc, column); - column.metrics.filter(filter).forEach(createPositiveRate(doc, intervalString, aggRoot)); - }); - return next(doc); -}; + panel.series.forEach((column) => { + const aggRoot = calculateAggRoot(doc, column); + column.metrics.filter(filter).forEach(createPositiveRate(doc, intervalString, aggRoot)); + }); + return next(doc); + }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/query.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/query.ts index c6419ae3da15..5ddf83e1134b 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/query.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/query.ts @@ -10,43 +10,40 @@ import { getTimerange, overwrite } from '../../helpers'; import { esQuery } from '../../../../../../data/server'; import type { TableRequestProcessorsFunction } from './types'; -export const query: TableRequestProcessorsFunction = ({ - req, - panel, - esQueryConfig, - seriesIndex, - buildSeriesMetaParams, -}) => (next) => async (doc) => { - const { timeField } = await buildSeriesMetaParams(); - const { from, to } = getTimerange(req); - const indexPattern = seriesIndex.indexPattern || undefined; - - doc.size = 0; - - const queries = !panel.ignore_global_filter ? req.body.query : []; - const filters = !panel.ignore_global_filter ? req.body.filters : []; - doc.query = esQuery.buildEsQuery(indexPattern, queries, filters, esQueryConfig); - - const boolFilters: unknown[] = []; - - if (timeField) { - const timerange = { - range: { - [timeField]: { - gte: from.toISOString(), - lte: to.toISOString(), - format: 'strict_date_optional_time', +export const query: TableRequestProcessorsFunction = + ({ req, panel, esQueryConfig, seriesIndex, buildSeriesMetaParams }) => + (next) => + async (doc) => { + const { timeField } = await buildSeriesMetaParams(); + const { from, to } = getTimerange(req); + const indexPattern = seriesIndex.indexPattern || undefined; + + doc.size = 0; + + const queries = !panel.ignore_global_filter ? req.body.query : []; + const filters = !panel.ignore_global_filter ? req.body.filters : []; + doc.query = esQuery.buildEsQuery(indexPattern, queries, filters, esQueryConfig); + + const boolFilters: unknown[] = []; + + if (timeField) { + const timerange = { + range: { + [timeField]: { + gte: from.toISOString(), + lte: to.toISOString(), + format: 'strict_date_optional_time', + }, }, - }, - }; + }; - boolFilters.push(timerange); - } - if (panel.filter) { - boolFilters.push(esQuery.buildEsQuery(indexPattern, [panel.filter], [], esQueryConfig)); - } + boolFilters.push(timerange); + } + if (panel.filter) { + boolFilters.push(esQuery.buildEsQuery(indexPattern, [panel.filter], [], esQueryConfig)); + } - overwrite(doc, 'query.bool.must', boolFilters); + overwrite(doc, 'query.bool.must', boolFilters); - return next(doc); -}; + return next(doc); + }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/sibling_buckets.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/sibling_buckets.ts index af9bbdb5ce60..fd31b10dc585 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/sibling_buckets.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/sibling_buckets.ts @@ -10,29 +10,30 @@ import { overwrite, bucketTransform } from '../../helpers'; import { calculateAggRoot } from './calculate_agg_root'; import type { TableRequestProcessorsFunction } from './types'; -export const siblingBuckets: TableRequestProcessorsFunction = ({ panel }) => (next) => async ( - doc -) => { - panel.series.forEach((column) => { - const aggRoot = calculateAggRoot(doc, column); +export const siblingBuckets: TableRequestProcessorsFunction = + ({ panel }) => + (next) => + async (doc) => { + panel.series.forEach((column) => { + const aggRoot = calculateAggRoot(doc, column); - column.metrics - .filter((row) => /_bucket$/.test(row.type)) - .forEach((metric) => { - const fn = bucketTransform[metric.type]; + column.metrics + .filter((row) => /_bucket$/.test(row.type)) + .forEach((metric) => { + const fn = bucketTransform[metric.type]; - if (fn) { - try { - const intervalString = get(doc, aggRoot.replace(/\.aggs$/, '.meta.intervalString')); - const bucket = fn(metric, column.metrics, intervalString); + if (fn) { + try { + const intervalString = get(doc, aggRoot.replace(/\.aggs$/, '.meta.intervalString')); + const bucket = fn(metric, column.metrics, intervalString); - overwrite(doc, `${aggRoot}.${metric.id}`, bucket); - } catch (e) { - // meh + overwrite(doc, `${aggRoot}.${metric.id}`, bucket); + } catch (e) { + // meh + } } - } - }); - }); + }); + }); - return next(doc); -}; + return next(doc); + }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/split_by_everything.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/split_by_everything.ts index 79efa7715f75..cca86a1960fc 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/split_by_everything.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/split_by_everything.ts @@ -11,26 +11,25 @@ import { esQuery } from '../../../../../../data/server'; import type { TableRequestProcessorsFunction } from './types'; -export const splitByEverything: TableRequestProcessorsFunction = ({ - panel, - esQueryConfig, - seriesIndex, -}) => (next) => (doc) => { - const indexPattern = seriesIndex.indexPattern || undefined; +export const splitByEverything: TableRequestProcessorsFunction = + ({ panel, esQueryConfig, seriesIndex }) => + (next) => + (doc) => { + const indexPattern = seriesIndex.indexPattern || undefined; - panel.series - .filter((c) => !(c.aggregate_by && c.aggregate_function)) - .forEach((column) => { - if (column.filter) { - overwrite( - doc, - `aggs.pivot.aggs.${column.id}.filter`, - esQuery.buildEsQuery(indexPattern, [column.filter], [], esQueryConfig) - ); - } else { - overwrite(doc, `aggs.pivot.aggs.${column.id}.filter.match_all`, {}); - } - }); + panel.series + .filter((c) => !(c.aggregate_by && c.aggregate_function)) + .forEach((column) => { + if (column.filter) { + overwrite( + doc, + `aggs.pivot.aggs.${column.id}.filter`, + esQuery.buildEsQuery(indexPattern, [column.filter], [], esQueryConfig) + ); + } else { + overwrite(doc, `aggs.pivot.aggs.${column.id}.filter.match_all`, {}); + } + }); - return next(doc); -}; + return next(doc); + }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile_rank.test.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile_rank.test.ts index c1e5bd006ef6..79c3eab91c3c 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile_rank.test.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile_rank.test.ts @@ -18,7 +18,7 @@ describe('percentile_rank(resp, panel, series, meta, extractFields)', () => { panel = { time_field: 'timestamp', } as Panel; - series = ({ + series = { chart_type: 'line', stacked: 'stacked', line_width: 1, @@ -36,7 +36,7 @@ describe('percentile_rank(resp, panel, series, meta, extractFields)', () => { colors: ['#000028', '#0000FF'], }, ], - } as unknown) as Series; + } as unknown as Series; resp = { aggregations: { test: { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/drop_last_bucket.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/drop_last_bucket.ts index 3c7d46b17230..aff784ff886a 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/drop_last_bucket.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/drop_last_bucket.ts @@ -13,16 +13,17 @@ import { dropLastBucket } from '../series/drop_last_bucket'; import type { TableResponseProcessorsFunction } from './types'; -export const dropLastBucketFn: TableResponseProcessorsFunction = ({ bucket, panel, series }) => ( - next -) => (results) => { - const shouldDropLastBucket = isLastValueTimerangeMode(panel); +export const dropLastBucketFn: TableResponseProcessorsFunction = + ({ bucket, panel, series }) => + (next) => + (results) => { + const shouldDropLastBucket = isLastValueTimerangeMode(panel); - if (shouldDropLastBucket) { - const fn = dropLastBucket({ aggregations: bucket }, panel, series); + if (shouldDropLastBucket) { + const fn = dropLastBucket({ aggregations: bucket }, panel, series); - return fn(next)(results); - } + return fn(next)(results); + } - return next(results); -}; + return next(results); + }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/math.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/math.ts index b806d93a691a..b1b6c4129611 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/math.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/math.ts @@ -11,13 +11,10 @@ import { mathAgg } from '../series/math'; import type { TableResponseProcessorsFunction } from './types'; -export const math: TableResponseProcessorsFunction = ({ - bucket, - panel, - series, - meta, - extractFields, -}) => (next) => (results) => { - const mathFn = mathAgg({ aggregations: bucket }, panel, series, meta, extractFields); - return mathFn(next)(results); -}; +export const math: TableResponseProcessorsFunction = + ({ bucket, panel, series, meta, extractFields }) => + (next) => + (results) => { + const mathFn = mathAgg({ aggregations: bucket }, panel, series, meta, extractFields); + return mathFn(next)(results); + }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile.ts index 723a72f661cf..18e087255c83 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile.ts @@ -14,38 +14,35 @@ import { TSVB_METRIC_TYPES } from '../../../../../common/enums'; import type { TableResponseProcessorsFunction } from './types'; import type { PanelDataArray } from '../../../../../common/types/vis_data'; -export const percentile: TableResponseProcessorsFunction = ({ - bucket, - panel, - series, - meta, - extractFields, -}) => (next) => async (results) => { - const metric = getLastMetric(series); - - if (metric.type !== TSVB_METRIC_TYPES.PERCENTILE) { - return next(results); - } - - const fakeResp = { - aggregations: bucket, - }; - - (await getSplits(fakeResp, panel, series, meta, extractFields)).forEach((split) => { - // table allows only one percentile in a series (the last one will be chosen in case of several) - const lastPercentile = last(metric.percentiles)?.value ?? 0; - const percentileKey = toPercentileNumber(lastPercentile); - const data = split.timeseries.buckets.map((b) => [ - b.key, - b[metric.id].values[percentileKey], - ]) as PanelDataArray[]; - - results.push({ - id: split.id, - label: `${split.label} (${lastPercentile ?? 0})`, - data: data!, +export const percentile: TableResponseProcessorsFunction = + ({ bucket, panel, series, meta, extractFields }) => + (next) => + async (results) => { + const metric = getLastMetric(series); + + if (metric.type !== TSVB_METRIC_TYPES.PERCENTILE) { + return next(results); + } + + const fakeResp = { + aggregations: bucket, + }; + + (await getSplits(fakeResp, panel, series, meta, extractFields)).forEach((split) => { + // table allows only one percentile in a series (the last one will be chosen in case of several) + const lastPercentile = last(metric.percentiles)?.value ?? 0; + const percentileKey = toPercentileNumber(lastPercentile); + const data = split.timeseries.buckets.map((b) => [ + b.key, + b[metric.id].values[percentileKey], + ]) as PanelDataArray[]; + + results.push({ + id: split.id, + label: `${split.label} (${lastPercentile ?? 0})`, + data: data!, + }); }); - }); - return next(results); -}; + return next(results); + }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile_rank.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile_rank.ts index 31f9f1fd9904..b924682d9bdc 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile_rank.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile_rank.ts @@ -14,42 +14,39 @@ import { TSVB_METRIC_TYPES } from '../../../../../common/enums'; import type { TableResponseProcessorsFunction } from './types'; import type { PanelDataArray } from '../../../../../common/types/vis_data'; -export const percentileRank: TableResponseProcessorsFunction = ({ - bucket, - panel, - series, - meta, - extractFields, -}) => (next) => async (results) => { - const metric = getLastMetric(series); - - if (metric.type !== TSVB_METRIC_TYPES.PERCENTILE_RANK) { - return next(results); - } - - const fakeResp = { - aggregations: bucket, - }; - - (await getSplits(fakeResp, panel, series, meta, extractFields)).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) ?? 0; - const lastPercentileNumber = toPercentileNumber(lastRankValue); - - const data = split.timeseries.buckets.map((b) => [ - b.key, - getAggValue(b, { - ...metric, - value: lastPercentileNumber, - }), - ]) as PanelDataArray[]; - - results.push({ - data, - id: split.id, - label: `${split.label} (${lastRankValue ?? 0})`, +export const percentileRank: TableResponseProcessorsFunction = + ({ bucket, panel, series, meta, extractFields }) => + (next) => + async (results) => { + const metric = getLastMetric(series); + + if (metric.type !== TSVB_METRIC_TYPES.PERCENTILE_RANK) { + return next(results); + } + + const fakeResp = { + aggregations: bucket, + }; + + (await getSplits(fakeResp, panel, series, meta, extractFields)).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) ?? 0; + const lastPercentileNumber = toPercentileNumber(lastRankValue); + + const data = split.timeseries.buckets.map((b) => [ + b.key, + getAggValue(b, { + ...metric, + value: lastPercentileNumber, + }), + ]) as PanelDataArray[]; + + results.push({ + data, + id: split.id, + label: `${split.label} (${lastRankValue ?? 0})`, + }); }); - }); - return next(results); -}; + return next(results); + }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/series_agg.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/series_agg.ts index 3b089a2b0de8..f64daf91da12 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/series_agg.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/series_agg.ts @@ -16,31 +16,33 @@ import { SeriesAgg } from './_series_agg'; import type { TableResponseProcessorsFunction } from './types'; import type { PanelDataArray } from '../../../../../common/types/vis_data'; -export const seriesAgg: TableResponseProcessorsFunction = ({ series, meta, extractFields }) => ( - next -) => async (results) => { - if (series.aggregate_by && series.aggregate_function) { - const targetSeries: PanelDataArray[][] = []; - - // Filter out the seires with the matching metric and store them - // in targetSeries - results = results.filter((s) => { - if (s.id && s.id.split(/:/)[0] === series.id) { - targetSeries.push(s.data!); - return false; - } - return true; - }); - - const fn = SeriesAgg[series.aggregate_function]; - const data = fn(targetSeries); - const fieldsForSeries = meta.index ? await extractFields({ id: meta.index }) : []; - - results.push({ - id: `${series.id}`, - label: series.label || calculateLabel(last(series.metrics)!, series.metrics, fieldsForSeries), - data: data[0], - }); - } - return next(results); -}; +export const seriesAgg: TableResponseProcessorsFunction = + ({ series, meta, extractFields }) => + (next) => + async (results) => { + if (series.aggregate_by && series.aggregate_function) { + const targetSeries: PanelDataArray[][] = []; + + // Filter out the seires with the matching metric and store them + // in targetSeries + results = results.filter((s) => { + if (s.id && s.id.split(/:/)[0] === series.id) { + targetSeries.push(s.data!); + return false; + } + return true; + }); + + const fn = SeriesAgg[series.aggregate_function]; + const data = fn(targetSeries); + const fieldsForSeries = meta.index ? await extractFields({ id: meta.index }) : []; + + results.push({ + id: `${series.id}`, + label: + series.label || calculateLabel(last(series.metrics)!, series.metrics, fieldsForSeries), + data: data[0], + }); + } + return next(results); + }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_metric.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_metric.ts index eb537bf16f51..ffcbfb422103 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_metric.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_metric.ts @@ -11,44 +11,41 @@ import { TSVB_METRIC_TYPES } from '../../../../../common/enums'; import type { TableResponseProcessorsFunction } from './types'; -export const stdMetric: TableResponseProcessorsFunction = ({ - bucket, - panel, - series, - meta, - extractFields, -}) => (next) => async (results) => { - const metric = getLastMetric(series); - - if (metric.type === TSVB_METRIC_TYPES.STD_DEVIATION && metric.mode === 'band') { - return next(results); - } - - if ( - [TSVB_METRIC_TYPES.PERCENTILE_RANK, TSVB_METRIC_TYPES.PERCENTILE].includes( - metric.type as TSVB_METRIC_TYPES - ) - ) { - return next(results); - } +export const stdMetric: TableResponseProcessorsFunction = + ({ bucket, panel, series, meta, extractFields }) => + (next) => + async (results) => { + const metric = getLastMetric(series); + + if (metric.type === TSVB_METRIC_TYPES.STD_DEVIATION && metric.mode === 'band') { + return next(results); + } + + if ( + [TSVB_METRIC_TYPES.PERCENTILE_RANK, TSVB_METRIC_TYPES.PERCENTILE].includes( + metric.type as TSVB_METRIC_TYPES + ) + ) { + return next(results); + } + + if (/_bucket$/.test(metric.type)) { + return next(results); + } + + const fakeResp = { + aggregations: bucket, + }; + + (await getSplits(fakeResp, panel, series, meta, extractFields)).forEach((split) => { + const data = mapEmptyToZero(metric, split.timeseries.buckets); + + results.push({ + id: split.id, + label: split.label, + data, + }); + }); - if (/_bucket$/.test(metric.type)) { return next(results); - } - - const fakeResp = { - aggregations: bucket, }; - - (await getSplits(fakeResp, panel, series, meta, extractFields)).forEach((split) => { - const data = mapEmptyToZero(metric, split.timeseries.buckets); - - results.push({ - id: split.id, - label: split.label, - data, - }); - }); - - return next(results); -}; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_sibling.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_sibling.ts index 414108291a24..5c114266de39 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_sibling.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_sibling.ts @@ -11,30 +11,27 @@ import { getSplits, getLastMetric, getSiblingAggValue } from '../../helpers'; import type { TableResponseProcessorsFunction } from './types'; import type { PanelDataArray } from '../../../../../common/types/vis_data'; -export const stdSibling: TableResponseProcessorsFunction = ({ - bucket, - panel, - series, - meta, - extractFields, -}) => (next) => async (results) => { - const metric = getLastMetric(series); +export const stdSibling: TableResponseProcessorsFunction = + ({ bucket, panel, series, meta, extractFields }) => + (next) => + async (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); + if (!/_bucket$/.test(metric.type)) return next(results); + if (metric.type === 'std_deviation_bucket' && metric.mode === 'band') return next(results); - const fakeResp = { aggregations: bucket }; - (await getSplits(fakeResp, panel, series, meta, extractFields)).forEach((split) => { - const data: PanelDataArray[] = split.timeseries.buckets.map((b) => { - return [b.key, getSiblingAggValue(split, metric)]; - }); + const fakeResp = { aggregations: bucket }; + (await getSplits(fakeResp, panel, series, meta, extractFields)).forEach((split) => { + const data: PanelDataArray[] = split.timeseries.buckets.map((b) => { + return [b.key, getSiblingAggValue(split, metric)]; + }); - results.push({ - id: split.id, - label: split.label, - data, + results.push({ + id: split.id, + label: split.label, + data, + }); }); - }); - return next(results); -}; + return next(results); + }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/table/process_bucket.test.ts b/src/plugins/vis_type_timeseries/server/lib/vis_data/table/process_bucket.test.ts index 4a6c36c50599..6e0b599e57e2 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/table/process_bucket.test.ts +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/table/process_bucket.test.ts @@ -32,11 +32,11 @@ function createPanel(series: string[]) { return { type: 'table', time_field: '', - series: (series.map((seriesId) => ({ + series: series.map((seriesId) => ({ id: seriesId, metrics: [{ id: seriesId, type: 'count' }], trend_arrows: 1, - })) as unknown) as Series[], + })) as unknown as Series[], } as Panel; } diff --git a/src/plugins/vis_type_timeseries/server/usage_collector/get_usage_collector.test.ts b/src/plugins/vis_type_timeseries/server/usage_collector/get_usage_collector.test.ts index 6bb5f3bbfcad..91daf09121f1 100644 --- a/src/plugins/vis_type_timeseries/server/usage_collector/get_usage_collector.test.ts +++ b/src/plugins/vis_type_timeseries/server/usage_collector/get_usage_collector.test.ts @@ -88,7 +88,7 @@ const getMockCollectorFetchContext = ( ) => { const fetchParamsMock = createCollectorFetchContextMock(); - fetchParamsMock.soClient = ({ + fetchParamsMock.soClient = { find: jest.fn().mockResolvedValue({ saved_objects: savedObjectsByValue, }), @@ -98,14 +98,14 @@ const getMockCollectorFetchContext = ( yield savedObjects; }, }), - } as unknown) as SavedObjectsClientContract; + } as unknown as SavedObjectsClientContract; return fetchParamsMock; }; describe('Timeseries visualization usage collector', () => { test('Returns undefined when no results found (undefined)', async () => { const mockCollectorFetchContext = getMockCollectorFetchContext( - ({ saved_objects: [] } as unknown) as SavedObjectsFindResponse, + { saved_objects: [] } as unknown as SavedObjectsFindResponse, [] ); const result = await getStats(mockCollectorFetchContext.soClient); diff --git a/src/plugins/vis_type_timeseries/server/usage_collector/get_usage_collector.ts b/src/plugins/vis_type_timeseries/server/usage_collector/get_usage_collector.ts index b5b22e06b51c..a8d64afaf8ce 100644 --- a/src/plugins/vis_type_timeseries/server/usage_collector/get_usage_collector.ts +++ b/src/plugins/vis_type_timeseries/server/usage_collector/get_usage_collector.ts @@ -53,7 +53,7 @@ const doTelemetryForByValueVisualizations = async ( const byValueVisualizations = await findByValueEmbeddables(soClient, 'visualization'); for (const item of byValueVisualizations) { - telemetryUseLastValueMode((item.savedVis as unknown) as SavedVisState); + telemetryUseLastValueMode(item.savedVis as unknown as SavedVisState); } }; diff --git a/src/plugins/vis_types/metric/public/to_ast.test.ts b/src/plugins/vis_types/metric/public/to_ast.test.ts index 4931b40d597b..1c8987bfab5d 100644 --- a/src/plugins/vis_types/metric/public/to_ast.test.ts +++ b/src/plugins/vis_types/metric/public/to_ast.test.ts @@ -16,7 +16,7 @@ describe('metric vis toExpressionAst function', () => { let vis: Vis; beforeEach(() => { - vis = ({ + vis = { isHierarchical: () => false, type: {}, params: { @@ -29,7 +29,7 @@ describe('metric vis toExpressionAst function', () => { aggs: [], } as any, }, - } as unknown) as Vis; + } as unknown as Vis; }); it('without params', () => { diff --git a/src/plugins/vis_types/pie/public/editor/components/index.tsx b/src/plugins/vis_types/pie/public/editor/components/index.tsx index 5f7c744db071..1d44dc21c68e 100644 --- a/src/plugins/vis_types/pie/public/editor/components/index.tsx +++ b/src/plugins/vis_types/pie/public/editor/components/index.tsx @@ -12,15 +12,14 @@ import { PieVisParams, PieTypeProps } from '../../types'; const PieOptionsLazy = lazy(() => import('./pie')); -export const getPieOptions = ({ - showElasticChartsOptions, - palettes, - trackUiMetric, -}: PieTypeProps) => (props: VisEditorOptionsProps) => ( - -); +export const getPieOptions = + ({ showElasticChartsOptions, palettes, trackUiMetric }: PieTypeProps) => + (props: VisEditorOptionsProps) => + ( + + ); diff --git a/src/plugins/vis_types/pie/public/editor/components/pie.test.tsx b/src/plugins/vis_types/pie/public/editor/components/pie.test.tsx index ee8d0bf19eca..ac02b33b92ad 100644 --- a/src/plugins/vis_types/pie/public/editor/components/pie.test.tsx +++ b/src/plugins/vis_types/pie/public/editor/components/pie.test.tsx @@ -19,7 +19,7 @@ describe('PalettePicker', function () { let component: ReactWrapper; beforeAll(() => { - props = ({ + props = { palettes: chartPluginMock.createSetupContract().palettes, showElasticChartsOptions: true, vis: { @@ -56,7 +56,7 @@ describe('PalettePicker', function () { }, }, setValue: jest.fn(), - } as unknown) as PieOptionsProps; + } as unknown as PieOptionsProps; }); it('renders the nested legend switch for the elastic charts implementation', async () => { diff --git a/src/plugins/vis_types/pie/public/mocks.ts b/src/plugins/vis_types/pie/public/mocks.ts index f7ba4056c77e..cd57aeb54afb 100644 --- a/src/plugins/vis_types/pie/public/mocks.ts +++ b/src/plugins/vis_types/pie/public/mocks.ts @@ -265,7 +265,7 @@ export const createMockVisData = (): Datatable => { }; export const createMockPieParams = (): PieVisParams => { - return ({ + return { addLegend: true, addTooltip: true, isDonut: true, @@ -326,5 +326,5 @@ export const createMockPieParams = (): PieVisParams => { }, ], }, - } as unknown) as PieVisParams; + } as unknown as PieVisParams; }; diff --git a/src/plugins/vis_types/pie/public/pie_component.test.tsx b/src/plugins/vis_types/pie/public/pie_component.test.tsx index 846daa1e4571..85ce1947087a 100644 --- a/src/plugins/vis_types/pie/public/pie_component.test.tsx +++ b/src/plugins/vis_types/pie/public/pie_component.test.tsx @@ -123,7 +123,7 @@ describe('PieComponent', function () { }); it('renders the no results component if all the values are zero', () => { - const newVisData = ({ + const newVisData = { type: 'datatable', columns: [ { @@ -145,14 +145,14 @@ describe('PieComponent', function () { 'col-1-1': 0, }, ], - } as unknown) as Datatable; + } as unknown as Datatable; const newProps = { ...wrapperProps, visData: newVisData }; const component = mount(); expect(findTestSubject(component, 'pieVisualizationError').text()).toEqual('No results found'); }); it('renders the no results component if there are negative values', () => { - const newVisData = ({ + const newVisData = { type: 'datatable', columns: [ { @@ -174,7 +174,7 @@ describe('PieComponent', function () { 'col-1-1': -10, }, ], - } as unknown) as Datatable; + } as unknown as Datatable; const newProps = { ...wrapperProps, visData: newVisData }; const component = mount(); expect(findTestSubject(component, 'pieVisualizationError').text()).toEqual( diff --git a/src/plugins/vis_types/pie/public/pie_component.tsx b/src/plugins/vis_types/pie/public/pie_component.tsx index c41b47f9aa68..9211274a8abc 100644 --- a/src/plugins/vis_types/pie/public/pie_component.tsx +++ b/src/plugins/vis_types/pie/public/pie_component.tsx @@ -129,17 +129,18 @@ const PieComponent = (props: PieComponentProps) => { // handles legend action event data const getLegendActionEventData = useCallback( - (visData: Datatable) => (series: SeriesIdentifier): ClickTriggerEvent | null => { - const data = getFilterEventData(visData, series); + (visData: Datatable) => + (series: SeriesIdentifier): ClickTriggerEvent | null => { + const data = getFilterEventData(visData, series); - return { - name: 'filterBucket', - data: { - negate: false, - data, - }, - }; - }, + return { + name: 'filterBucket', + data: { + negate: false, + data, + }, + }; + }, [] ); @@ -207,10 +208,10 @@ const PieComponent = (props: PieComponentProps) => { }, }); - const { bucketColumns, metricColumn } = useMemo(() => getColumns(visParams, visData), [ - visData, - visParams, - ]); + const { bucketColumns, metricColumn } = useMemo( + () => getColumns(visParams, visData), + [visData, visParams] + ); const layers = useMemo( () => @@ -233,11 +234,10 @@ const PieComponent = (props: PieComponentProps) => { syncColors, ] ); - const config = useMemo(() => getConfig(visParams, chartTheme, dimensions), [ - chartTheme, - visParams, - dimensions, - ]); + const config = useMemo( + () => getConfig(visParams, chartTheme, dimensions), + [chartTheme, visParams, dimensions] + ); const tooltip: TooltipProps = { type: visParams.addTooltip ? TooltipType.Follow : TooltipType.None, }; @@ -288,10 +288,10 @@ const PieComponent = (props: PieComponentProps) => { * Checks whether data have all zero values. * If so, the no data container is loaded. */ - const isAllZeros = useMemo(() => visData.rows.every((row) => row[metricColumn.id] === 0), [ - visData.rows, - metricColumn, - ]); + const isAllZeros = useMemo( + () => visData.rows.every((row) => row[metricColumn.id] === 0), + [visData.rows, metricColumn] + ); /** * Checks whether data have negative values. diff --git a/src/plugins/vis_types/pie/public/utils/get_color_picker.test.tsx b/src/plugins/vis_types/pie/public/utils/get_color_picker.test.tsx index bb4cbd8c08ae..c129fdd356a6 100644 --- a/src/plugins/vis_types/pie/public/utils/get_color_picker.test.tsx +++ b/src/plugins/vis_types/pie/public/utils/get_color_picker.test.tsx @@ -30,14 +30,14 @@ jest.mock('@elastic/charts', () => { describe('getColorPicker', function () { const mockState = new Map(); - const uiState = ({ + const uiState = { get: jest .fn() .mockImplementation((key, fallback) => (mockState.has(key) ? mockState.get(key) : fallback)), set: jest.fn().mockImplementation((key, value) => mockState.set(key, value)), emit: jest.fn(), setSilent: jest.fn(), - } as unknown) as PersistedState; + } as unknown as PersistedState; let wrapperProps: LegendColorPickerProps; const Component: ComponentType = getColorPicker( diff --git a/src/plugins/vis_types/pie/public/utils/get_color_picker.tsx b/src/plugins/vis_types/pie/public/utils/get_color_picker.tsx index 68daa7bb82df..6bfd231aa75a 100644 --- a/src/plugins/vis_types/pie/public/utils/get_color_picker.tsx +++ b/src/plugins/vis_types/pie/public/utils/get_color_picker.tsx @@ -48,74 +48,71 @@ function isOnInnerLayer( return data.find((d) => firstBucket.id && d[firstBucket.id] === seriesKey); } -export const getColorPicker = ( - legendPosition: Position, - setColor: (newColor: string | null, seriesKey: string | number) => void, - bucketColumns: Array>, - palette: string, - data: DatatableRow[], - uiState: PersistedState, - distinctColors: boolean -): LegendColorPicker => ({ - anchor, - color, - onClose, - onChange, - seriesIdentifiers: [seriesIdentifier], -}) => { - const seriesName = seriesIdentifier.key; - const overwriteColors: Record = uiState?.get('vis.colors', {}) ?? {}; - const colorIsOverwritten = Object.keys(overwriteColors).includes(seriesName.toString()); - let keyDownEventOn = false; - const handleChange = (newColor: string | null) => { - if (newColor) { - onChange(newColor); - } - setColor(newColor, seriesName); - // close the popover if no color is applied or the user has clicked a color - if (!newColor || !keyDownEventOn) { - onClose(); - } - }; +export const getColorPicker = + ( + legendPosition: Position, + setColor: (newColor: string | null, seriesKey: string | number) => void, + bucketColumns: Array>, + palette: string, + data: DatatableRow[], + uiState: PersistedState, + distinctColors: boolean + ): LegendColorPicker => + ({ anchor, color, onClose, onChange, seriesIdentifiers: [seriesIdentifier] }) => { + const seriesName = seriesIdentifier.key; + const overwriteColors: Record = uiState?.get('vis.colors', {}) ?? {}; + const colorIsOverwritten = Object.keys(overwriteColors).includes(seriesName.toString()); + let keyDownEventOn = false; + const handleChange = (newColor: string | null) => { + if (newColor) { + onChange(newColor); + } + setColor(newColor, seriesName); + // close the popover if no color is applied or the user has clicked a color + if (!newColor || !keyDownEventOn) { + onClose(); + } + }; + + const onKeyDown = (e: React.KeyboardEvent) => { + if (e.keyCode === KEY_CODE_ENTER) { + onClose?.(); + } + keyDownEventOn = true; + }; - const onKeyDown = (e: React.KeyboardEvent) => { - if (e.keyCode === KEY_CODE_ENTER) { + const handleOutsideClick = useCallback(() => { onClose?.(); + }, [onClose]); + + if (!distinctColors) { + const enablePicker = + isOnInnerLayer(bucketColumns[0], data, seriesName) || !bucketColumns[0].id; + if (!enablePicker) return null; } - keyDownEventOn = true; + const hexColor = new Color(color).hex(); + return ( + + + + + + ); }; - - const handleOutsideClick = useCallback(() => { - onClose?.(); - }, [onClose]); - - if (!distinctColors) { - const enablePicker = isOnInnerLayer(bucketColumns[0], data, seriesName) || !bucketColumns[0].id; - if (!enablePicker) return null; - } - const hexColor = new Color(color).hex(); - return ( - - - - - - ); -}; diff --git a/src/plugins/vis_types/pie/public/utils/get_columns.test.ts b/src/plugins/vis_types/pie/public/utils/get_columns.test.ts index 9f64266ed0e0..7752f4300dbb 100644 --- a/src/plugins/vis_types/pie/public/utils/get_columns.test.ts +++ b/src/plugins/vis_types/pie/public/utils/get_columns.test.ts @@ -130,7 +130,7 @@ describe('getColumns', () => { }); it('should return the first data column if no buckets specified', () => { - const visParamsOnlyMetric = ({ + const visParamsOnlyMetric = { addLegend: true, addTooltip: true, isDonut: true, @@ -162,7 +162,7 @@ describe('getColumns', () => { aggType: 'count', }, }, - } as unknown) as PieVisParams; + } as unknown as PieVisParams; const { metricColumn } = getColumns(visParamsOnlyMetric, visData); expect(metricColumn).toEqual({ id: 'col-1-1', @@ -187,7 +187,7 @@ describe('getColumns', () => { }); it('should return an object with the name of the metric if no buckets specified', () => { - const visParamsOnlyMetric = ({ + const visParamsOnlyMetric = { addLegend: true, addTooltip: true, isDonut: true, @@ -217,7 +217,7 @@ describe('getColumns', () => { aggType: 'count', }, }, - } as unknown) as PieVisParams; + } as unknown as PieVisParams; const { bucketColumns, metricColumn } = getColumns(visParamsOnlyMetric, visData); expect(bucketColumns).toEqual([{ name: metricColumn.name }]); }); diff --git a/src/plugins/vis_types/pie/public/utils/get_layers.test.ts b/src/plugins/vis_types/pie/public/utils/get_layers.test.ts index 859d0daf07a0..39c3ccfc45a9 100644 --- a/src/plugins/vis_types/pie/public/utils/get_layers.test.ts +++ b/src/plugins/vis_types/pie/public/utils/get_layers.test.ts @@ -22,13 +22,13 @@ interface RangeProps { lt: number; } -dataMock.fieldFormats = ({ +dataMock.fieldFormats = { deserialize: jest.fn(() => ({ convert: jest.fn((s: RangeProps) => { return `≥ ${s.gte} and < ${s.lt}`; }), })), -} as unknown) as DataPublicPluginStart['fieldFormats']; +} as unknown as DataPublicPluginStart['fieldFormats']; export const getPaletteRegistry = () => { const mockPalette1: jest.Mocked = { @@ -58,7 +58,7 @@ export const getPaletteRegistry = () => { describe('computeColor', () => { it('should return the correct color based on the parent sortIndex', () => { - const d = ({ + const d = { dataName: 'ES-Air', depth: 1, sortIndex: 0, @@ -67,7 +67,7 @@ describe('computeColor', () => { depth: 0, sortIndex: 0, }, - } as unknown) as ShapeTreeNode; + } as unknown as ShapeTreeNode; const color = computeColor( d, false, @@ -83,7 +83,7 @@ describe('computeColor', () => { }); it('slices with the same label should have the same color for small multiples', () => { - const d = ({ + const d = { dataName: 'ES-Air', depth: 1, sortIndex: 0, @@ -92,7 +92,7 @@ describe('computeColor', () => { depth: 0, sortIndex: 0, }, - } as unknown) as ShapeTreeNode; + } as unknown as ShapeTreeNode; const color = computeColor( d, true, @@ -107,7 +107,7 @@ describe('computeColor', () => { expect(color).toEqual('color3'); }); it('returns the overwriteColor if exists', () => { - const d = ({ + const d = { dataName: 'ES-Air', depth: 1, sortIndex: 0, @@ -116,7 +116,7 @@ describe('computeColor', () => { depth: 0, sortIndex: 0, }, - } as unknown) as ShapeTreeNode; + } as unknown as ShapeTreeNode; const color = computeColor( d, true, @@ -132,7 +132,7 @@ describe('computeColor', () => { }); it('returns the overwriteColor for older visualizations with formatted values', () => { - const d = ({ + const d = { dataName: { gte: 1000, lt: 2000, @@ -157,7 +157,7 @@ describe('computeColor', () => { depth: 0, sortIndex: 0, }, - } as unknown) as ShapeTreeNode; + } as unknown as ShapeTreeNode; const visParamsNew = { ...visParams, distinctColors: true, diff --git a/src/plugins/vis_types/pie/public/utils/get_split_dimension_accessor.ts b/src/plugins/vis_types/pie/public/utils/get_split_dimension_accessor.ts index 4f30d4f8b3cc..b2ca7560b63c 100644 --- a/src/plugins/vis_types/pie/public/utils/get_split_dimension_accessor.ts +++ b/src/plugins/vis_types/pie/public/utils/get_split_dimension_accessor.ts @@ -10,22 +10,21 @@ import { DatatableColumn } from '../../../../expressions/public'; import type { FieldFormatsStart } from '../../../../field_formats/public'; import { Dimension } from '../types'; -export const getSplitDimensionAccessor = ( - fieldFormats: FieldFormatsStart, - columns: DatatableColumn[] -) => (splitDimension: Dimension): AccessorFn => { - const formatter = fieldFormats.deserialize(splitDimension.format); - const splitChartColumn = columns[splitDimension.accessor]; - const accessor = splitChartColumn.id; +export const getSplitDimensionAccessor = + (fieldFormats: FieldFormatsStart, columns: DatatableColumn[]) => + (splitDimension: Dimension): AccessorFn => { + const formatter = fieldFormats.deserialize(splitDimension.format); + const splitChartColumn = columns[splitDimension.accessor]; + const accessor = splitChartColumn.id; - const fn: AccessorFn = (d) => { - const v = d[accessor]; - if (v === undefined) { - return; - } - const f = formatter.convert(v); - return f; - }; + const fn: AccessorFn = (d) => { + const v = d[accessor]; + if (v === undefined) { + return; + } + const f = formatter.convert(v); + return f; + }; - return fn; -}; + return fn; + }; diff --git a/src/plugins/vis_types/table/config.ts b/src/plugins/vis_types/table/config.ts index b831d26854c3..c47a14395c3b 100644 --- a/src/plugins/vis_types/table/config.ts +++ b/src/plugins/vis_types/table/config.ts @@ -10,6 +10,8 @@ import { schema, TypeOf } from '@kbn/config-schema'; export const configSchema = schema.object({ enabled: schema.boolean({ defaultValue: true }), + /** @deprecated **/ + legacyVisEnabled: schema.boolean({ defaultValue: false }), }); export type ConfigSchema = TypeOf; diff --git a/src/plugins/vis_types/table/public/components/table_vis_basic.tsx b/src/plugins/vis_types/table/public/components/table_vis_basic.tsx index 572efd90e61a..e627b9e7f92f 100644 --- a/src/plugins/vis_types/table/public/components/table_vis_basic.tsx +++ b/src/plugins/vis_types/table/public/components/table_vis_basic.tsx @@ -46,10 +46,10 @@ export const TableVisBasic = memo( ); // renderCellValue is a component which renders a cell based on column and row indexes - const renderCellValue = useMemo(() => createTableVisCell(sortedRows, formattedColumns), [ - formattedColumns, - sortedRows, - ]); + const renderCellValue = useMemo( + () => createTableVisCell(sortedRows, formattedColumns), + [formattedColumns, sortedRows] + ); // Columns config const gridColumns = createGridColumns( diff --git a/src/plugins/vis_types/table/public/components/table_vis_cell.test.tsx b/src/plugins/vis_types/table/public/components/table_vis_cell.test.tsx index 322ceacbe002..46dc6d55a2fa 100644 --- a/src/plugins/vis_types/table/public/components/table_vis_cell.test.tsx +++ b/src/plugins/vis_types/table/public/components/table_vis_cell.test.tsx @@ -15,13 +15,13 @@ import { FormattedColumns } from '../types'; describe('table vis cell', () => { it('should return a cell component with data in scope', () => { const rows = [{ first: 1, second: 2 }]; - const formattedColumns = ({ + const formattedColumns = { second: { formatter: { convert: jest.fn(), }, }, - } as unknown) as FormattedColumns; + } as unknown as FormattedColumns; const Cell = createTableVisCell(rows, formattedColumns); const cellProps = { rowIndex: 0, diff --git a/src/plugins/vis_types/table/public/components/table_vis_cell.tsx b/src/plugins/vis_types/table/public/components/table_vis_cell.tsx index 16a4ccf568a2..9749cdcb5740 100644 --- a/src/plugins/vis_types/table/public/components/table_vis_cell.tsx +++ b/src/plugins/vis_types/table/public/components/table_vis_cell.tsx @@ -12,26 +12,25 @@ import { EuiDataGridCellValueElementProps } from '@elastic/eui'; import { DatatableRow } from 'src/plugins/expressions'; import { FormattedColumns } from '../types'; -export const createTableVisCell = (rows: DatatableRow[], formattedColumns: FormattedColumns) => ({ - rowIndex, - columnId, -}: EuiDataGridCellValueElementProps) => { - const rowValue = rows[rowIndex][columnId]; - const column = formattedColumns[columnId]; - const content = column.formatter.convert(rowValue, 'html'); +export const createTableVisCell = + (rows: DatatableRow[], formattedColumns: FormattedColumns) => + ({ rowIndex, columnId }: EuiDataGridCellValueElementProps) => { + const rowValue = rows[rowIndex][columnId]; + const column = formattedColumns[columnId]; + const content = column.formatter.convert(rowValue, 'html'); - const cellContent = ( -
- ); + const cellContent = ( +
+ ); - return cellContent; -}; + return cellContent; + }; diff --git a/src/plugins/vis_types/table/public/components/table_vis_columns.tsx b/src/plugins/vis_types/table/public/components/table_vis_columns.tsx index f994e71f9fcb..23918e7df3f8 100644 --- a/src/plugins/vis_types/table/public/components/table_vis_columns.tsx +++ b/src/plugins/vis_types/table/public/components/table_vis_columns.tsx @@ -51,115 +51,113 @@ export const createGridColumns = ( }); }; - return columns.map( - (col, colIndex): EuiDataGridColumn => { - const formattedColumn = formattedColumns[col.id]; - const cellActions = formattedColumn.filterable - ? [ - ({ rowIndex, columnId, Component, closePopover }: EuiDataGridColumnCellActionProps) => { - const rowValue = rows[rowIndex][columnId]; - const contentsIsDefined = rowValue !== null && rowValue !== undefined; - const cellContent = formattedColumn.formatter.convert(rowValue); + return columns.map((col, colIndex): EuiDataGridColumn => { + const formattedColumn = formattedColumns[col.id]; + const cellActions = formattedColumn.filterable + ? [ + ({ rowIndex, columnId, Component, closePopover }: EuiDataGridColumnCellActionProps) => { + const rowValue = rows[rowIndex][columnId]; + const contentsIsDefined = rowValue !== null && rowValue !== undefined; + const cellContent = formattedColumn.formatter.convert(rowValue); - const filterForText = i18n.translate( - 'visTypeTable.tableCellFilter.filterForValueText', - { - defaultMessage: 'Filter for value', - } - ); - const filterForAriaLabel = i18n.translate( - 'visTypeTable.tableCellFilter.filterForValueAriaLabel', - { - defaultMessage: 'Filter for value: {cellContent}', - values: { - cellContent, - }, - } - ); + const filterForText = i18n.translate( + 'visTypeTable.tableCellFilter.filterForValueText', + { + defaultMessage: 'Filter for value', + } + ); + const filterForAriaLabel = i18n.translate( + 'visTypeTable.tableCellFilter.filterForValueAriaLabel', + { + defaultMessage: 'Filter for value: {cellContent}', + values: { + cellContent, + }, + } + ); - return ( - contentsIsDefined && ( - { - onFilterClick({ row: rowIndex, column: colIndex, value: rowValue }, false); - closePopover(); - }} - iconType="plusInCircle" - > - {filterForText} - - ) - ); - }, - ({ rowIndex, columnId, Component, closePopover }: EuiDataGridColumnCellActionProps) => { - const rowValue = rows[rowIndex][columnId]; - const contentsIsDefined = rowValue !== null && rowValue !== undefined; - const cellContent = formattedColumn.formatter.convert(rowValue); + return ( + contentsIsDefined && ( + { + onFilterClick({ row: rowIndex, column: colIndex, value: rowValue }, false); + closePopover(); + }} + iconType="plusInCircle" + > + {filterForText} + + ) + ); + }, + ({ rowIndex, columnId, Component, closePopover }: EuiDataGridColumnCellActionProps) => { + const rowValue = rows[rowIndex][columnId]; + const contentsIsDefined = rowValue !== null && rowValue !== undefined; + const cellContent = formattedColumn.formatter.convert(rowValue); - const filterOutText = i18n.translate( - 'visTypeTable.tableCellFilter.filterOutValueText', - { - defaultMessage: 'Filter out value', - } - ); - const filterOutAriaLabel = i18n.translate( - 'visTypeTable.tableCellFilter.filterOutValueAriaLabel', - { - defaultMessage: 'Filter out value: {cellContent}', - values: { - cellContent, - }, - } - ); + const filterOutText = i18n.translate( + 'visTypeTable.tableCellFilter.filterOutValueText', + { + defaultMessage: 'Filter out value', + } + ); + const filterOutAriaLabel = i18n.translate( + 'visTypeTable.tableCellFilter.filterOutValueAriaLabel', + { + defaultMessage: 'Filter out value: {cellContent}', + values: { + cellContent, + }, + } + ); - return ( - contentsIsDefined && ( - { - onFilterClick({ row: rowIndex, column: colIndex, value: rowValue }, true); - closePopover(); - }} - iconType="minusInCircle" - > - {filterOutText} - - ) - ); - }, - ] - : undefined; - - const initialWidth = columnsWidth.find((c) => c.colIndex === colIndex); - const column: EuiDataGridColumn = { - id: col.id, - display: col.name, - displayAsText: col.name, - actions: { - showHide: false, - showMoveLeft: false, - showMoveRight: false, - showSortAsc: { - label: i18n.translate('visTypeTable.sort.ascLabel', { - defaultMessage: 'Sort asc', - }), - }, - showSortDesc: { - label: i18n.translate('visTypeTable.sort.descLabel', { - defaultMessage: 'Sort desc', - }), + return ( + contentsIsDefined && ( + { + onFilterClick({ row: rowIndex, column: colIndex, value: rowValue }, true); + closePopover(); + }} + iconType="minusInCircle" + > + {filterOutText} + + ) + ); }, - }, - cellActions, - }; + ] + : undefined; - if (initialWidth) { - column.initialWidth = initialWidth.width; - } + const initialWidth = columnsWidth.find((c) => c.colIndex === colIndex); + const column: EuiDataGridColumn = { + id: col.id, + display: col.name, + displayAsText: col.name, + actions: { + showHide: false, + showMoveLeft: false, + showMoveRight: false, + showSortAsc: { + label: i18n.translate('visTypeTable.sort.ascLabel', { + defaultMessage: 'Sort asc', + }), + }, + showSortDesc: { + label: i18n.translate('visTypeTable.sort.descLabel', { + defaultMessage: 'Sort desc', + }), + }, + }, + cellActions, + }; - return column; + if (initialWidth) { + column.initialWidth = initialWidth.width; } - ); + + return column; + }); }; diff --git a/src/plugins/vis_types/table/public/components/table_visualization.test.tsx b/src/plugins/vis_types/table/public/components/table_visualization.test.tsx index 0de7e8c15105..a8c0ae250737 100644 --- a/src/plugins/vis_types/table/public/components/table_visualization.test.tsx +++ b/src/plugins/vis_types/table/public/components/table_visualization.test.tsx @@ -20,11 +20,11 @@ import { useUiState } from '../utils'; describe('TableVisualizationComponent', () => { const coreStartMock = coreMock.createStart(); - const handlers = ({ + const handlers = { done: jest.fn(), uiState: 'uiState', event: 'event', - } as unknown) as IInterpreterRenderHandlers; + } as unknown as IInterpreterRenderHandlers; const visData: TableVisData = { table: { columns: [], @@ -33,7 +33,7 @@ describe('TableVisualizationComponent', () => { }, tables: [], }; - const visConfig = ({} as unknown) as TableVisConfig; + const visConfig = {} as unknown as TableVisConfig; it('should render the basic table', () => { const comp = shallow( diff --git a/src/plugins/vis_types/table/public/plugin.ts b/src/plugins/vis_types/table/public/plugin.ts index fa02550f5048..e36b4a14c3a5 100644 --- a/src/plugins/vis_types/table/public/plugin.ts +++ b/src/plugins/vis_types/table/public/plugin.ts @@ -29,7 +29,8 @@ export interface TablePluginStartDependencies { /** @internal */ export class TableVisPlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, deps: TablePluginSetupDependencies) { registerTableVis(core, deps); } diff --git a/src/plugins/vis_types/table/public/services.ts b/src/plugins/vis_types/table/public/services.ts index d4d83c9e92c6..e1e6daf3615e 100644 --- a/src/plugins/vis_types/table/public/services.ts +++ b/src/plugins/vis_types/table/public/services.ts @@ -9,6 +9,5 @@ import { createGetterSetter } from '../../../kibana_utils/public'; import { DataPublicPluginStart } from '../../../data/public'; -export const [getFormatService, setFormatService] = createGetterSetter< - DataPublicPluginStart['fieldFormats'] ->('table data.fieldFormats'); +export const [getFormatService, setFormatService] = + createGetterSetter('table data.fieldFormats'); diff --git a/src/plugins/vis_types/table/server/index.ts b/src/plugins/vis_types/table/server/index.ts index b98fdd9c445d..eed1134f3ff4 100644 --- a/src/plugins/vis_types/table/server/index.ts +++ b/src/plugins/vis_types/table/server/index.ts @@ -14,8 +14,10 @@ import { registerVisTypeTableUsageCollector } from './usage_collector'; export const config: PluginConfigDescriptor = { schema: configSchema, - deprecations: ({ renameFromRoot }) => [ + deprecations: ({ renameFromRoot, unused }) => [ renameFromRoot('table_vis.enabled', 'vis_type_table.enabled'), + // Unused property which should be removed after releasing Kibana v8.0: + unused('legacyVisEnabled'), ], }; diff --git a/src/plugins/vis_types/table/server/usage_collector/get_stats.test.ts b/src/plugins/vis_types/table/server/usage_collector/get_stats.test.ts index 4c91def40300..85912aa4d5bd 100644 --- a/src/plugins/vis_types/table/server/usage_collector/get_stats.test.ts +++ b/src/plugins/vis_types/table/server/usage_collector/get_stats.test.ts @@ -41,14 +41,14 @@ const mockVisualizations = { }; describe('vis_type_table getStats', () => { - const mockSoClient = ({ + const mockSoClient = { createPointInTimeFinder: jest.fn().mockResolvedValue({ close: jest.fn(), find: function* asyncGenerator() { yield mockVisualizations; }, }), - } as unknown) as SavedObjectsClientContract; + } as unknown as SavedObjectsClientContract; test('Returns stats from saved objects for table vis only', async () => { const result = await getStats(mockSoClient); diff --git a/src/plugins/vis_types/tagcloud/public/__snapshots__/to_ast.test.ts.snap b/src/plugins/vis_types/tagcloud/public/__snapshots__/to_ast.test.ts.snap index 9e4c3071db8d..3f50cdf559e1 100644 --- a/src/plugins/vis_types/tagcloud/public/__snapshots__/to_ast.test.ts.snap +++ b/src/plugins/vis_types/tagcloud/public/__snapshots__/to_ast.test.ts.snap @@ -85,7 +85,20 @@ Object { "single", ], "palette": Array [ - "default", + Object { + "chain": Array [ + Object { + "arguments": Object { + "name": Array [ + "default", + ], + }, + "function": "system_palette", + "type": "function", + }, + ], + "type": "expression", + }, ], "scale": Array [ "linear", @@ -187,7 +200,20 @@ Object { "single", ], "palette": Array [ - "default", + Object { + "chain": Array [ + Object { + "arguments": Object { + "name": Array [ + "default", + ], + }, + "function": "system_palette", + "type": "function", + }, + ], + "type": "expression", + }, ], "scale": Array [ "linear", @@ -279,6 +305,18 @@ Object { "type": "expression", }, ], + "palette": Array [ + Object { + "chain": Array [ + Object { + "arguments": Object {}, + "function": "system_palette", + "type": "function", + }, + ], + "type": "expression", + }, + ], "showLabel": Array [ false, ], diff --git a/src/plugins/vis_types/tagcloud/public/components/get_tag_cloud_options.tsx b/src/plugins/vis_types/tagcloud/public/components/get_tag_cloud_options.tsx index 82663bbf7070..bb5af48bf007 100644 --- a/src/plugins/vis_types/tagcloud/public/components/get_tag_cloud_options.tsx +++ b/src/plugins/vis_types/tagcloud/public/components/get_tag_cloud_options.tsx @@ -12,6 +12,7 @@ import { TagCloudVisParams, TagCloudTypeProps } from '../types'; const TagCloudOptionsLazy = lazy(() => import('./tag_cloud_options')); -export const getTagCloudOptions = ({ palettes }: TagCloudTypeProps) => ( - props: VisEditorOptionsProps -) => ; +export const getTagCloudOptions = + ({ palettes }: TagCloudTypeProps) => + (props: VisEditorOptionsProps) => + ; diff --git a/src/plugins/vis_types/tagcloud/public/tag_cloud_type.ts b/src/plugins/vis_types/tagcloud/public/tag_cloud_type.ts index a193a7fecc1f..daad73c08298 100644 --- a/src/plugins/vis_types/tagcloud/public/tag_cloud_type.ts +++ b/src/plugins/vis_types/tagcloud/public/tag_cloud_type.ts @@ -14,66 +14,68 @@ import { getTagCloudOptions } from './components/get_tag_cloud_options'; import { toExpressionAst } from './to_ast'; import { TagCloudVisDependencies } from './plugin'; -export const getTagCloudVisTypeDefinition = ({ palettes }: TagCloudVisDependencies) => ({ - name: 'tagcloud', - title: i18n.translate('visTypeTagCloud.vis.tagCloudTitle', { defaultMessage: 'Tag cloud' }), - icon: 'visTagCloud', - getSupportedTriggers: () => { - return [VIS_EVENT_TO_TRIGGER.filter]; - }, - description: i18n.translate('visTypeTagCloud.vis.tagCloudDescription', { - defaultMessage: 'Display word frequency with font size.', - }), - visConfig: { - defaults: { - scale: 'linear', - orientation: 'single', - minFontSize: 18, - maxFontSize: 72, - showLabel: true, - palette: { - name: 'default', - type: 'palette', - }, +export const getTagCloudVisTypeDefinition = ({ palettes }: TagCloudVisDependencies) => { + return { + name: 'tagcloud', + title: i18n.translate('visTypeTagCloud.vis.tagCloudTitle', { defaultMessage: 'Tag cloud' }), + icon: 'visTagCloud', + getSupportedTriggers: () => { + return [VIS_EVENT_TO_TRIGGER.filter]; }, - }, - toExpressionAst, - editorConfig: { - optionsTemplate: getTagCloudOptions({ - palettes, + description: i18n.translate('visTypeTagCloud.vis.tagCloudDescription', { + defaultMessage: 'Display word frequency with font size.', }), - schemas: [ - { - group: AggGroupNames.Metrics, - name: 'metric', - title: i18n.translate('visTypeTagCloud.vis.schemas.metricTitle', { - defaultMessage: 'Tag size', - }), - min: 1, - max: 1, - aggFilter: [ - '!std_dev', - '!percentiles', - '!percentile_ranks', - '!derivative', - '!geo_bounds', - '!geo_centroid', - '!filtered_metric', - '!single_percentile', - ], - defaults: [{ schema: 'metric', type: 'count' }], - }, - { - group: AggGroupNames.Buckets, - name: 'segment', - title: i18n.translate('visTypeTagCloud.vis.schemas.segmentTitle', { - defaultMessage: 'Tags', - }), - min: 1, - max: 1, - aggFilter: ['terms', 'significant_terms'], + visConfig: { + defaults: { + scale: 'linear', + orientation: 'single', + minFontSize: 18, + maxFontSize: 72, + showLabel: true, + palette: { + name: 'default', + type: 'palette', + }, }, - ], - }, - requiresSearch: true, -}); + }, + toExpressionAst, + editorConfig: { + optionsTemplate: getTagCloudOptions({ + palettes, + }), + schemas: [ + { + group: AggGroupNames.Metrics, + name: 'metric', + title: i18n.translate('visTypeTagCloud.vis.schemas.metricTitle', { + defaultMessage: 'Tag size', + }), + min: 1, + max: 1, + aggFilter: [ + '!std_dev', + '!percentiles', + '!percentile_ranks', + '!derivative', + '!geo_bounds', + '!geo_centroid', + '!filtered_metric', + '!single_percentile', + ], + defaults: [{ schema: 'metric', type: 'count' }], + }, + { + group: AggGroupNames.Buckets, + name: 'segment', + title: i18n.translate('visTypeTagCloud.vis.schemas.segmentTitle', { + defaultMessage: 'Tags', + }), + min: 1, + max: 1, + aggFilter: ['terms', 'significant_terms'], + }, + ], + }, + requiresSearch: true, + }; +}; diff --git a/src/plugins/vis_types/tagcloud/public/to_ast.test.ts b/src/plugins/vis_types/tagcloud/public/to_ast.test.ts index 6de1d4fb3e75..789acda46ec5 100644 --- a/src/plugins/vis_types/tagcloud/public/to_ast.test.ts +++ b/src/plugins/vis_types/tagcloud/public/to_ast.test.ts @@ -38,7 +38,7 @@ describe('tagcloud vis toExpressionAst function', () => { let vis: Vis; beforeEach(() => { - vis = ({ + vis = { isHierarchical: () => false, type: {}, params: { @@ -51,7 +51,7 @@ describe('tagcloud vis toExpressionAst function', () => { aggs: [], }, }, - } as unknown) as Vis; + } as unknown as Vis; }); it('should match snapshot without params', () => { diff --git a/src/plugins/vis_types/tagcloud/public/to_ast.ts b/src/plugins/vis_types/tagcloud/public/to_ast.ts index b5256c586d1d..e9ef8f84ba55 100644 --- a/src/plugins/vis_types/tagcloud/public/to_ast.ts +++ b/src/plugins/vis_types/tagcloud/public/to_ast.ts @@ -6,6 +6,7 @@ * Side Public License, v 1. */ +import { PaletteOutput } from 'src/plugins/charts/common'; import { EsaggsExpressionFunctionDefinition, IndexPatternLoadExpressionFunctionDefinition, @@ -25,6 +26,13 @@ const prepareDimension = (params: SchemaConfig) => { return buildExpression([visdimension]); }; +const preparePalette = (palette?: PaletteOutput) => { + const paletteExpressionFunction = buildExpressionFunction('system_palette', { + name: palette?.name, + }); + return buildExpression([paletteExpressionFunction]); +}; + export const toExpressionAst: VisToExpressionAst = (vis, params) => { const esaggs = buildExpressionFunction('esaggs', { index: buildExpression([ @@ -47,7 +55,7 @@ export const toExpressionAst: VisToExpressionAst = (vis, para maxFontSize, showLabel, metric: prepareDimension(schemas.metric[0]), - palette: palette?.name, + palette: preparePalette(palette), }); if (schemas.segment) { diff --git a/src/plugins/vis_types/timelion/config.ts b/src/plugins/vis_types/timelion/config.ts index cfd3d13c277e..629b11cc95b0 100644 --- a/src/plugins/vis_types/timelion/config.ts +++ b/src/plugins/vis_types/timelion/config.ts @@ -11,6 +11,11 @@ import { schema, TypeOf } from '@kbn/config-schema'; export const configSchema = schema.object({ graphiteUrls: schema.maybe(schema.arrayOf(schema.string())), enabled: schema.boolean({ defaultValue: true }), + // should be removed in v8.0 + /** @deprecated **/ + ui: schema.object({ + enabled: schema.boolean({ defaultValue: true }), + }), }); export type ConfigSchema = TypeOf; diff --git a/src/plugins/vis_types/timelion/public/components/timelion_vis_component.tsx b/src/plugins/vis_types/timelion/public/components/timelion_vis_component.tsx index 9a15159b33a1..d7b7bb14723d 100644 --- a/src/plugins/vis_types/timelion/public/components/timelion_vis_component.tsx +++ b/src/plugins/vis_types/timelion/public/components/timelion_vis_component.tsx @@ -132,9 +132,10 @@ const TimelionVisComponent = ({ [renderComplete] ); - const title: string = useMemo(() => last(compact(map(seriesList.list, '_title'))) || '', [ - seriesList.list, - ]); + const title: string = useMemo( + () => last(compact(map(seriesList.list, '_title'))) || '', + [seriesList.list] + ); const tickFormat = useMemo( () => createTickFormat(interval, kibana.services.timefilter, kibana.services.uiSettings), @@ -153,8 +154,11 @@ const TimelionVisComponent = ({ chart.forEach((series) => { if (series._global?.legend) { - const { show = true, position, noColumns = legendPosition.floatingColumns } = - series._global?.legend ?? {}; + const { + show = true, + position, + noColumns = legendPosition.floatingColumns, + } = series._global?.legend ?? {}; if (validateLegendPositionValue(position)) { const [vAlign, hAlign] = position.split(''); diff --git a/src/plugins/vis_types/timelion/public/helpers/panel_utils.ts b/src/plugins/vis_types/timelion/public/helpers/panel_utils.ts index 1ee834b7d30e..3c76b95bd05c 100644 --- a/src/plugins/vis_types/timelion/public/helpers/panel_utils.ts +++ b/src/plugins/vis_types/timelion/public/helpers/panel_utils.ts @@ -66,11 +66,11 @@ export const createTickFormat = ( export const MAIN_GROUP_ID = 1; export const withStaticPadding = (domain: AxisSpec['domain']): AxisSpec['domain'] => - (({ + ({ ...domain, padding: 50, paddingUnit: 'pixel', - } as unknown) as AxisSpec['domain']); + } as unknown as AxisSpec['domain']); const adaptYaxisParams = (yaxis: IAxis) => { const y = { ...yaxis }; diff --git a/src/plugins/vis_types/timelion/public/helpers/plugin_services.ts b/src/plugins/vis_types/timelion/public/helpers/plugin_services.ts index 0e9014437b32..c88097efa9bf 100644 --- a/src/plugins/vis_types/timelion/public/helpers/plugin_services.ts +++ b/src/plugins/vis_types/timelion/public/helpers/plugin_services.ts @@ -10,9 +10,8 @@ import type { IndexPatternsContract, ISearchStart } from 'src/plugins/data/publi import type { ChartsPluginStart } from 'src/plugins/charts/public'; import { createGetterSetter } from '../../../../kibana_utils/public'; -export const [getIndexPatterns, setIndexPatterns] = createGetterSetter( - 'IndexPatterns' -); +export const [getIndexPatterns, setIndexPatterns] = + createGetterSetter('IndexPatterns'); export const [getDataSearch, setDataSearch] = createGetterSetter('Search'); diff --git a/src/plugins/vis_types/timelion/public/legacy/timelion_vis_component.tsx b/src/plugins/vis_types/timelion/public/legacy/timelion_vis_component.tsx index 1fdb1b37f1c8..136544ac068a 100644 --- a/src/plugins/vis_types/timelion/public/legacy/timelion_vis_component.tsx +++ b/src/plugins/vis_types/timelion/public/legacy/timelion_vis_component.tsx @@ -300,9 +300,9 @@ function TimelionVisComponent({ legendValueNumbers.eq(i).empty(); } else { let label = y.toFixed(precision); - const formatter = ((series.yaxis as unknown) as LegacyAxis).tickFormatter; + const formatter = (series.yaxis as unknown as LegacyAxis).tickFormatter; if (formatter) { - label = formatter(Number(label), (series.yaxis as unknown) as LegacyAxis); + label = formatter(Number(label), series.yaxis as unknown as LegacyAxis); } legendValueNumbers.eq(i).text(`(${label})`); } @@ -401,9 +401,10 @@ function TimelionVisComponent({ } }, [chartElem, plotHoverHandler]); - const title: string = useMemo(() => last(compact(map(seriesList.list, '_title'))) || '', [ - seriesList.list, - ]); + const title: string = useMemo( + () => last(compact(map(seriesList.list, '_title'))) || '', + [seriesList.list] + ); return (
diff --git a/src/plugins/vis_types/timelion/public/plugin.ts b/src/plugins/vis_types/timelion/public/plugin.ts index acc10f991469..d37e15a9938b 100644 --- a/src/plugins/vis_types/timelion/public/plugin.ts +++ b/src/plugins/vis_types/timelion/public/plugin.ts @@ -66,7 +66,8 @@ export class TimelionVisPlugin VisTypeTimelionPluginStart, TimelionVisSetupDependencies, TimelionVisStartDependencies - > { + > +{ constructor(public initializerContext: PluginInitializerContext) {} public setup( diff --git a/src/plugins/vis_types/timelion/server/index.ts b/src/plugins/vis_types/timelion/server/index.ts index 396ef8b61c7b..ef7baf981de1 100644 --- a/src/plugins/vis_types/timelion/server/index.ts +++ b/src/plugins/vis_types/timelion/server/index.ts @@ -12,6 +12,14 @@ import { TimelionPlugin } from './plugin'; export const config: PluginConfigDescriptor = { schema: configSchema, + deprecations: ({ renameFromRoot, unused }) => [ + renameFromRoot('timelion_vis.enabled', 'vis_type_timelion.enabled'), + renameFromRoot('timelion.enabled', 'vis_type_timelion.enabled'), + renameFromRoot('timelion.graphiteUrls', 'vis_type_timelion.graphiteUrls'), + // Unused properties which should be removed after releasing Kibana v8.0: + renameFromRoot('timelion.ui.enabled', 'vis_type_timelion.ui.enabled', { silent: true }), + unused('ui.enabled'), + ], }; export const plugin = (initializerContext: PluginInitializerContext) => diff --git a/src/plugins/vis_types/timelion/server/series_functions/movingaverage.test.js b/src/plugins/vis_types/timelion/server/series_functions/movingaverage.test.js index b2d98df49f72..6a5b62497ec6 100644 --- a/src/plugins/vis_types/timelion/server/series_functions/movingaverage.test.js +++ b/src/plugins/vis_types/timelion/server/series_functions/movingaverage.test.js @@ -18,13 +18,11 @@ import invoke from './helpers/invoke_series_fn.js'; function getFivePointSeries() { return getSeriesList([ - getSeries('Five', [].concat(buckets).push(moment('1984-01-01T00:00:00.000Z')), [ - 10, - 20, - 30, - 40, - 50, - ]), + getSeries( + 'Five', + [].concat(buckets).push(moment('1984-01-01T00:00:00.000Z')), + [10, 20, 30, 40, 50] + ), ]); } diff --git a/src/plugins/vis_types/timelion/server/series_functions/movingstd.test.js b/src/plugins/vis_types/timelion/server/series_functions/movingstd.test.js index 0a1178ece9cc..3c91cc4ec05b 100644 --- a/src/plugins/vis_types/timelion/server/series_functions/movingstd.test.js +++ b/src/plugins/vis_types/timelion/server/series_functions/movingstd.test.js @@ -17,32 +17,9 @@ import getSeriesList from './helpers/get_series_list'; describe('movingstd.js', () => { it('computes the moving standard deviation of a list', async () => { const points = [ - 108.48, - 111.56, - 112.13, - 113.75, - 114.25, - 110.79, - 111.21, - 116.82, - 117.16, - 120.38, - 116.96, - 119.56, - 118.97, - 117.54, - 114.42, - 111.01, - 114.2, - 116.43, - 117.74, - 119.9, - 124.65, - 124.98, - 124.7, - 123.6, - 124.5, - 126.85, + 108.48, 111.56, 112.13, 113.75, 114.25, 110.79, 111.21, 116.82, 117.16, 120.38, 116.96, + 119.56, 118.97, 117.54, 114.42, 111.01, 114.2, 116.43, 117.74, 119.9, 124.65, 124.98, 124.7, + 123.6, 124.5, 126.85, ]; const buckets = []; buckets[0] = moment('2018-01-01T00:00:00.000Z'); @@ -63,27 +40,8 @@ describe('movingstd.js', () => { const trimmedResultPoints = resultPoints.slice(numWindows); const expectedPoints = [ - 2.28, - 1.46, - 1.53, - 2.46, - 3.0, - 4.14, - 3.31, - 1.67, - 1.5, - 1.41, - 2.01, - 3.56, - 3.12, - 2.5, - 2.56, - 3.41, - 3.97, - 3.92, - 3.35, - 2.12, - 0.52, + 2.28, 1.46, 1.53, 2.46, 3.0, 4.14, 3.31, 1.67, 1.5, 1.41, 2.01, 3.56, 3.12, 2.5, 2.56, 3.41, + 3.97, 3.92, 3.35, 2.12, 0.52, ]; expectedPoints.forEach((value, index) => { diff --git a/src/plugins/vis_types/timelion/server/series_functions/subtract.test.js b/src/plugins/vis_types/timelion/server/series_functions/subtract.test.js index f0b654787376..a45236516412 100644 --- a/src/plugins/vis_types/timelion/server/series_functions/subtract.test.js +++ b/src/plugins/vis_types/timelion/server/series_functions/subtract.test.js @@ -32,10 +32,7 @@ describe('subtract.js', () => { const outputSeries = await invoke(fn, [seriesList]); expect(outputSeries.output.list.length).to.eql(1); expect(_.map(outputSeries.output.list[0].data, 1)).to.eql([ - -165.1415926535, - -136, - 19.561, - -2.3424234999999998, + -165.1415926535, -136, 19.561, -2.3424234999999998, ]); }); diff --git a/src/plugins/vis_types/vega/public/data_model/search_api.test.ts b/src/plugins/vis_types/vega/public/data_model/search_api.test.ts index 27dc1627ae22..9ecc160246e2 100644 --- a/src/plugins/vis_types/vega/public/data_model/search_api.test.ts +++ b/src/plugins/vis_types/vega/public/data_model/search_api.test.ts @@ -53,13 +53,13 @@ describe('extendSearchParamsWithRuntimeFields', () => { }); test('should use runtime mappings from spec if it is specified', async () => { - const requestParams = ({ + const requestParams = { body: { runtime_mappings: { test: {}, }, }, - } as unknown) as ReturnType; + } as unknown as ReturnType; const runtimeFields = { foo: {} }; mockComputedFields(dataStart, 'index', runtimeFields); diff --git a/src/plugins/vis_types/vega/public/lib/extract_index_pattern.test.ts b/src/plugins/vis_types/vega/public/lib/extract_index_pattern.test.ts index 39aadc009b93..8d9ab0e10ebc 100644 --- a/src/plugins/vis_types/vega/public/lib/extract_index_pattern.test.ts +++ b/src/plugins/vis_types/vega/public/lib/extract_index_pattern.test.ts @@ -12,7 +12,7 @@ import { setData } from '../services'; import type { VegaSpec } from '../data_model/types'; -const getMockedSpec = (mockedObj: any) => (mockedObj as unknown) as VegaSpec; +const getMockedSpec = (mockedObj: any) => mockedObj as unknown as VegaSpec; describe('extractIndexPatternsFromSpec', () => { const dataStart = dataPluginMock.createStartContract(); diff --git a/src/plugins/vis_types/vega/public/services.ts b/src/plugins/vis_types/vega/public/services.ts index 1cdb24ff7b02..47cf0de3fdae 100644 --- a/src/plugins/vis_types/vega/public/services.ts +++ b/src/plugins/vis_types/vega/public/services.ts @@ -14,20 +14,16 @@ import { MapServiceSettings } from './vega_view/vega_map_view/map_service_settin export const [getData, setData] = createGetterSetter('Data'); -export const [getNotifications, setNotifications] = createGetterSetter( - 'Notifications' -); +export const [getNotifications, setNotifications] = + createGetterSetter('Notifications'); export const [getUISettings, setUISettings] = createGetterSetter('UISettings'); -export const [getInjectedMetadata, setInjectedMetadata] = createGetterSetter< - CoreStart['injectedMetadata'] ->('InjectedMetadata'); +export const [getInjectedMetadata, setInjectedMetadata] = + createGetterSetter('InjectedMetadata'); -export const [ - getMapServiceSettings, - setMapServiceSettings, -] = createGetterSetter('MapServiceSettings'); +export const [getMapServiceSettings, setMapServiceSettings] = + createGetterSetter('MapServiceSettings'); export const [getInjectedVars, setInjectedVars] = createGetterSetter<{ enableExternalUrls: boolean; diff --git a/src/plugins/vis_types/vega/public/vega_inspector/components/inspector_data_grid.tsx b/src/plugins/vis_types/vega/public/vega_inspector/components/inspector_data_grid.tsx index 7d317c46ca80..97890b3373cf 100644 --- a/src/plugins/vis_types/vega/public/vega_inspector/components/inspector_data_grid.tsx +++ b/src/plugins/vis_types/vega/public/vega_inspector/components/inspector_data_grid.tsx @@ -23,9 +23,10 @@ export const InspectorDataGrid = ({ columns, data, dataGridAriaLabel }: Inspecto [setPagination] ); - const onChangePage = useCallback((pageIndex) => setPagination((p) => ({ ...p, pageIndex })), [ - setPagination, - ]); + const onChangePage = useCallback( + (pageIndex) => setPagination((p) => ({ ...p, pageIndex })), + [setPagination] + ); // Column visibility const [visibleColumns, setVisibleColumns] = useState([]); diff --git a/src/plugins/vis_types/vega/public/vega_view/vega_map_view/layers/tms_raster_layer.test.ts b/src/plugins/vis_types/vega/public/vega_view/vega_map_view/layers/tms_raster_layer.test.ts index f8b064f00218..4a755dc2ad87 100644 --- a/src/plugins/vis_types/vega/public/vega_view/vega_map_view/layers/tms_raster_layer.test.ts +++ b/src/plugins/vis_types/vega/public/vega_view/vega_map_view/layers/tms_raster_layer.test.ts @@ -21,10 +21,10 @@ describe('vega_map_view/tms_raster_layer', () => { beforeEach(() => { id = 'foo_tms_layer_id'; - map = ({ + map = { addSource: jest.fn(), addLayer: jest.fn(), - } as unknown) as MapType; + } as unknown as MapType; context = { tiles: ['http://some.tile.com/map/{z}/{x}/{y}.jpg'], maxZoom: 10, diff --git a/src/plugins/vis_types/vega/public/vega_view/vega_map_view/layers/vega_layer.test.ts b/src/plugins/vis_types/vega/public/vega_view/vega_map_view/layers/vega_layer.test.ts index 53337388dc19..d4e761cdb480 100644 --- a/src/plugins/vis_types/vega/public/vega_view/vega_map_view/layers/vega_layer.test.ts +++ b/src/plugins/vis_types/vega/public/vega_view/vega_map_view/layers/vega_layer.test.ts @@ -22,7 +22,7 @@ describe('vega_map_view/tms_raster_layer', () => { beforeEach(() => { id = 'foo_vega_layer_id'; - map = ({ + map = { getCanvasContainer: () => document.createElement('div'), getCanvas: () => ({ style: { @@ -31,11 +31,11 @@ describe('vega_map_view/tms_raster_layer', () => { }, }), addLayer: jest.fn(), - } as unknown) as MapType; + } as unknown as MapType; context = { - vegaView: ({ + vegaView: { initialize: jest.fn(), - } as unknown) as View, + } as unknown as View, vegaControls: 'element', updateVegaView: jest.fn(), }; diff --git a/src/plugins/vis_types/vega/public/vega_view/vega_map_view/map_service_settings.test.ts b/src/plugins/vis_types/vega/public/vega_view/vega_map_view/map_service_settings.test.ts index 95fee2ea3820..acaccb6dbcb1 100644 --- a/src/plugins/vis_types/vega/public/vega_view/vega_map_view/map_service_settings.test.ts +++ b/src/plugins/vis_types/vega/public/vega_view/vega_map_view/map_service_settings.test.ts @@ -88,12 +88,12 @@ describe('vega_map_view/map_service_settings', () => { }); test('getAttributionsForTmsService method should return attributes in a correct form', () => { - const tmsService = ({ + const tmsService = { getAttributions: jest.fn(() => [ { url: 'https://fist_attr.com', label: 'fist_attr' }, { url: 'https://second_attr.com', label: 'second_attr' }, ]), - } as unknown) as TMSService; + } as unknown as TMSService; expect(getAttributionsForTmsService(tmsService)).toMatchInlineSnapshot(` Array [ diff --git a/src/plugins/vis_types/vega/public/vega_view/vega_map_view/utils/vsi_helper.test.ts b/src/plugins/vis_types/vega/public/vega_view/vega_map_view/utils/vsi_helper.test.ts index dcec9e66dc46..987c41563710 100644 --- a/src/plugins/vis_types/vega/public/vega_view/vega_map_view/utils/vsi_helper.test.ts +++ b/src/plugins/vis_types/vega/public/vega_view/vega_map_view/utils/vsi_helper.test.ts @@ -12,12 +12,12 @@ import { VegaSpec } from '../../../data_model/types'; describe('vega_map_view/vsi_helper', () => { describe('injectMapPropsIntoSpec', () => { test('should inject map properties into vega spec', () => { - const spec = ({ + const spec = { $schema: 'https://vega.github.io/schema/vega/v5.json', config: { kibana: { type: 'map', latitude: 25, longitude: -70, zoom: 3 }, }, - } as unknown) as VegaSpec; + } as unknown as VegaSpec; expect(injectMapPropsIntoSpec(spec)).toMatchInlineSnapshot(` Object { diff --git a/src/plugins/vis_types/vega/public/vega_view/vega_map_view/view.test.ts b/src/plugins/vis_types/vega/public/vega_view/vega_map_view/view.test.ts index e4bf4977094f..d3d0b6cb0411 100644 --- a/src/plugins/vis_types/vega/public/vega_view/vega_map_view/view.test.ts +++ b/src/plugins/vis_types/vega/public/vega_view/vega_map_view/view.test.ts @@ -78,7 +78,7 @@ describe('vega_map_view/view', () => { setNotifications(coreStart.notifications); setUISettings(coreStart.uiSettings); - const getTmsService = jest.fn().mockReturnValue(({ + const getTmsService = jest.fn().mockReturnValue({ getVectorStyleSheet: () => ({ version: 8, sources: {}, @@ -88,7 +88,7 @@ describe('vega_map_view/view', () => { getMaxZoom: async () => 20, getMinZoom: async () => 0, getAttributions: () => [{ url: 'tms_attributions' }], - } as unknown) as TMSService); + } as unknown as TMSService); const config = { tilemap: { url: 'test', @@ -101,16 +101,16 @@ describe('vega_map_view/view', () => { } as MapsEmsConfig; function setMapService(defaultTmsLayer: string) { - setMapServiceSettings(({ + setMapServiceSettings({ getTmsService, defaultTmsLayer: () => defaultTmsLayer, config, - } as unknown) as MapServiceSettings); + } as unknown as MapServiceSettings); } async function createVegaMapView() { await vegaParser.parseAsync(); - return new VegaMapView(({ + return new VegaMapView({ vegaParser, filterManager: dataPluginStart.query.filterManager, timefilter: dataPluginStart.query.timefilter.timefilter, @@ -121,7 +121,7 @@ describe('vega_map_view/view', () => { restore: jest.fn(), clear: jest.fn(), }, - } as unknown) as VegaViewParams); + } as unknown as VegaViewParams); } beforeEach(() => { diff --git a/src/plugins/vis_types/vega/server/usage_collector/get_usage_collector.test.ts b/src/plugins/vis_types/vega/server/usage_collector/get_usage_collector.test.ts index aa1b8e447bbc..627f8c2eea83 100644 --- a/src/plugins/vis_types/vega/server/usage_collector/get_usage_collector.test.ts +++ b/src/plugins/vis_types/vega/server/usage_collector/get_usage_collector.test.ts @@ -40,8 +40,7 @@ const mockedSavedObjects = [ visState: JSON.stringify({ type: 'vega', params: { - spec: - '{"$schema": "https://vega.github.io/schema/vega/v3.json" \n "config": { "kibana" : { "type": "map" }} }', + spec: '{"$schema": "https://vega.github.io/schema/vega/v3.json" \n "config": { "kibana" : { "type": "map" }} }', }, }), }, @@ -51,21 +50,21 @@ const mockedSavedObjects = [ const getMockCollectorFetchContext = (savedObjects?: unknown[]) => { const fetchParamsMock = createCollectorFetchContextMock(); - fetchParamsMock.soClient = ({ + fetchParamsMock.soClient = { createPointInTimeFinder: jest.fn().mockResolvedValue({ close: jest.fn(), find: function* asyncGenerator() { yield { saved_objects: savedObjects }; }, }), - } as unknown) as SavedObjectsClientContract; + } as unknown as SavedObjectsClientContract; return fetchParamsMock; }; describe('Vega visualization usage collector', () => { const mockDeps = { - home: ({ + home: { sampleData: { getSampleDatasets: jest.fn().mockReturnValue([ { @@ -86,7 +85,7 @@ describe('Vega visualization usage collector', () => { }, ]), }, - } as unknown) as HomeServerPluginSetup, + } as unknown as HomeServerPluginSetup, }; test('Returns undefined when no results found (undefined)', async () => { diff --git a/src/plugins/vis_types/vega/server/usage_collector/register_vega_collector.test.ts b/src/plugins/vis_types/vega/server/usage_collector/register_vega_collector.test.ts index 137dd2f17375..0597f3b856f0 100644 --- a/src/plugins/vis_types/vega/server/usage_collector/register_vega_collector.test.ts +++ b/src/plugins/vis_types/vega/server/usage_collector/register_vega_collector.test.ts @@ -17,7 +17,7 @@ import type { HomeServerPluginSetup } from '../../../../home/server'; import type { ConfigObservable } from '../types'; describe('registerVegaUsageCollector', () => { - const mockDeps = { home: ({} as unknown) as HomeServerPluginSetup }; + const mockDeps = { home: {} as unknown as HomeServerPluginSetup }; const mockConfig = {} as ConfigObservable; test('makes a usage collector and registers it`', () => { diff --git a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_columns.js b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_columns.js index b3eff8b2f82f..bc42445ddb18 100644 --- a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_columns.js +++ b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_columns.js @@ -272,36 +272,11 @@ export default { }, ], xAxisOrderedValues: [ - 1415826600000, - 1415826630000, - 1415826660000, - 1415826690000, - 1415826720000, - 1415826750000, - 1415826780000, - 1415826810000, - 1415826840000, - 1415826870000, - 1415826900000, - 1415826930000, - 1415826960000, - 1415826990000, - 1415827020000, - 1415827050000, - 1415827080000, - 1415827110000, - 1415827140000, - 1415827170000, - 1415827200000, - 1415827230000, - 1415827260000, - 1415827290000, - 1415827320000, - 1415827350000, - 1415827380000, - 1415827410000, - 1415827440000, - 1415827470000, + 1415826600000, 1415826630000, 1415826660000, 1415826690000, 1415826720000, 1415826750000, + 1415826780000, 1415826810000, 1415826840000, 1415826870000, 1415826900000, 1415826930000, + 1415826960000, 1415826990000, 1415827020000, 1415827050000, 1415827080000, 1415827110000, + 1415827140000, 1415827170000, 1415827200000, 1415827230000, 1415827260000, 1415827290000, + 1415827320000, 1415827350000, 1415827380000, 1415827410000, 1415827440000, 1415827470000, 1415827500000, ], hits: 225, diff --git a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_rows.js b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_rows.js index 9ee922ed3d2e..87eecea5f2ed 100644 --- a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_rows.js +++ b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_rows.js @@ -1650,36 +1650,11 @@ export default { }, ], xAxisOrderedValues: [ - 1415826240000, - 1415826270000, - 1415826300000, - 1415826330000, - 1415826360000, - 1415826390000, - 1415826420000, - 1415826450000, - 1415826480000, - 1415826510000, - 1415826540000, - 1415826570000, - 1415826600000, - 1415826630000, - 1415826660000, - 1415826690000, - 1415826720000, - 1415826750000, - 1415826780000, - 1415826810000, - 1415826840000, - 1415826870000, - 1415826900000, - 1415826930000, - 1415826960000, - 1415826990000, - 1415827020000, - 1415827050000, - 1415827080000, - 1415827110000, + 1415826240000, 1415826270000, 1415826300000, 1415826330000, 1415826360000, 1415826390000, + 1415826420000, 1415826450000, 1415826480000, 1415826510000, 1415826540000, 1415826570000, + 1415826600000, 1415826630000, 1415826660000, 1415826690000, 1415826720000, 1415826750000, + 1415826780000, 1415826810000, 1415826840000, 1415826870000, 1415826900000, 1415826930000, + 1415826960000, 1415826990000, 1415827020000, 1415827050000, 1415827080000, 1415827110000, 1415827140000, ], hits: 236, diff --git a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_rows_series_with_holes.js b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_rows_series_with_holes.js index 3b67e12827cf..a752a76be586 100644 --- a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_rows_series_with_holes.js +++ b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_rows_series_with_holes.js @@ -109,23 +109,8 @@ export const rowsSeriesWithHoles = { }, ], xAxisOrderedValues: [ - 1411761450000, - 1411761510000, - 1411761540000, - 1411761840000, - 1411761870000, - 1411761900000, - 1411761930000, - 1411761960000, - 1411761990000, - 1411762020000, - 1411762050000, - 1411762080000, - 1411762110000, - 1411762140000, - 1411762170000, - 1411762200000, - 1411762320000, - 1411762350000, + 1411761450000, 1411761510000, 1411761540000, 1411761840000, 1411761870000, 1411761900000, + 1411761930000, 1411761960000, 1411761990000, 1411762020000, 1411762050000, 1411762080000, + 1411762110000, 1411762140000, 1411762170000, 1411762200000, 1411762320000, 1411762350000, ], }; diff --git a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series.js b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series.js index 43962b4cc885..58970e55e2b8 100644 --- a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series.js +++ b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series.js @@ -151,36 +151,11 @@ export default { ], hits: 533, xAxisOrderedValues: [ - 1411761450000, - 1411761480000, - 1411761510000, - 1411761540000, - 1411761570000, - 1411761600000, - 1411761630000, - 1411761660000, - 1411761690000, - 1411761720000, - 1411761750000, - 1411761780000, - 1411761810000, - 1411761840000, - 1411761870000, - 1411761900000, - 1411761930000, - 1411761960000, - 1411761990000, - 1411762020000, - 1411762050000, - 1411762080000, - 1411762110000, - 1411762140000, - 1411762170000, - 1411762200000, - 1411762230000, - 1411762260000, - 1411762290000, - 1411762320000, + 1411761450000, 1411761480000, 1411761510000, 1411761540000, 1411761570000, 1411761600000, + 1411761630000, 1411761660000, 1411761690000, 1411761720000, 1411761750000, 1411761780000, + 1411761810000, 1411761840000, 1411761870000, 1411761900000, 1411761930000, 1411761960000, + 1411761990000, 1411762020000, 1411762050000, 1411762080000, 1411762110000, 1411762140000, + 1411762170000, 1411762200000, 1411762230000, 1411762260000, 1411762290000, 1411762320000, 1411762350000, ], xAxisFormatter: function (thing) { diff --git a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series_monthly_interval.js b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series_monthly_interval.js index 6b154158fdbe..f29bab822286 100644 --- a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series_monthly_interval.js +++ b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series_monthly_interval.js @@ -75,18 +75,8 @@ export const seriesMonthlyInterval = { ], hits: 533, xAxisOrderedValues: [ - 1451631600000, - 1454310000000, - 1456815600000, - 1459490400000, - 1462082400000, - 1464760800000, - 1467352800000, - 1470031200000, - 1472709600000, - 1475301600000, - 1477980000000, - 1480575600000, + 1451631600000, 1454310000000, 1456815600000, 1459490400000, 1462082400000, 1464760800000, + 1467352800000, 1470031200000, 1472709600000, 1475301600000, 1477980000000, 1480575600000, ], xAxisFormatter: function (thing) { return moment(thing); diff --git a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series_neg.js b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series_neg.js index 3bc344548240..79ec01b0253f 100644 --- a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series_neg.js +++ b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series_neg.js @@ -151,36 +151,11 @@ export default { ], hits: 533, xAxisOrderedValues: [ - 1411761450000, - 1411761480000, - 1411761510000, - 1411761540000, - 1411761570000, - 1411761600000, - 1411761630000, - 1411761660000, - 1411761690000, - 1411761720000, - 1411761750000, - 1411761780000, - 1411761810000, - 1411761840000, - 1411761870000, - 1411761900000, - 1411761930000, - 1411761960000, - 1411761990000, - 1411762020000, - 1411762050000, - 1411762080000, - 1411762110000, - 1411762140000, - 1411762170000, - 1411762200000, - 1411762230000, - 1411762260000, - 1411762290000, - 1411762320000, + 1411761450000, 1411761480000, 1411761510000, 1411761540000, 1411761570000, 1411761600000, + 1411761630000, 1411761660000, 1411761690000, 1411761720000, 1411761750000, 1411761780000, + 1411761810000, 1411761840000, 1411761870000, 1411761900000, 1411761930000, 1411761960000, + 1411761990000, 1411762020000, 1411762050000, 1411762080000, 1411762110000, 1411762140000, + 1411762170000, 1411762200000, 1411762230000, 1411762260000, 1411762290000, 1411762320000, 1411762350000, ], xAxisFormatter: function (thing) { diff --git a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series_pos_neg.js b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series_pos_neg.js index 680d4ee01133..d99d25d67ff7 100644 --- a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series_pos_neg.js +++ b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_series_pos_neg.js @@ -151,36 +151,11 @@ export default { ], hits: 533, xAxisOrderedValues: [ - 1411761450000, - 1411761480000, - 1411761510000, - 1411761540000, - 1411761570000, - 1411761600000, - 1411761630000, - 1411761660000, - 1411761690000, - 1411761720000, - 1411761750000, - 1411761780000, - 1411761810000, - 1411761840000, - 1411761870000, - 1411761900000, - 1411761930000, - 1411761960000, - 1411761990000, - 1411762020000, - 1411762050000, - 1411762080000, - 1411762110000, - 1411762140000, - 1411762170000, - 1411762200000, - 1411762230000, - 1411762260000, - 1411762290000, - 1411762320000, + 1411761450000, 1411761480000, 1411761510000, 1411761540000, 1411761570000, 1411761600000, + 1411761630000, 1411761660000, 1411761690000, 1411761720000, 1411761750000, 1411761780000, + 1411761810000, 1411761840000, 1411761870000, 1411761900000, 1411761930000, 1411761960000, + 1411761990000, 1411762020000, 1411762050000, 1411762080000, 1411762110000, 1411762140000, + 1411762170000, 1411762200000, 1411762230000, 1411762260000, 1411762290000, 1411762320000, 1411762350000, ], xAxisFormatter: function (thing) { diff --git a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_stacked_series.js b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_stacked_series.js index 9d7873fd9011..7605f8cdd69b 100644 --- a/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_stacked_series.js +++ b/src/plugins/vis_types/vislib/public/fixtures/mock_data/date_histogram/_stacked_series.js @@ -1483,78 +1483,18 @@ export default { ], hits: 108970, xAxisOrderedValues: [ - 1413543600000, - 1413544200000, - 1413544800000, - 1413545400000, - 1413546000000, - 1413546600000, - 1413547200000, - 1413547800000, - 1413548400000, - 1413549000000, - 1413549600000, - 1413550200000, - 1413550800000, - 1413551400000, - 1413552000000, - 1413552600000, - 1413553200000, - 1413553800000, - 1413554400000, - 1413555000000, - 1413555600000, - 1413556200000, - 1413556800000, - 1413557400000, - 1413558000000, - 1413558600000, - 1413559200000, - 1413559800000, - 1413560400000, - 1413561000000, - 1413561600000, - 1413562200000, - 1413562800000, - 1413563400000, - 1413564000000, - 1413564600000, - 1413565200000, - 1413565800000, - 1413566400000, - 1413567000000, - 1413567600000, - 1413568200000, - 1413568800000, - 1413569400000, - 1413570000000, - 1413570600000, - 1413571200000, - 1413571800000, - 1413572400000, - 1413573600000, - 1413574200000, - 1413574800000, - 1413575400000, - 1413576000000, - 1413576600000, - 1413577200000, - 1413577800000, - 1413578400000, - 1413579000000, - 1413579600000, - 1413580200000, - 1413580800000, - 1413581400000, - 1413582000000, - 1413582600000, - 1413583200000, - 1413583800000, - 1413584400000, - 1413585000000, - 1413585600000, - 1413586200000, - 1413586800000, + 1413543600000, 1413544200000, 1413544800000, 1413545400000, 1413546000000, 1413546600000, + 1413547200000, 1413547800000, 1413548400000, 1413549000000, 1413549600000, 1413550200000, + 1413550800000, 1413551400000, 1413552000000, 1413552600000, 1413553200000, 1413553800000, + 1413554400000, 1413555000000, 1413555600000, 1413556200000, 1413556800000, 1413557400000, + 1413558000000, 1413558600000, 1413559200000, 1413559800000, 1413560400000, 1413561000000, + 1413561600000, 1413562200000, 1413562800000, 1413563400000, 1413564000000, 1413564600000, + 1413565200000, 1413565800000, 1413566400000, 1413567000000, 1413567600000, 1413568200000, + 1413568800000, 1413569400000, 1413570000000, 1413570600000, 1413571200000, 1413571800000, + 1413572400000, 1413573600000, 1413574200000, 1413574800000, 1413575400000, 1413576000000, + 1413576600000, 1413577200000, 1413577800000, 1413578400000, 1413579000000, 1413579600000, + 1413580200000, 1413580800000, 1413581400000, 1413582000000, 1413582600000, 1413583200000, + 1413583800000, 1413584400000, 1413585000000, 1413585600000, 1413586200000, 1413586800000, ], xAxisFormatter: function (thing) { return moment(thing); diff --git a/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_columns.js b/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_columns.js index 19e242a7a24e..9181a064f955 100644 --- a/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_columns.js +++ b/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_columns.js @@ -348,23 +348,9 @@ export default { }, ], xAxisOrderedValues: [ - 2147483600, - 3221225400, - 4294967200, - 5368709100, - 6442450900, - 7516192700, - 8589934500, - 10737418200, - 11811160000, - 12884901800, - 13958643700, - 15032385500, - 16106127300, - 18253611000, - 19327352800, - 20401094600, - 21474836400, + 2147483600, 3221225400, 4294967200, 5368709100, 6442450900, 7516192700, 8589934500, 10737418200, + 11811160000, 12884901800, 13958643700, 15032385500, 16106127300, 18253611000, 19327352800, + 20401094600, 21474836400, ], hits: 40, }; diff --git a/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_rows.js b/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_rows.js index a5cd5a5481d3..29fe11a31199 100644 --- a/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_rows.js +++ b/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_rows.js @@ -189,26 +189,9 @@ export default { }, ], xAxisOrderedValues: [ - 2147483600, - 3221225400, - 4294967200, - 5368709100, - 6442450900, - 7516192700, - 8589934500, - 9663676400, - 10737418200, - 11811160000, - 12884901800, - 13958643700, - 15032385500, - 16106127300, - 17179869100, - 18253611000, - 19327352800, - 20401094600, - 21474836400, - 32212254700, + 2147483600, 3221225400, 4294967200, 5368709100, 6442450900, 7516192700, 8589934500, 9663676400, + 10737418200, 11811160000, 12884901800, 13958643700, 15032385500, 16106127300, 17179869100, + 18253611000, 19327352800, 20401094600, 21474836400, 32212254700, ], hits: 51, }; diff --git a/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_series.js b/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_series.js index 8b732f359b84..8d4a8666753f 100644 --- a/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_series.js +++ b/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_series.js @@ -96,24 +96,9 @@ export default { ], hits: 71, xAxisOrderedValues: [ - 3221225400, - 4294967200, - 5368709100, - 6442450900, - 7516192700, - 9663676400, - 10737418200, - 11811160000, - 12884901800, - 13958643700, - 15032385500, - 16106127300, - 17179869100, - 18253611000, - 19327352800, - 20401094600, - 21474836400, - 32212254700, + 3221225400, 4294967200, 5368709100, 6442450900, 7516192700, 9663676400, 10737418200, + 11811160000, 12884901800, 13958643700, 15032385500, 16106127300, 17179869100, 18253611000, + 19327352800, 20401094600, 21474836400, 32212254700, ], xAxisFormatter: function (val) { if (_.isObject(val)) { diff --git a/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_slices.js b/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_slices.js index b120bb6cf1cb..bfe5a31a8aba 100644 --- a/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_slices.js +++ b/src/plugins/vis_types/vislib/public/fixtures/mock_data/histogram/_slices.js @@ -288,27 +288,8 @@ export default { ], }, names: [ - 0, - 1000, - 2000, - 3000, - 4000, - 5000, - 6000, - 7000, - 8000, - 9000, - 10000, - 11000, - 12000, - 13000, - 14000, - 15000, - 16000, - 17000, - 18000, - 19000, - 20000, + 0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000, 12000, 13000, 14000, + 15000, 16000, 17000, 18000, 19000, 20000, ], hits: 3967374, tooltipFormatter: function (event) { diff --git a/src/plugins/vis_types/vislib/public/fixtures/mock_data/stacked/_stacked.js b/src/plugins/vis_types/vislib/public/fixtures/mock_data/stacked/_stacked.js index 3da5c1a5d6d7..3ba912657efa 100644 --- a/src/plugins/vis_types/vislib/public/fixtures/mock_data/stacked/_stacked.js +++ b/src/plugins/vis_types/vislib/public/fixtures/mock_data/stacked/_stacked.js @@ -19,66 +19,16 @@ export default { }, yAxisLabel: 'Count of documents', xAxisOrderedValues: [ - 1416850320000, - 1416850350000, - 1416850380000, - 1416850410000, - 1416850440000, - 1416850470000, - 1416850500000, - 1416850530000, - 1416850560000, - 1416850590000, - 1416850620000, - 1416850650000, - 1416850680000, - 1416850710000, - 1416850740000, - 1416850770000, - 1416850800000, - 1416850830000, - 1416850860000, - 1416850890000, - 1416850920000, - 1416850950000, - 1416850980000, - 1416851010000, - 1416851040000, - 1416851070000, - 1416851100000, - 1416851130000, - 1416851160000, - 1416851190000, - 1416851220000, - 1416851250000, - 1416851280000, - 1416851310000, - 1416851340000, - 1416851370000, - 1416851400000, - 1416851430000, - 1416851460000, - 1416851490000, - 1416851520000, - 1416851550000, - 1416851580000, - 1416851610000, - 1416851640000, - 1416851670000, - 1416851700000, - 1416851730000, - 1416851760000, - 1416851790000, - 1416851820000, - 1416851850000, - 1416851880000, - 1416851910000, - 1416851940000, - 1416851970000, - 1416852000000, - 1416852030000, - 1416852060000, - 1416852090000, + 1416850320000, 1416850350000, 1416850380000, 1416850410000, 1416850440000, 1416850470000, + 1416850500000, 1416850530000, 1416850560000, 1416850590000, 1416850620000, 1416850650000, + 1416850680000, 1416850710000, 1416850740000, 1416850770000, 1416850800000, 1416850830000, + 1416850860000, 1416850890000, 1416850920000, 1416850950000, 1416850980000, 1416851010000, + 1416851040000, 1416851070000, 1416851100000, 1416851130000, 1416851160000, 1416851190000, + 1416851220000, 1416851250000, 1416851280000, 1416851310000, 1416851340000, 1416851370000, + 1416851400000, 1416851430000, 1416851460000, 1416851490000, 1416851520000, 1416851550000, + 1416851580000, 1416851610000, 1416851640000, 1416851670000, 1416851700000, 1416851730000, + 1416851760000, 1416851790000, 1416851820000, 1416851850000, 1416851880000, 1416851910000, + 1416851940000, 1416851970000, 1416852000000, 1416852030000, 1416852060000, 1416852090000, 1416852120000, ], series: [ diff --git a/src/plugins/vis_types/vislib/public/plugin.ts b/src/plugins/vis_types/vislib/public/plugin.ts index b0385475f710..7e9095ce4199 100644 --- a/src/plugins/vis_types/vislib/public/plugin.ts +++ b/src/plugins/vis_types/vislib/public/plugin.ts @@ -39,7 +39,8 @@ export type VisTypeVislibCoreSetup = CoreSetup { + Plugin +{ constructor(public initializerContext: PluginInitializerContext) {} public setup( diff --git a/src/plugins/vis_types/vislib/public/services.ts b/src/plugins/vis_types/vislib/public/services.ts index d111007598b8..21fb77a4d41c 100644 --- a/src/plugins/vis_types/vislib/public/services.ts +++ b/src/plugins/vis_types/vislib/public/services.ts @@ -9,9 +9,8 @@ import { createGetterSetter } from '../../../kibana_utils/public'; import { DataPublicPluginStart } from '../../../data/public'; -export const [getDataActions, setDataActions] = createGetterSetter< - DataPublicPluginStart['actions'] ->('vislib data.actions'); +export const [getDataActions, setDataActions] = + createGetterSetter('vislib data.actions'); export const [getFormatService, setFormatService] = createGetterSetter< DataPublicPluginStart['fieldFormats'] diff --git a/src/plugins/vis_types/vislib/public/vislib/components/zero_injection/zero_injection.test.js b/src/plugins/vis_types/vislib/public/vislib/components/zero_injection/zero_injection.test.js index 54c981ddb33d..5def9a7c72ea 100644 --- a/src/plugins/vis_types/vislib/public/vislib/components/zero_injection/zero_injection.test.js +++ b/src/plugins/vis_types/vislib/public/vislib/components/zero_injection/zero_injection.test.js @@ -17,12 +17,7 @@ import { zeroFillDataArray } from './zero_fill_data_array'; describe('Vislib Zero Injection Module Test Suite', function () { const dateHistogramRowsObj = { xAxisOrderedValues: [ - 1418410560000, - 1418410620000, - 1418410680000, - 1418410740000, - 1418410800000, - 1418410860000, + 1418410560000, 1418410620000, 1418410680000, 1418410740000, 1418410800000, 1418410860000, 1418410920000, ], series: [ diff --git a/src/plugins/vis_types/vislib/public/vislib/lib/axis/x_axis.test.js b/src/plugins/vis_types/vislib/public/vislib/lib/axis/x_axis.test.js index 1ded9e48fcfd..6b41c55242e2 100644 --- a/src/plugins/vis_types/vislib/public/vislib/lib/axis/x_axis.test.js +++ b/src/plugins/vis_types/vislib/public/vislib/lib/axis/x_axis.test.js @@ -28,16 +28,8 @@ describe('Vislib xAxis Class Test Suite', function () { min: 1408734082458, }, xAxisOrderedValues: [ - 1408734060000, - 1408734090000, - 1408734120000, - 1408734150000, - 1408734180000, - 1408734210000, - 1408734240000, - 1408734270000, - 1408734300000, - 1408734330000, + 1408734060000, 1408734090000, 1408734120000, 1408734150000, 1408734180000, 1408734210000, + 1408734240000, 1408734270000, 1408734300000, 1408734330000, ], series: [ { diff --git a/src/plugins/vis_types/vislib/public/vislib/lib/axis/y_axis.test.js b/src/plugins/vis_types/vislib/public/vislib/lib/axis/y_axis.test.js index 5bbfde01197e..9c1e27e7731f 100644 --- a/src/plugins/vis_types/vislib/public/vislib/lib/axis/y_axis.test.js +++ b/src/plugins/vis_types/vislib/public/vislib/lib/axis/y_axis.test.js @@ -22,16 +22,8 @@ let yAxis; let yAxisDiv; const timeSeries = [ - 1408734060000, - 1408734090000, - 1408734120000, - 1408734150000, - 1408734180000, - 1408734210000, - 1408734240000, - 1408734270000, - 1408734300000, - 1408734330000, + 1408734060000, 1408734090000, 1408734120000, 1408734150000, 1408734180000, 1408734210000, + 1408734240000, 1408734270000, 1408734300000, 1408734330000, ]; const defaultGraphData = [ diff --git a/src/plugins/vis_types/vislib/public/vislib/visualizations/chart.test.js b/src/plugins/vis_types/vislib/public/vislib/visualizations/chart.test.js index c105102dc6ab..21ec67707126 100644 --- a/src/plugins/vis_types/vislib/public/vislib/visualizations/chart.test.js +++ b/src/plugins/vis_types/vislib/public/vislib/visualizations/chart.test.js @@ -32,16 +32,8 @@ describe('Vislib _chart Test Suite', function () { min: 1408734082458, }, xAxisOrderedValues: [ - 1408734060000, - 1408734090000, - 1408734120000, - 1408734150000, - 1408734180000, - 1408734210000, - 1408734240000, - 1408734270000, - 1408734300000, - 1408734330000, + 1408734060000, 1408734090000, 1408734120000, 1408734150000, 1408734180000, 1408734210000, + 1408734240000, 1408734270000, 1408734300000, 1408734330000, ], series: [ { diff --git a/src/plugins/vis_types/xy/public/components/detailed_tooltip.mock.ts b/src/plugins/vis_types/xy/public/components/detailed_tooltip.mock.ts index 25310ea1ee7f..bc6a1f292dad 100644 --- a/src/plugins/vis_types/xy/public/components/detailed_tooltip.mock.ts +++ b/src/plugins/vis_types/xy/public/components/detailed_tooltip.mock.ts @@ -148,8 +148,7 @@ export const aspectsWithSplitRow = { export const header = { seriesIdentifier: { - key: - 'groupId{__pseudo_stacked_group-ValueAxis-1__}spec{area-col-1-1}yAccessor{col-1-1}splitAccessors{}smV{__ECH_DEFAULT_SINGLE_PANEL_SM_VALUE__}smH{__ECH_DEFAULT_SINGLE_PANEL_SM_VALUE__}', + key: 'groupId{__pseudo_stacked_group-ValueAxis-1__}spec{area-col-1-1}yAccessor{col-1-1}splitAccessors{}smV{__ECH_DEFAULT_SINGLE_PANEL_SM_VALUE__}smH{__ECH_DEFAULT_SINGLE_PANEL_SM_VALUE__}', specId: 'area-col-1-1', yAccessor: 'col-1-1', splitAccessors: {}, @@ -169,8 +168,7 @@ export const header = { export const value = { seriesIdentifier: { - key: - 'groupId{__pseudo_stacked_group-ValueAxis-1__}spec{area-col-1-1}yAccessor{col-1-1}splitAccessors{}smV{__ECH_DEFAULT_SINGLE_PANEL_SM_VALUE__}smH{__ECH_DEFAULT_SINGLE_PANEL_SM_VALUE__}', + key: 'groupId{__pseudo_stacked_group-ValueAxis-1__}spec{area-col-1-1}yAccessor{col-1-1}splitAccessors{}smV{__ECH_DEFAULT_SINGLE_PANEL_SM_VALUE__}smH{__ECH_DEFAULT_SINGLE_PANEL_SM_VALUE__}', specId: 'area-col-1-1', yAccessor: 'col-1-1', splitAccessors: [], diff --git a/src/plugins/vis_types/xy/public/components/detailed_tooltip.tsx b/src/plugins/vis_types/xy/public/components/detailed_tooltip.tsx index fb6b4bb41d9b..a7eb7a909615 100644 --- a/src/plugins/vis_types/xy/public/components/detailed_tooltip.tsx +++ b/src/plugins/vis_types/xy/public/components/detailed_tooltip.tsx @@ -113,34 +113,34 @@ const renderData = ({ label, value }: TooltipData, index: number) => { ) : null; }; -export const getDetailedTooltip = (aspects: Aspects) => ( - headerFormatter?: TooltipValueFormatter -): CustomTooltip => { - return function DetailedTooltip({ header, values }) { - // Note: first value is not necessarily the closest value - // To be fixed with https://github.com/elastic/elastic-charts/issues/835 - // TODO: Allow multiple values to be displayed in tooltip - const highlightedValue = values.find(({ isHighlighted }) => isHighlighted); - - if (!highlightedValue) { - return null; - } - - const tooltipData = getTooltipData(aspects, header, highlightedValue); - - if (tooltipData.length === 0) { - return null; - } - - return ( -
- {headerFormatter && header && ( -
{headerFormatter(header)}
- )} - - {tooltipData.map(renderData)} -
-
- ); +export const getDetailedTooltip = + (aspects: Aspects) => + (headerFormatter?: TooltipValueFormatter): CustomTooltip => { + return function DetailedTooltip({ header, values }) { + // Note: first value is not necessarily the closest value + // To be fixed with https://github.com/elastic/elastic-charts/issues/835 + // TODO: Allow multiple values to be displayed in tooltip + const highlightedValue = values.find(({ isHighlighted }) => isHighlighted); + + if (!highlightedValue) { + return null; + } + + const tooltipData = getTooltipData(aspects, header, highlightedValue); + + if (tooltipData.length === 0) { + return null; + } + + return ( +
+ {headerFormatter && header && ( +
{headerFormatter(header)}
+ )} + + {tooltipData.map(renderData)} +
+
+ ); + }; }; -}; diff --git a/src/plugins/vis_types/xy/public/config/get_axis.ts b/src/plugins/vis_types/xy/public/config/get_axis.ts index 4750724ca3d4..b5cc96830e46 100644 --- a/src/plugins/vis_types/xy/public/config/get_axis.ts +++ b/src/plugins/vis_types/xy/public/config/get_axis.ts @@ -126,14 +126,16 @@ function getScale( format: Aspect['format'], isCategoryAxis: boolean ): ScaleConfig { - const type = (isCategoryAxis - ? getScaleType( - scale, - format?.id === 'number' || (format?.params?.id === 'number' && format?.id !== 'range'), - 'date' in params, - 'interval' in params - ) - : getScaleType(scale, true)) as S; + const type = ( + isCategoryAxis + ? getScaleType( + scale, + format?.id === 'number' || (format?.params?.id === 'number' && format?.id !== 'range'), + 'date' in params, + 'interval' in params + ) + : getScaleType(scale, true) + ) as S; return { ...scale, diff --git a/src/plugins/vis_types/xy/public/config/get_threshold_line.ts b/src/plugins/vis_types/xy/public/config/get_threshold_line.ts index 9f0cf4c515ab..64eb7e5e24a8 100644 --- a/src/plugins/vis_types/xy/public/config/get_threshold_line.ts +++ b/src/plugins/vis_types/xy/public/config/get_threshold_line.ts @@ -20,8 +20,9 @@ export function getThresholdLine( yAxes: Array>, seriesParams: SeriesParam[] ): ThresholdLineConfig { - const groupId = yAxes.find(({ id }) => seriesParams.some(({ valueAxis }) => id === valueAxis)) - ?.groupId; + const groupId = yAxes.find(({ id }) => + seriesParams.some(({ valueAxis }) => id === valueAxis) + )?.groupId; return { ...rest, diff --git a/src/plugins/vis_types/xy/public/editor/components/options/metrics_axes/mocks.ts b/src/plugins/vis_types/xy/public/editor/components/options/metrics_axes/mocks.ts index cbc970c7ed7d..1541837dacc3 100644 --- a/src/plugins/vis_types/xy/public/editor/components/options/metrics_axes/mocks.ts +++ b/src/plugins/vis_types/xy/public/editor/components/options/metrics_axes/mocks.ts @@ -80,10 +80,10 @@ const seriesParam: SeriesParam = { valueAxis: defaultValueAxisId, }; -const vis = ({ +const vis = { type: { editorConfig: {}, }, -} as any) as Vis; +} as any as Vis; export { defaultValueAxisId, categoryAxis, valueAxis, seriesParam, vis }; diff --git a/src/plugins/vis_types/xy/public/editor/components/options/point_series/point_series.test.tsx b/src/plugins/vis_types/xy/public/editor/components/options/point_series/point_series.test.tsx index 6367494bf926..5bf9486bbc4e 100644 --- a/src/plugins/vis_types/xy/public/editor/components/options/point_series/point_series.test.tsx +++ b/src/plugins/vis_types/xy/public/editor/components/options/point_series/point_series.test.tsx @@ -31,7 +31,7 @@ describe('PointSeries Editor', function () { let component: ReactWrapper; beforeEach(() => { - props = ({ + props = { aggs: getAggs(), hasHistogramAgg: false, isTabSelected: false, @@ -41,7 +41,7 @@ describe('PointSeries Editor', function () { setValidity: jest.fn(), stateParams: getStateParams(ChartType.Histogram, false), vis: getVis('date_histogram'), - } as unknown) as PointSeriesOptionsProps; + } as unknown as PointSeriesOptionsProps; }); it('renders the showValuesOnChart switch for a bar chart', async () => { @@ -52,10 +52,10 @@ describe('PointSeries Editor', function () { }); it('not renders the showValuesOnChart switch for an area chart', async () => { - const areaVisProps = ({ + const areaVisProps = { ...props, stateParams: getStateParams(ChartType.Area, false), - } as unknown) as PointSeriesOptionsProps; + } as unknown as PointSeriesOptionsProps; component = mountWithIntl(); await act(async () => { expect(findTestSubject(component, 'showValuesOnChart').length).toBe(0); @@ -71,10 +71,10 @@ describe('PointSeries Editor', function () { }); it('renders the orderBucketsBySum switch for a non date histogram bucket', async () => { - const newVisProps = ({ + const newVisProps = { ...props, vis: getVis('terms'), - } as unknown) as PointSeriesOptionsProps; + } as unknown as PointSeriesOptionsProps; component = mountWithIntl(); await act(async () => { expect(findTestSubject(component, 'addTimeMarker').length).toBe(0); @@ -104,10 +104,10 @@ describe('PointSeries Editor', function () { }); it('renders the fitting function for a line chart', async () => { - const newVisProps = ({ + const newVisProps = { ...props, stateParams: getStateParams(ChartType.Line, false), - } as unknown) as PointSeriesOptionsProps; + } as unknown as PointSeriesOptionsProps; component = mountWithIntl(); await act(async () => { expect(findTestSubject(component, 'fittingFunction').length).toBe(1); @@ -129,10 +129,10 @@ describe('PointSeries Editor', function () { }); it('renders the threshold panel if the Show threshold line switch is on', async () => { - const newVisProps = ({ + const newVisProps = { ...props, stateParams: getStateParams(ChartType.Histogram, true), - } as unknown) as PointSeriesOptionsProps; + } as unknown as PointSeriesOptionsProps; component = mountWithIntl(); await act(async () => { expect(findTestSubject(component, 'thresholdValueInputOption').length).toBe(1); diff --git a/src/plugins/vis_types/xy/public/plugin.ts b/src/plugins/vis_types/xy/public/plugin.ts index 600e78b5b394..c79ead242e35 100644 --- a/src/plugins/vis_types/xy/public/plugin.ts +++ b/src/plugins/vis_types/xy/public/plugin.ts @@ -59,7 +59,8 @@ export class VisTypeXyPlugin VisTypeXyPluginStart, VisTypeXyPluginSetupDependencies, VisTypeXyPluginStartDependencies - > { + > +{ public setup( core: VisTypeXyCoreSetup, { expressions, visualizations, charts, usageCollection }: VisTypeXyPluginSetupDependencies diff --git a/src/plugins/vis_types/xy/public/services.ts b/src/plugins/vis_types/xy/public/services.ts index 7f1f7e872815..d8c8689eee29 100644 --- a/src/plugins/vis_types/xy/public/services.ts +++ b/src/plugins/vis_types/xy/public/services.ts @@ -12,32 +12,27 @@ import { createGetterSetter } from '../../../kibana_utils/public'; import { DataPublicPluginStart } from '../../../data/public'; import { ChartsPluginSetup, ChartsPluginStart } from '../../../charts/public'; -export const [getUISettings, setUISettings] = createGetterSetter( - 'xy core.uiSettings' -); +export const [getUISettings, setUISettings] = + createGetterSetter('xy core.uiSettings'); -export const [getDataActions, setDataActions] = createGetterSetter< - DataPublicPluginStart['actions'] ->('xy data.actions'); +export const [getDataActions, setDataActions] = + createGetterSetter('xy data.actions'); -export const [getFormatService, setFormatService] = createGetterSetter< - DataPublicPluginStart['fieldFormats'] ->('xy data.fieldFormats'); +export const [getFormatService, setFormatService] = + createGetterSetter('xy data.fieldFormats'); -export const [getThemeService, setThemeService] = createGetterSetter( - 'xy charts.theme' -); +export const [getThemeService, setThemeService] = + createGetterSetter('xy charts.theme'); -export const [getActiveCursor, setActiveCursor] = createGetterSetter< - ChartsPluginStart['activeCursor'] ->('xy charts.activeCursor'); +export const [getActiveCursor, setActiveCursor] = + createGetterSetter('xy charts.activeCursor'); -export const [getPalettesService, setPalettesService] = createGetterSetter< - ChartsPluginSetup['palettes'] ->('xy charts.palette'); +export const [getPalettesService, setPalettesService] = + createGetterSetter('xy charts.palette'); export const [getDocLinks, setDocLinks] = createGetterSetter('DocLinks'); -export const [getTrackUiMetric, setTrackUiMetric] = createGetterSetter< - (metricType: UiCounterMetricType, eventName: string | string[]) => void ->('trackUiMetric'); +export const [getTrackUiMetric, setTrackUiMetric] = + createGetterSetter<(metricType: UiCounterMetricType, eventName: string | string[]) => void>( + 'trackUiMetric' + ); diff --git a/src/plugins/vis_types/xy/public/utils/accessors.tsx b/src/plugins/vis_types/xy/public/utils/accessors.tsx index 748430e3b16a..9566f819ba14 100644 --- a/src/plugins/vis_types/xy/public/utils/accessors.tsx +++ b/src/plugins/vis_types/xy/public/utils/accessors.tsx @@ -36,33 +36,32 @@ export const isRangeAggType = (type: string | null) => * @param aspect * @param isComplex - forces to be functional/complex accessor */ -export const getComplexAccessor = (fieldName: string, isComplex: boolean = false) => ( - aspect: Aspect, - index?: number -): Accessor | AccessorFn | undefined => { - if (!aspect.accessor || aspect.aggType === SHARD_DELAY) { - return; - } - - if (!((isComplex || isRangeAggType(aspect.aggType)) && aspect.formatter)) { - return aspect.accessor; - } - - const formatter = aspect.formatter; - const accessor = aspect.accessor; - const fn: AccessorFn = (d) => { - const v = d[accessor]; - if (v === undefined) { +export const getComplexAccessor = + (fieldName: string, isComplex: boolean = false) => + (aspect: Aspect, index?: number): Accessor | AccessorFn | undefined => { + if (!aspect.accessor || aspect.aggType === SHARD_DELAY) { return; } - const f = formatter(v); - return f; - }; - fn.fieldName = getFieldName(fieldName, index); + if (!((isComplex || isRangeAggType(aspect.aggType)) && aspect.formatter)) { + return aspect.accessor; + } + + const formatter = aspect.formatter; + const accessor = aspect.accessor; + const fn: AccessorFn = (d) => { + const v = d[accessor]; + if (v === undefined) { + return; + } + const f = formatter(v); + return f; + }; - return fn; -}; + fn.fieldName = getFieldName(fieldName, index); + + return fn; + }; export const getSplitSeriesAccessorFnMap = ( splitSeriesAccessors: Array diff --git a/src/plugins/vis_types/xy/public/utils/get_color_picker.test.tsx b/src/plugins/vis_types/xy/public/utils/get_color_picker.test.tsx index e015521f7436..352cff0d4c4a 100644 --- a/src/plugins/vis_types/xy/public/utils/get_color_picker.test.tsx +++ b/src/plugins/vis_types/xy/public/utils/get_color_picker.test.tsx @@ -26,14 +26,14 @@ jest.mock('@elastic/charts', () => { describe('getColorPicker', function () { const mockState = new Map(); - const uiState = ({ + const uiState = { get: jest .fn() .mockImplementation((key, fallback) => (mockState.has(key) ? mockState.get(key) : fallback)), set: jest.fn().mockImplementation((key, value) => mockState.set(key, value)), emit: jest.fn(), setSilent: jest.fn(), - } as unknown) as PersistedState; + } as unknown as PersistedState; let wrapperProps: LegendColorPickerProps; const Component: ComponentType = getColorPicker( @@ -57,8 +57,7 @@ describe('getColorPicker', function () { splitAccessors: {}, seriesKeys: ['Logstash Airways', 'col-2-1'], specId: 'histogram-col-2-1', - key: - 'groupId{__pseudo_stacked_group-ValueAxis-1__}spec{histogram-col-2-1}yAccessor{col-2-1}splitAccessors{col-1-3-Logstash Airways}', + key: 'groupId{__pseudo_stacked_group-ValueAxis-1__}spec{histogram-col-2-1}yAccessor{col-2-1}splitAccessors{col-1-3-Logstash Airways}', } as XYChartSeriesIdentifier, ], }; diff --git a/src/plugins/vis_types/xy/public/utils/get_color_picker.tsx b/src/plugins/vis_types/xy/public/utils/get_color_picker.tsx index 1b5a16a8894a..6e1a61875b5a 100644 --- a/src/plugins/vis_types/xy/public/utils/get_color_picker.tsx +++ b/src/plugins/vis_types/xy/public/utils/get_color_picker.tsx @@ -28,69 +28,65 @@ function getAnchorPosition(legendPosition: Position): PopoverAnchorPosition { const KEY_CODE_ENTER = 13; -export const getColorPicker = ( - legendPosition: Position, - setColor: (newColor: string | null, seriesKey: string | number) => void, - getSeriesName: (series: XYChartSeriesIdentifier) => SeriesName, - paletteName: string, - uiState: PersistedState -): LegendColorPicker => ({ - anchor, - color, - onClose, - onChange, - seriesIdentifiers: [seriesIdentifier], -}) => { - const seriesName = getSeriesName(seriesIdentifier as XYChartSeriesIdentifier); - const overwriteColors: Record = uiState?.get('vis.colors', {}); - const colorIsOverwritten = Object.keys(overwriteColors).includes(seriesName as string); - let keyDownEventOn = false; +export const getColorPicker = + ( + legendPosition: Position, + setColor: (newColor: string | null, seriesKey: string | number) => void, + getSeriesName: (series: XYChartSeriesIdentifier) => SeriesName, + paletteName: string, + uiState: PersistedState + ): LegendColorPicker => + ({ anchor, color, onClose, onChange, seriesIdentifiers: [seriesIdentifier] }) => { + const seriesName = getSeriesName(seriesIdentifier as XYChartSeriesIdentifier); + const overwriteColors: Record = uiState?.get('vis.colors', {}); + const colorIsOverwritten = Object.keys(overwriteColors).includes(seriesName as string); + let keyDownEventOn = false; - const handleChange = (newColor: string | null) => { - if (!seriesName) { - return; - } - if (newColor) { - onChange(newColor); - } - setColor(newColor, seriesName); - // close the popover if no color is applied or the user has clicked a color - if (!newColor || !keyDownEventOn) { - onClose(); - } - }; + const handleChange = (newColor: string | null) => { + if (!seriesName) { + return; + } + if (newColor) { + onChange(newColor); + } + setColor(newColor, seriesName); + // close the popover if no color is applied or the user has clicked a color + if (!newColor || !keyDownEventOn) { + onClose(); + } + }; - const onKeyDown = (e: React.KeyboardEvent) => { - if (e.keyCode === KEY_CODE_ENTER) { - onClose?.(); - } - keyDownEventOn = true; - }; + const onKeyDown = (e: React.KeyboardEvent) => { + if (e.keyCode === KEY_CODE_ENTER) { + onClose?.(); + } + keyDownEventOn = true; + }; - const handleOutsideClick = useCallback(() => { - onClose?.(); - }, [onClose]); + const handleOutsideClick = useCallback(() => { + onClose?.(); + }, [onClose]); - return ( - - - - - - ); -}; + return ( + + + + + + ); + }; diff --git a/src/plugins/vis_types/xy/public/utils/get_series_name_fn.test.ts b/src/plugins/vis_types/xy/public/utils/get_series_name_fn.test.ts index 8853e6075e26..88be9ab16089 100644 --- a/src/plugins/vis_types/xy/public/utils/get_series_name_fn.test.ts +++ b/src/plugins/vis_types/xy/public/utils/get_series_name_fn.test.ts @@ -63,7 +63,7 @@ const aspects = { ], }; -const series = ({ +const series = { specId: 'histogram-col-1-1', seriesKeys: ['col-1-1'], yAccessor: 'col-1-1', @@ -73,12 +73,12 @@ const series = ({ groupId: '__pseudo_stacked_group-ValueAxis-1__', seriesType: 'bar', isStacked: true, -} as unknown) as XYChartSeriesIdentifier; +} as unknown as XYChartSeriesIdentifier; const splitAccessors = new Map(); splitAccessors.set('col-1-3', 'Weather Delay'); -const seriesSplitAccessors = ({ +const seriesSplitAccessors = { specId: 'histogram-col-2-1', seriesKeys: ['Weather Delay', 'col-2-1'], yAccessor: 'col-2-1', @@ -88,7 +88,7 @@ const seriesSplitAccessors = ({ groupId: '__pseudo_stacked_group-ValueAxis-1__', seriesType: 'bar', isStacked: true, -} as unknown) as XYChartSeriesIdentifier; +} as unknown as XYChartSeriesIdentifier; describe('getSeriesNameFn', () => { it('returns the y aspects title if splitAccessors are empty array', () => { diff --git a/src/plugins/vis_types/xy/public/utils/get_series_name_fn.ts b/src/plugins/vis_types/xy/public/utils/get_series_name_fn.ts index 137f8a555801..8019e36c1e6d 100644 --- a/src/plugins/vis_types/xy/public/utils/get_series_name_fn.ts +++ b/src/plugins/vis_types/xy/public/utils/get_series_name_fn.ts @@ -29,23 +29,20 @@ function getSplitValues( } export const getSeriesNameFn = (aspects: VisConfig['aspects'], multipleY = false) => - memoize( - ({ splitAccessors, yAccessor }: XYChartSeriesIdentifier): SeriesName => { - const splitValues = getSplitValues(splitAccessors, aspects.series); - const yAccessorTitle = - aspects.y.find(({ accessor }) => accessor === yAccessor)?.title ?? null; - - if (!yAccessorTitle) { - return null; - } + memoize(({ splitAccessors, yAccessor }: XYChartSeriesIdentifier): SeriesName => { + const splitValues = getSplitValues(splitAccessors, aspects.series); + const yAccessorTitle = aspects.y.find(({ accessor }) => accessor === yAccessor)?.title ?? null; - if (multipleY) { - if (splitValues.length === 0) { - return yAccessorTitle; - } - return `${splitValues.join(' - ')}: ${yAccessorTitle}`; - } + if (!yAccessorTitle) { + return null; + } - return splitValues.length > 0 ? splitValues.join(' - ') : yAccessorTitle; + if (multipleY) { + if (splitValues.length === 0) { + return yAccessorTitle; + } + return `${splitValues.join(' - ')}: ${yAccessorTitle}`; } - ); + + return splitValues.length > 0 ? splitValues.join(' - ') : yAccessorTitle; + }); diff --git a/src/plugins/vis_types/xy/public/vis_component.tsx b/src/plugins/vis_types/xy/public/vis_component.tsx index 3e4f3e1ffe29..f4d566f49602 100644 --- a/src/plugins/vis_types/xy/public/vis_component.tsx +++ b/src/plugins/vis_types/xy/public/vis_component.tsx @@ -221,9 +221,10 @@ const VisComponent = (props: VisComponentProps) => { config.xAxis.scale.type === ScaleType.Ordinal ? undefined : getAdjustedDomain(visData.rows, config.aspects.x, timeZone, xDomain, hasBars); - const legendPosition = useMemo(() => config.legend.position ?? Position.Right, [ - config.legend.position, - ]); + const legendPosition = useMemo( + () => config.legend.position ?? Position.Right, + [config.legend.position] + ); const isDarkMode = getThemeService().useDarkMode(); const getSeriesName = getSeriesNameFn(config.aspects, config.aspects.y.length > 1); @@ -231,11 +232,10 @@ const VisComponent = (props: VisComponentProps) => { return { accessor, formatter }; }); - const allSeries = useMemo(() => getAllSeries(visData.rows, splitAccessors, config.aspects.y), [ - config.aspects.y, - splitAccessors, - visData.rows, - ]); + const allSeries = useMemo( + () => getAllSeries(visData.rows, splitAccessors, config.aspects.y), + [config.aspects.y, splitAccessors, visData.rows] + ); const getSeriesColor = useCallback( (series: XYChartSeriesIdentifier) => { diff --git a/src/plugins/visualizations/public/embeddable/create_vis_embeddable_from_object.ts b/src/plugins/visualizations/public/embeddable/create_vis_embeddable_from_object.ts index b2c729b5cbea..cfa871f17b0e 100644 --- a/src/plugins/visualizations/public/embeddable/create_vis_embeddable_from_object.ts +++ b/src/plugins/visualizations/public/embeddable/create_vis_embeddable_from_object.ts @@ -33,63 +33,65 @@ import { SavedVisualizationsLoader } from '../saved_visualizations'; import { IndexPattern } from '../../../data/public'; import { createVisualizeEmbeddableAsync } from './visualize_embeddable_async'; -export const createVisEmbeddableFromObject = (deps: VisualizeEmbeddableFactoryDeps) => async ( - vis: Vis, - input: Partial & { id: string }, - savedVisualizationsLoader?: SavedVisualizationsLoader, - attributeService?: AttributeService< - VisualizeSavedObjectAttributes, - VisualizeByValueInput, - VisualizeByReferenceInput - >, - parent?: IContainer -): Promise => { - const savedVisualizations = getSavedVisualizationsLoader(); +export const createVisEmbeddableFromObject = + (deps: VisualizeEmbeddableFactoryDeps) => + async ( + vis: Vis, + input: Partial & { id: string }, + savedVisualizationsLoader?: SavedVisualizationsLoader, + attributeService?: AttributeService< + VisualizeSavedObjectAttributes, + VisualizeByValueInput, + VisualizeByReferenceInput + >, + parent?: IContainer + ): Promise => { + const savedVisualizations = getSavedVisualizationsLoader(); - try { - const visId = vis.id as string; + try { + const visId = vis.id as string; - const editPath = visId ? savedVisualizations.urlFor(visId) : '#/edit_by_value'; + const editPath = visId ? savedVisualizations.urlFor(visId) : '#/edit_by_value'; - const editUrl = visId - ? getHttp().basePath.prepend(`/app/visualize${savedVisualizations.urlFor(visId)}`) - : ''; - const isLabsEnabled = getUISettings().get(VISUALIZE_ENABLE_LABS_SETTING); + const editUrl = visId + ? getHttp().basePath.prepend(`/app/visualize${savedVisualizations.urlFor(visId)}`) + : ''; + const isLabsEnabled = getUISettings().get(VISUALIZE_ENABLE_LABS_SETTING); - if (!isLabsEnabled && vis.type.stage === 'experimental') { - return new DisabledLabEmbeddable(vis.title, input); - } + if (!isLabsEnabled && vis.type.stage === 'experimental') { + return new DisabledLabEmbeddable(vis.title, input); + } - let indexPatterns: IndexPattern[] = []; + let indexPatterns: IndexPattern[] = []; - if (vis.type.getUsedIndexPattern) { - indexPatterns = await vis.type.getUsedIndexPattern(vis.params); - } else if (vis.data.indexPattern) { - indexPatterns = [vis.data.indexPattern]; - } + if (vis.type.getUsedIndexPattern) { + indexPatterns = await vis.type.getUsedIndexPattern(vis.params); + } else if (vis.data.indexPattern) { + indexPatterns = [vis.data.indexPattern]; + } - const capabilities = { - visualizeSave: Boolean(getCapabilities().visualize.save), - dashboardSave: Boolean(getCapabilities().dashboard?.showWriteControls), - }; + const capabilities = { + visualizeSave: Boolean(getCapabilities().visualize.save), + dashboardSave: Boolean(getCapabilities().dashboard?.showWriteControls), + }; - return createVisualizeEmbeddableAsync( - getTimeFilter(), - { - vis, - indexPatterns, - editPath, - editUrl, - deps, - capabilities, - }, - input, - attributeService, - savedVisualizationsLoader, - parent - ); - } catch (e) { - console.error(e); // eslint-disable-line no-console - return new ErrorEmbeddable(e, input, parent); - } -}; + return createVisualizeEmbeddableAsync( + getTimeFilter(), + { + vis, + indexPatterns, + editPath, + editUrl, + deps, + capabilities, + }, + input, + attributeService, + savedVisualizationsLoader, + parent + ); + } catch (e) { + console.error(e); // eslint-disable-line no-console + return new ErrorEmbeddable(e, input, parent); + } + }; diff --git a/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts b/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts index 637334067b51..75809bd06ba4 100644 --- a/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts +++ b/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts @@ -85,7 +85,8 @@ type ExpressionLoader = InstanceType; export class VisualizeEmbeddable extends Embeddable - implements ReferenceOrValueEmbeddable { + implements ReferenceOrValueEmbeddable +{ private handler?: ExpressionLoader; private timefilter: TimefilterContract; private timeRange?: TimeRange; diff --git a/src/plugins/visualizations/public/embeddable/visualize_embeddable_factory.tsx b/src/plugins/visualizations/public/embeddable/visualize_embeddable_factory.tsx index 872132416352..9e22b33bdee9 100644 --- a/src/plugins/visualizations/public/embeddable/visualize_embeddable_factory.tsx +++ b/src/plugins/visualizations/public/embeddable/visualize_embeddable_factory.tsx @@ -70,7 +70,8 @@ export class VisualizeEmbeddableFactory VisualizeOutput | EmbeddableOutput, VisualizeEmbeddable | DisabledLabEmbeddable, VisualizationAttributes - > { + > +{ public readonly type = VISUALIZE_EMBEDDABLE_TYPE; private attributeService?: AttributeService< @@ -205,7 +206,7 @@ export class VisualizeEmbeddableFactory savedVis.copyOnSave = false; savedVis.description = ''; savedVis.searchSourceFields = visObj?.data.searchSource?.getSerializedFields(); - const serializedVis = ((visObj as unknown) as Vis).serialize(); + const serializedVis = (visObj as unknown as Vis).serialize(); const { params, data } = serializedVis; savedVis.visState = { title, @@ -251,7 +252,7 @@ export class VisualizeEmbeddableFactory } public inject(_state: EmbeddableStateWithType, references: SavedObjectReference[]) { - const state = (_state as unknown) as VisualizeInput; + const state = _state as unknown as VisualizeInput; const { type, params } = state.savedVis ?? {}; @@ -264,7 +265,7 @@ export class VisualizeEmbeddableFactory } public extract(_state: EmbeddableStateWithType) { - const state = (_state as unknown) as VisualizeInput; + const state = _state as unknown as VisualizeInput; const references = []; if (state.savedVis?.data.searchSource) { diff --git a/src/plugins/visualizations/public/plugin.ts b/src/plugins/visualizations/public/plugin.ts index ae97080b31fc..ee3e914aa4bc 100644 --- a/src/plugins/visualizations/public/plugin.ts +++ b/src/plugins/visualizations/public/plugin.ts @@ -120,7 +120,8 @@ export class VisualizationsPlugin VisualizationsStart, VisualizationsSetupDeps, VisualizationsStartDeps - > { + > +{ private readonly types: TypesService = new TypesService(); private getStartServicesOrDie?: StartServicesGetter; diff --git a/src/plugins/visualizations/public/saved_visualizations/_saved_vis.ts b/src/plugins/visualizations/public/saved_visualizations/_saved_vis.ts index f1fba28297e4..fb6c99ac8ef0 100644 --- a/src/plugins/visualizations/public/saved_visualizations/_saved_vis.ts +++ b/src/plugins/visualizations/public/saved_visualizations/_saved_vis.ts @@ -103,7 +103,7 @@ export function createSavedVisClass(services: SavedVisServices) { version: 1, }, afterESResp: async (savedObject: SavedObject) => { - const savedVis = (savedObject as any) as ISavedVis; + const savedVis = savedObject as any as ISavedVis; savedVis.visState = await updateOldState(savedVis.visState); if (savedVis.searchSourceFields?.index) { await services.indexPatterns.get(savedVis.searchSourceFields.index as any); @@ -111,7 +111,7 @@ export function createSavedVisClass(services: SavedVisServices) { if (savedVis.savedSearchId) { await savedSearch.get(savedVis.savedSearchId); } - return (savedVis as any) as SavedObject; + return savedVis as any as SavedObject; }, }); this.showInRecentlyAccessed = true; @@ -121,5 +121,5 @@ export function createSavedVisClass(services: SavedVisServices) { } } - return (SavedVis as unknown) as new (opts: Record | string) => SavedObject; + return SavedVis as unknown as new (opts: Record | string) => SavedObject; } diff --git a/src/plugins/visualizations/public/saved_visualizations/saved_visualization_references/saved_visualization_references.test.ts b/src/plugins/visualizations/public/saved_visualizations/saved_visualization_references/saved_visualization_references.test.ts index 9c832414e7f0..ee0e3d481929 100644 --- a/src/plugins/visualizations/public/saved_visualizations/saved_visualization_references/saved_visualization_references.test.ts +++ b/src/plugins/visualizations/public/saved_visualizations/saved_visualization_references/saved_visualization_references.test.ts @@ -115,11 +115,11 @@ describe('injectReferences', () => { }); test('injects references into context', () => { - const context = ({ + const context = { id: '1', title: 'test', savedSearchRefName: 'search_0', - visState: ({ + visState: { type: 'input_control_vis', params: { controls: [ @@ -132,8 +132,8 @@ describe('injectReferences', () => { }, ], }, - } as unknown) as SavedVisState, - } as unknown) as VisSavedObject; + } as unknown as SavedVisState, + } as unknown as VisSavedObject; const references = [ { name: 'search_0', @@ -182,10 +182,10 @@ describe('injectReferences', () => { }); test(`fails when it can't find the index pattern reference in the array`, () => { - const context = ({ + const context = { id: '1', title: 'test', - visState: ({ + visState: { type: 'input_control_vis', params: { controls: [ @@ -195,8 +195,8 @@ describe('injectReferences', () => { }, ], }, - } as unknown) as SavedVisState, - } as unknown) as VisSavedObject; + } as unknown as SavedVisState, + } as unknown as VisSavedObject; expect(() => injectReferences(context, [])).toThrowErrorMatchingInlineSnapshot( `"Could not find index pattern reference \\"control_0_index_pattern\\""` ); diff --git a/src/plugins/visualizations/public/services.ts b/src/plugins/visualizations/public/services.ts index b135e0556ace..f1ab9077cd20 100644 --- a/src/plugins/visualizations/public/services.ts +++ b/src/plugins/visualizations/public/services.ts @@ -36,9 +36,8 @@ export const [getApplication, setApplication] = createGetterSetter('Embeddable'); -export const [getSavedObjects, setSavedObjects] = createGetterSetter( - 'SavedObjects' -); +export const [getSavedObjects, setSavedObjects] = + createGetterSetter('SavedObjects'); export const [getTypes, setTypes] = createGetterSetter('Types'); @@ -48,27 +47,22 @@ export const [getTimeFilter, setTimeFilter] = createGetterSetter('Search'); -export const [getUsageCollector, setUsageCollector] = createGetterSetter( - 'UsageCollection' -); +export const [getUsageCollector, setUsageCollector] = + createGetterSetter('UsageCollection'); export const [getExpressions, setExpressions] = createGetterSetter('Expressions'); export const [getUiActions, setUiActions] = createGetterSetter('UiActions'); -export const [ - getSavedVisualizationsLoader, - setSavedVisualizationsLoader, -] = createGetterSetter('SavedVisualisationsLoader'); +export const [getSavedVisualizationsLoader, setSavedVisualizationsLoader] = + createGetterSetter('SavedVisualisationsLoader'); -export const [getAggs, setAggs] = createGetterSetter( - 'AggConfigs' -); +export const [getAggs, setAggs] = + createGetterSetter('AggConfigs'); export const [getOverlays, setOverlays] = createGetterSetter('Overlays'); export const [getChrome, setChrome] = createGetterSetter('Chrome'); -export const [getSavedSearchLoader, setSavedSearchLoader] = createGetterSetter( - 'savedSearchLoader' -); +export const [getSavedSearchLoader, setSavedSearchLoader] = + createGetterSetter('savedSearchLoader'); diff --git a/src/plugins/visualizations/public/wizard/agg_based_selection/agg_based_selection.test.tsx b/src/plugins/visualizations/public/wizard/agg_based_selection/agg_based_selection.test.tsx index c96dc17abf83..e3707a7aace7 100644 --- a/src/plugins/visualizations/public/wizard/agg_based_selection/agg_based_selection.test.tsx +++ b/src/plugins/visualizations/public/wizard/agg_based_selection/agg_based_selection.test.tsx @@ -48,7 +48,7 @@ describe('AggBasedSelection', () => { const visTypes: TypesStart = { get(id: string): BaseVisType { - return (_visTypes.find((vis) => vis.name === id) as unknown) as BaseVisType; + return _visTypes.find((vis) => vis.name === id) as unknown as BaseVisType; }, all: () => _visTypes, getAliases: () => [], diff --git a/src/plugins/visualizations/public/wizard/group_selection/group_selection.test.tsx b/src/plugins/visualizations/public/wizard/group_selection/group_selection.test.tsx index 708be0d74938..04824ae25704 100644 --- a/src/plugins/visualizations/public/wizard/group_selection/group_selection.test.tsx +++ b/src/plugins/visualizations/public/wizard/group_selection/group_selection.test.tsx @@ -58,17 +58,17 @@ describe('GroupSelection', () => { const visTypesRegistry = (visTypes: BaseVisType[]): TypesStart => { return { get(id: string): BaseVisType { - return (visTypes.find((vis) => vis.name === id) as unknown) as BaseVisType; + return visTypes.find((vis) => vis.name === id) as unknown as BaseVisType; }, all: () => { - return (visTypes as unknown) as BaseVisType[]; + return visTypes as unknown as BaseVisType[]; }, getAliases: () => [], unRegisterAlias: () => [], getByGroup: (group: VisGroups) => { - return (visTypes.filter((type) => { + return visTypes.filter((type) => { return type.group === group; - }) as unknown) as BaseVisType[]; + }) as unknown as BaseVisType[]; }, }; }; 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 29d8c58e617e..7514f467840e 100644 --- a/src/plugins/visualizations/public/wizard/new_vis_modal.test.tsx +++ b/src/plugins/visualizations/public/wizard/new_vis_modal.test.tsx @@ -58,7 +58,7 @@ describe('NewVisModal', () => { ] as BaseVisType[]; const visTypes: TypesStart = { get(id: string): BaseVisType { - return (_visTypes.find((vis) => vis.name === id) as unknown) as BaseVisType; + return _visTypes.find((vis) => vis.name === id) as unknown as BaseVisType; }, all: () => _visTypes, getAliases: () => [], @@ -190,7 +190,7 @@ describe('NewVisModal', () => { originatingApp={'coolJestTestApp'} addBasePath={addBasePath} uiSettings={uiSettings} - application={({ navigateToApp } as unknown) as ApplicationStart} + application={{ navigateToApp } as unknown as ApplicationStart} docLinks={docLinks as DocLinksStart} stateTransfer={stateTransfer} savedObjects={{} as SavedObjectsStart} @@ -216,7 +216,7 @@ describe('NewVisModal', () => { editorParams={['foo=true', 'bar=42']} addBasePath={addBasePath} uiSettings={uiSettings} - application={({ navigateToApp } as unknown) as ApplicationStart} + application={{ navigateToApp } as unknown as ApplicationStart} docLinks={docLinks as DocLinksStart} savedObjects={{} as SavedObjectsStart} /> diff --git a/src/plugins/visualizations/server/migrations/visualization_saved_object_migrations.test.ts b/src/plugins/visualizations/server/migrations/visualization_saved_object_migrations.test.ts index 00c7e26715e6..d9801b8a5950 100644 --- a/src/plugins/visualizations/server/migrations/visualization_saved_object_migrations.test.ts +++ b/src/plugins/visualizations/server/migrations/visualization_saved_object_migrations.test.ts @@ -9,7 +9,7 @@ import { visualizationSavedObjectTypeMigrations } from './visualization_saved_object_migrations'; import { SavedObjectMigrationContext, SavedObjectMigrationFn } from 'kibana/server'; -const savedObjectMigrationContext = (null as unknown) as SavedObjectMigrationContext; +const savedObjectMigrationContext = null as unknown as SavedObjectMigrationContext; const testMigrateMatchAllQuery = (migrate: Function) => { it('should migrate obsolete match_all query', () => { @@ -922,11 +922,11 @@ describe('migration visualization', () => { describe('7.3.0', () => { const logMsgArr: string[] = []; - const logger = ({ + const logger = { log: { warn: (msg: string) => logMsgArr.push(msg), }, - } as unknown) as SavedObjectMigrationContext; + } as unknown as SavedObjectMigrationContext; const migrate = (doc: any) => visualizationSavedObjectTypeMigrations['7.3.0']( @@ -1636,10 +1636,8 @@ describe('migration visualization', () => { const migratedtimeSeriesDoc = migrate(timeSeriesDoc); expect(migratedtimeSeriesDoc.attributes.kibanaSavedObjectMeta.searchSourceJSON).toEqual('{}'); const { kibanaSavedObjectMeta, ...attributes } = migratedtimeSeriesDoc.attributes; - const { - kibanaSavedObjectMeta: oldKibanaSavedObjectMeta, - ...oldAttributes - } = migratedtimeSeriesDoc.attributes; + const { kibanaSavedObjectMeta: oldKibanaSavedObjectMeta, ...oldAttributes } = + migratedtimeSeriesDoc.attributes; expect(attributes).toEqual(oldAttributes); }); }); diff --git a/src/plugins/visualizations/server/plugin.ts b/src/plugins/visualizations/server/plugin.ts index 6b87c0206347..991d1b16ee23 100644 --- a/src/plugins/visualizations/server/plugin.ts +++ b/src/plugins/visualizations/server/plugin.ts @@ -26,7 +26,8 @@ import type { EmbeddableSetup } from '../../embeddable/server'; import { visualizeEmbeddableFactory } from './embeddable/visualize_embeddable_factory'; export class VisualizationsPlugin - implements Plugin { + implements Plugin +{ private readonly logger: Logger; constructor(initializerContext: PluginInitializerContext) { diff --git a/src/plugins/visualizations/server/usage_collector/get_usage_collector.test.ts b/src/plugins/visualizations/server/usage_collector/get_usage_collector.test.ts index 24c290ca849e..ab31d622e62c 100644 --- a/src/plugins/visualizations/server/usage_collector/get_usage_collector.test.ts +++ b/src/plugins/visualizations/server/usage_collector/get_usage_collector.test.ts @@ -85,14 +85,14 @@ const enlargedMockSavedObjects = [ describe('Visualizations usage collector', () => { const getMockCallCluster = (savedObjects: unknown[]) => - (({ + ({ createPointInTimeFinder: jest.fn().mockResolvedValue({ close: jest.fn(), find: function* asyncGenerator() { yield { saved_objects: savedObjects }; }, }), - } as unknown) as SavedObjectsClientContract); + } as unknown as SavedObjectsClientContract); test('Returns undefined when no results found (undefined)', async () => { const result = await getStats(getMockCallCluster(undefined as any)); diff --git a/src/plugins/visualize/public/application/components/visualize_editor.tsx b/src/plugins/visualize/public/application/components/visualize_editor.tsx index 546738bf36c3..e81a886cee5a 100644 --- a/src/plugins/visualize/public/application/components/visualize_editor.tsx +++ b/src/plugins/visualize/public/application/components/visualize_editor.tsx @@ -57,8 +57,11 @@ export const VisualizeEditor = ({ onAppLeave }: VisualizeAppProps) => { useEffect(() => { const { stateTransferService, data } = services; - const { originatingApp: value, searchSessionId, embeddableId } = - stateTransferService.getIncomingEditorState(VisualizeConstants.APP_ID) || {}; + const { + originatingApp: value, + searchSessionId, + embeddableId, + } = stateTransferService.getIncomingEditorState(VisualizeConstants.APP_ID) || {}; if (searchSessionId) { data.search.session.continue(searchSessionId); diff --git a/src/plugins/visualize/public/application/utils/create_visualize_app_state.test.ts b/src/plugins/visualize/public/application/utils/create_visualize_app_state.test.ts index 3711a0d945f9..0474e60cea67 100644 --- a/src/plugins/visualize/public/application/utils/create_visualize_app_state.test.ts +++ b/src/plugins/visualize/public/application/utils/create_visualize_app_state.test.ts @@ -28,10 +28,10 @@ jest.mock('./migrate_app_state', () => ({ const { createStateContainer, syncState } = jest.requireMock('../../../../kibana_utils/public'); describe('createVisualizeAppState', () => { - const kbnUrlStateStorage = ({ + const kbnUrlStateStorage = { set: jest.fn(), get: jest.fn(() => ({ linked: false })), - } as unknown) as IKbnUrlStateStorage; + } as unknown as IKbnUrlStateStorage; const { stateContainer, stopStateSync } = createVisualizeAppState({ stateDefaults: visualizeAppStateStub, diff --git a/src/plugins/visualize/public/application/utils/create_visualize_app_state.ts b/src/plugins/visualize/public/application/utils/create_visualize_app_state.ts index 10c573090da3..9e6ab5b1d7fc 100644 --- a/src/plugins/visualize/public/application/utils/create_visualize_app_state.ts +++ b/src/plugins/visualize/public/application/utils/create_visualize_app_state.ts @@ -39,12 +39,14 @@ const pureTransitions = { ...vis, }, }), - unlinkSavedSearch: (state) => ({ query, parentFilters = [] }) => ({ - ...state, - query: query || state.query, - filters: union(state.filters, parentFilters), - linked: false, - }), + unlinkSavedSearch: + (state) => + ({ query, parentFilters = [] }) => ({ + ...state, + query: query || state.query, + filters: union(state.filters, parentFilters), + linked: false, + }), updateVisState: (state) => (newVisState) => ({ ...state, vis: toObject(newVisState) }), updateSavedQuery: (state) => (savedQueryId) => { const updatedState = { diff --git a/src/plugins/visualize/public/application/utils/get_top_nav_config.tsx b/src/plugins/visualize/public/application/utils/get_top_nav_config.tsx index a4421d9535c7..0dc37ca00a6a 100644 --- a/src/plugins/visualize/public/application/utils/get_top_nav_config.tsx +++ b/src/plugins/visualize/public/application/utils/get_top_nav_config.tsx @@ -64,7 +64,7 @@ const SavedObjectSaveModalDashboard = withSuspense(LazySavedObjectSaveModalDashb export const showPublicUrlSwitch = (anonymousUserCapabilities: Capabilities) => { if (!anonymousUserCapabilities.visualize) return false; - const visualize = (anonymousUserCapabilities.visualize as unknown) as VisualizeCapabilities; + const visualize = anonymousUserCapabilities.visualize as unknown as VisualizeCapabilities; return !!visualize.show; }; diff --git a/src/plugins/visualize/public/application/utils/get_visualization_instance.test.ts b/src/plugins/visualize/public/application/utils/get_visualization_instance.test.ts index 4b00a1578963..83462ba9ae7b 100644 --- a/src/plugins/visualize/public/application/utils/get_visualization_instance.test.ts +++ b/src/plugins/visualize/public/application/utils/get_visualization_instance.test.ts @@ -152,7 +152,7 @@ describe('getVisualizationInstanceInput', () => { }); test('should create new instances of savedVis, vis and embeddableHandler', async () => { - const input = ({ + const input = { id: 'test-id', savedVis: { title: '', @@ -179,13 +179,9 @@ describe('getVisualizationInstanceInput', () => { }, }, }, - } as unknown) as VisualizeInput; - const { - savedVis, - savedSearch, - vis, - embeddableHandler, - } = await getVisualizationInstanceFromInput(mockServices, input); + } as unknown as VisualizeInput; + const { savedVis, savedSearch, vis, embeddableHandler } = + await getVisualizationInstanceFromInput(mockServices, input); expect(mockServices.savedVisualizations.get).toHaveBeenCalled(); expect(mockServices.visualizations.createVis).toHaveBeenCalledWith( diff --git a/src/plugins/visualize/public/application/utils/get_visualization_instance.ts b/src/plugins/visualize/public/application/utils/get_visualization_instance.ts index 8898076d7ddb..88797ce264e2 100644 --- a/src/plugins/visualize/public/application/utils/get_visualization_instance.ts +++ b/src/plugins/visualize/public/application/utils/get_visualization_instance.ts @@ -33,12 +33,8 @@ const createVisualizeEmbeddableAndLinkSavedSearch = async ( vis: Vis, visualizeServices: VisualizeServices ) => { - const { - data, - createVisEmbeddableFromObject, - savedObjects, - savedObjectsPublic, - } = visualizeServices; + const { data, createVisEmbeddableFromObject, savedObjects, savedObjectsPublic } = + visualizeServices; const embeddableHandler = (await createVisEmbeddableFromObject(vis, { id: '', timeRange: data.query.timefilter.timefilter.getTime(), @@ -49,7 +45,7 @@ const createVisualizeEmbeddableAndLinkSavedSearch = async ( embeddableHandler.getOutput$().subscribe((output) => { if (output.error && !isErrorRelatedToRuntimeFields(output.error)) { data.search.showError( - ((output.error as unknown) as ExpressionValueError['error']).original || output.error + (output.error as unknown as ExpressionValueError['error']).original || output.error ); } }); diff --git a/src/plugins/visualize/public/application/utils/get_visualize_list_item_link.test.ts b/src/plugins/visualize/public/application/utils/get_visualize_list_item_link.test.ts index 8a7bc33001d5..e138acf2e9e8 100644 --- a/src/plugins/visualize/public/application/utils/get_visualize_list_item_link.test.ts +++ b/src/plugins/visualize/public/application/utils/get_visualize_list_item_link.test.ts @@ -21,11 +21,11 @@ jest.mock('../../services', () => { }; }); -const application = ({ +const application = { getUrlForApp: jest.fn((appId: string, options?: { path?: string; absolute?: boolean }) => { return `/app/${appId}${options?.path}`; }), -} as unknown) as ApplicationStart; +} as unknown as ApplicationStart; const history = createHashHistory(); const kbnUrlStateStorage = createKbnUrlStateStorage({ diff --git a/src/plugins/visualize/public/application/utils/mocks.ts b/src/plugins/visualize/public/application/utils/mocks.ts index fc73ca1e6841..a7029071851c 100644 --- a/src/plugins/visualize/public/application/utils/mocks.ts +++ b/src/plugins/visualize/public/application/utils/mocks.ts @@ -17,7 +17,7 @@ export const createVisualizeServicesMock = () => { const toastNotifications = coreStartMock.notifications.toasts; const visualizations = visualizationsPluginMock.createStartContract(); - return ({ + return { ...coreStartMock, data: dataStartMock, toastNotifications, @@ -28,5 +28,5 @@ export const createVisualizeServicesMock = () => { visualizations, savedVisualizations: visualizations.savedVisualizationsLoader, createVisEmbeddableFromObject: visualizations.__LEGACY.createVisEmbeddableFromObject, - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; }; diff --git a/src/plugins/visualize/public/application/utils/use/use_editor_updates.test.ts b/src/plugins/visualize/public/application/utils/use/use_editor_updates.test.ts index b3e70043ec69..9e1cfe60caa3 100644 --- a/src/plugins/visualize/public/application/utils/use/use_editor_updates.test.ts +++ b/src/plugins/visualize/public/application/utils/use/use_editor_updates.test.ts @@ -55,14 +55,14 @@ describe('useEditorUpdates', () => { beforeEach(() => { unsubscribeStateUpdatesMock = jest.fn(); - appState = ({ + appState = { getState: jest.fn(() => visualizeAppStateStub), subscribe: jest.fn(() => unsubscribeStateUpdatesMock), transitions: { set: jest.fn(), }, - } as unknown) as VisualizeAppStateContainer; - savedVisInstance = ({ + } as unknown as VisualizeAppStateContainer; + savedVisInstance = { vis: { uiState: { on: jest.fn(), @@ -80,7 +80,7 @@ describe('useEditorUpdates', () => { reload: jest.fn(), }, savedVis: {}, - } as unknown) as SavedVisInstance; + } as unknown as SavedVisInstance; visEditorController = { render: jest.fn(), destroy: jest.fn(), diff --git a/src/plugins/visualize/public/application/utils/use/use_linked_search_updates.test.ts b/src/plugins/visualize/public/application/utils/use/use_linked_search_updates.test.ts index 7b0ecdc11d34..71b2aeaf3ebe 100644 --- a/src/plugins/visualize/public/application/utils/use/use_linked_search_updates.test.ts +++ b/src/plugins/visualize/public/application/utils/use/use_linked_search_updates.test.ts @@ -16,7 +16,7 @@ import { createVisualizeServicesMock } from '../mocks'; describe('useLinkedSearchUpdates', () => { let mockServices: jest.Mocked; const eventEmitter = new EventEmitter(); - const savedVisInstance = ({ + const savedVisInstance = { vis: { data: { searchSource: { setField: jest.fn(), setParent: jest.fn() }, @@ -24,7 +24,7 @@ describe('useLinkedSearchUpdates', () => { }, savedVis: {}, embeddableHandler: {}, - } as unknown) as SavedVisInstance; + } as unknown as SavedVisInstance; beforeEach(() => { mockServices = createVisualizeServicesMock(); @@ -37,19 +37,19 @@ describe('useLinkedSearchUpdates', () => { }); it('should subscribe on unlinkFromSavedSearch event if vis is based on saved search', () => { - const mockAppState = ({ + const mockAppState = { transitions: { unlinkSavedSearch: jest.fn(), }, - } as unknown) as VisualizeAppStateContainer; - savedVisInstance.savedSearch = ({ + } as unknown as VisualizeAppStateContainer; + savedVisInstance.savedSearch = { searchSource: { getParent: jest.fn(), getField: jest.fn(), getOwnField: jest.fn(), }, title: 'savedSearch', - } as unknown) as SavedVisInstance['savedSearch']; + } as unknown as SavedVisInstance['savedSearch']; renderHook(() => useLinkedSearchUpdates(mockServices, eventEmitter, mockAppState, savedVisInstance) diff --git a/src/plugins/visualize/public/application/utils/use/use_saved_vis_instance.test.ts b/src/plugins/visualize/public/application/utils/use/use_saved_vis_instance.test.ts index 6a597ecc4536..b142f3fcd406 100644 --- a/src/plugins/visualize/public/application/utils/use/use_saved_vis_instance.test.ts +++ b/src/plugins/visualize/public/application/utils/use/use_saved_vis_instance.test.ts @@ -55,8 +55,9 @@ jest.mock('../../../../../kibana_utils/public', () => { }; }); -const mockGetVisualizationInstance = jest.requireMock('../get_visualization_instance') - .getVisualizationInstance; +const mockGetVisualizationInstance = jest.requireMock( + '../get_visualization_instance' +).getVisualizationInstance; describe('useSavedVisInstance', () => { const coreStartMock = coreMock.createStart(); @@ -73,7 +74,7 @@ describe('useSavedVisInstance', () => { setVisEditorsRegistry(registry); - mockServices = ({ + mockServices = { ...coreStartMock, toastNotifications, stateTransferService: createEmbeddableStateTransferMock(), @@ -97,7 +98,7 @@ describe('useSavedVisInstance', () => { { name: 'gauge' }, ]), }, - } as unknown) as VisualizeServices; + } as unknown as VisualizeServices; mockDefaultEditorControllerDestroy.mockClear(); mockEmbeddableHandlerDestroy.mockClear(); diff --git a/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.test.ts b/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.test.ts index 26f866d22ce4..10b23a27ef32 100644 --- a/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.test.ts +++ b/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.test.ts @@ -44,14 +44,14 @@ describe('useVisualizeAppState', () => { connectToQueryState.mockImplementation(() => stopSyncingAppFiltersMock); const eventEmitter = new EventEmitter(); - const savedVisInstance = ({ + const savedVisInstance = { vis: { setState: jest.fn().mockResolvedValue({}), data: {}, }, savedVis: {}, embeddableHandler: {}, - } as unknown) as SavedVisInstance; + } as unknown as SavedVisInstance; let mockServices: jest.Mocked; beforeEach(() => { diff --git a/src/plugins/visualize/public/plugin.ts b/src/plugins/visualize/public/plugin.ts index d71e7fd81f1d..aef131ce8d53 100644 --- a/src/plugins/visualize/public/plugin.ts +++ b/src/plugins/visualize/public/plugin.ts @@ -81,7 +81,8 @@ export class VisualizePlugin void, VisualizePluginSetupDependencies, VisualizePluginStartDependencies - > { + > +{ private appStateUpdater = new BehaviorSubject(() => ({})); private stopUrlTracking: (() => void) | undefined = undefined; private currentHistory: ScopedHistory | undefined = undefined; diff --git a/src/plugins/visualize/public/services.ts b/src/plugins/visualize/public/services.ts index 8b8f98e9a15e..7efb054fc636 100644 --- a/src/plugins/visualize/public/services.ts +++ b/src/plugins/visualize/public/services.ts @@ -13,11 +13,8 @@ import type { UsageCollectionStart } from '../../usage_collection/public'; export const [getUISettings, setUISettings] = createGetterSetter('UISettings'); -export const [getUsageCollector, setUsageCollector] = createGetterSetter( - 'UsageCollection' -); +export const [getUsageCollector, setUsageCollector] = + createGetterSetter('UsageCollection'); -export const [ - getVisEditorsRegistry, - setVisEditorsRegistry, -] = createGetterSetter('VisEditorsRegistry'); +export const [getVisEditorsRegistry, setVisEditorsRegistry] = + createGetterSetter('VisEditorsRegistry'); diff --git a/test/accessibility/apps/management.ts b/test/accessibility/apps/management.ts index 69b799cc3b9e..0f65a3561c4a 100644 --- a/test/accessibility/apps/management.ts +++ b/test/accessibility/apps/management.ts @@ -65,7 +65,8 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await PageObjects.settings.setCustomLabel('custom label'); await testSubjects.click('toggleAdvancedSetting'); // Let's make sure the field preview is visible before testing the snapshot - const isFieldPreviewVisible = await PageObjects.indexPatternFieldEditorObjects.isFieldPreviewVisible(); + const isFieldPreviewVisible = + await PageObjects.indexPatternFieldEditorObjects.isFieldPreviewVisible(); expect(isFieldPreviewVisible).to.be(true); await a11y.testAppSnapshot(); diff --git a/test/api_integration/apis/saved_objects_management/find.ts b/test/api_integration/apis/saved_objects_management/find.ts index 6e36303cc1fe..f3f4b56cdccf 100644 --- a/test/api_integration/apis/saved_objects_management/find.ts +++ b/test/api_integration/apis/saved_objects_management/find.ts @@ -255,8 +255,7 @@ export default function ({ getService }: FtrProviderContext) { editUrl: '/management/kibana/indexPatterns/patterns/8963ca30-3224-11e8-a572-ffca06da1357', inAppUrl: { - path: - '/app/management/kibana/indexPatterns/patterns/8963ca30-3224-11e8-a572-ffca06da1357', + path: '/app/management/kibana/indexPatterns/patterns/8963ca30-3224-11e8-a572-ffca06da1357', uiCapabilitiesPath: 'management.kibana.indexPatterns', }, namespaceType: 'single', diff --git a/test/api_integration/apis/saved_objects_management/relationships.ts b/test/api_integration/apis/saved_objects_management/relationships.ts index aa488942edbe..5fbd5cad8ec8 100644 --- a/test/api_integration/apis/saved_objects_management/relationships.ts +++ b/test/api_integration/apis/saved_objects_management/relationships.ts @@ -89,8 +89,7 @@ export default function ({ getService }: FtrProviderContext) { editUrl: '/management/kibana/indexPatterns/patterns/8963ca30-3224-11e8-a572-ffca06da1357', inAppUrl: { - path: - '/app/management/kibana/indexPatterns/patterns/8963ca30-3224-11e8-a572-ffca06da1357', + path: '/app/management/kibana/indexPatterns/patterns/8963ca30-3224-11e8-a572-ffca06da1357', uiCapabilitiesPath: 'management.kibana.indexPatterns', }, namespaceType: 'single', @@ -134,8 +133,7 @@ export default function ({ getService }: FtrProviderContext) { editUrl: '/management/kibana/indexPatterns/patterns/8963ca30-3224-11e8-a572-ffca06da1357', inAppUrl: { - path: - '/app/management/kibana/indexPatterns/patterns/8963ca30-3224-11e8-a572-ffca06da1357', + path: '/app/management/kibana/indexPatterns/patterns/8963ca30-3224-11e8-a572-ffca06da1357', uiCapabilitiesPath: 'management.kibana.indexPatterns', }, namespaceType: 'single', diff --git a/test/common/services/saved_object_info/saved_object_info.ts b/test/common/services/saved_object_info/saved_object_info.ts index 2084ff8e9f4f..61472ea98d87 100644 --- a/test/common/services/saved_object_info/saved_object_info.ts +++ b/test/common/services/saved_object_info/saved_object_info.ts @@ -16,8 +16,10 @@ import { ToolingLog } from '@kbn/dev-utils'; import { FtrService } from '../../ftr_provider_context'; import { print } from './utils'; -const pluck = (key: string) => (obj: any): Either => - fromNullable(new Error(`Missing ${key}`))(obj[key]); +const pluck = + (key: string) => + (obj: any): Either => + fromNullable(new Error(`Missing ${key}`))(obj[key]); const query = { aggs: { @@ -29,29 +31,31 @@ const query = { }, }; -export const types = (node: string) => async (index: string = '.kibana') => - await pipe( - TE.tryCatch( - async () => { - const { body } = await new Client({ node }).search({ - index, - size: 0, - body: query, - }); - return body; - }, - (reason: any) => toError(reason) - ), - TE.map((resp: any) => - flow( - pluck('aggregations'), - chain(pluck('savedobjs')), - chain(pluck('buckets')), - getOrElse((err: Error) => err.message) - )(resp) - ), - TE.fold((x) => T.of(`Error while searching for saved object types: ${x}`), T.of) - )(); +export const types = + (node: string) => + async (index: string = '.kibana') => + await pipe( + TE.tryCatch( + async () => { + const { body } = await new Client({ node }).search({ + index, + size: 0, + body: query, + }); + return body; + }, + (reason: any) => toError(reason) + ), + TE.map((resp: any) => + flow( + pluck('aggregations'), + chain(pluck('savedobjs')), + chain(pluck('buckets')), + getOrElse((err: Error) => err.message) + )(resp) + ), + TE.fold((x) => T.of(`Error while searching for saved object types: ${x}`), T.of) + )(); export class SavedObjectInfoService extends FtrService { private readonly config = this.ctx.getService('config'); diff --git a/test/common/services/saved_object_info/utils.ts b/test/common/services/saved_object_info/utils.ts index 658803560eb6..64b39e5ebeed 100644 --- a/test/common/services/saved_object_info/utils.ts +++ b/test/common/services/saved_object_info/utils.ts @@ -33,10 +33,11 @@ export const areValid = (flags: any) => { return true; }; -export const print = (log: ToolingLog) => (msg: string | null = null) => ({ - xs, - count, -}: ResolvedPayload) => log.write(`\n### Saved Object Types ${msg || 'Count: ' + count}\n${xs}`); +export const print = + (log: ToolingLog) => + (msg: string | null = null) => + ({ xs, count }: ResolvedPayload) => + log.write(`\n### Saved Object Types ${msg || 'Count: ' + count}\n${xs}`); export const expectedFlags = () => ({ string: ['esUrl'], diff --git a/test/examples/field_formats/index.ts b/test/examples/field_formats/index.ts index 82f66aed3b29..bbef5cca2e44 100644 --- a/test/examples/field_formats/index.ts +++ b/test/examples/field_formats/index.ts @@ -22,18 +22,18 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { it('renders field formats example 1', async () => { const formattedValues = await Promise.all( - (await testSubjects.findAll('example1 sample formatted')).map((wrapper) => - wrapper.getVisibleText() - ) + ( + await testSubjects.findAll('example1 sample formatted') + ).map((wrapper) => wrapper.getVisibleText()) ); expect(formattedValues).to.eql(['1000.00B', '97.66KB', '95.37MB']); }); it('renders field formats example 2', async () => { const formattedValues = await Promise.all( - (await testSubjects.findAll('example2 sample formatted')).map((wrapper) => - wrapper.getVisibleText() - ) + ( + await testSubjects.findAll('example2 sample formatted') + ).map((wrapper) => wrapper.getVisibleText()) ); expect(formattedValues).to.eql(['$1,000.00', '$100,000.00', '$100,000,000.00']); }); diff --git a/test/functional/apps/discover/_discover.ts b/test/functional/apps/discover/_discover.ts index 87960d1b6a96..48a3128b6135 100644 --- a/test/functional/apps/discover/_discover.ts +++ b/test/functional/apps/discover/_discover.ts @@ -230,10 +230,8 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await retry.try(async () => { await PageObjects.discover.loadSavedSearch(expected.title); - const { - title, - description, - } = await PageObjects.common.getSharedItemTitleAndDescription(); + 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/management/_field_formatter.ts b/test/functional/apps/management/_field_formatter.ts index e070b262af9e..2377e714418e 100644 --- a/test/functional/apps/management/_field_formatter.ts +++ b/test/functional/apps/management/_field_formatter.ts @@ -491,9 +491,9 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { ( await Promise.all( ( - await (await testSubjects.find('editorSelectedFormatId')).findAllByTagName( - 'option' - ) + await ( + await testSubjects.find('editorSelectedFormatId') + ).findAllByTagName('option') ).map((option) => option.getAttribute('value')) ) ).filter(Boolean) diff --git a/test/functional/apps/management/_handle_version_conflict.js b/test/functional/apps/management/_handle_version_conflict.js index 8baf05385dd0..c2e4a540218e 100644 --- a/test/functional/apps/management/_handle_version_conflict.js +++ b/test/functional/apps/management/_handle_version_conflict.js @@ -72,9 +72,9 @@ export default function ({ getService, getPageObjects }) { await PageObjects.settings.openControlsByName(fieldName); log.debug('controls are open'); await ( - await (await testSubjects.find('formatRow')).findAllByCssSelector( - '[data-test-subj="toggle"]' - ) + await ( + await testSubjects.find('formatRow') + ).findAllByCssSelector('[data-test-subj="toggle"]') )[0].click(); await PageObjects.settings.setFieldFormat('url'); const response = await es.update({ diff --git a/test/functional/apps/visualize/_area_chart.ts b/test/functional/apps/visualize/_area_chart.ts index 4e4fe5e2902b..2a5be3940300 100644 --- a/test/functional/apps/visualize/_area_chart.ts +++ b/test/functional/apps/visualize/_area_chart.ts @@ -103,30 +103,8 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { ]; const yAxisLabels = ['0', '200', '400', '600', '800', '1,000', '1,200', '1,400']; const expectedAreaChartData = [ - 37, - 202, - 740, - 1437, - 1371, - 751, - 188, - 31, - 42, - 202, - 683, - 1361, - 1415, - 707, - 177, - 27, - 32, - 175, - 707, - 1408, - 1355, - 726, - 201, - 29, + 37, 202, 740, 1437, 1371, 751, 188, 31, 42, 202, 683, 1361, 1415, 707, 177, 27, 32, 175, + 707, 1408, 1355, 726, 201, 29, ]; await retry.try(async function tryingForTime() { diff --git a/test/functional/apps/visualize/_point_series_options.ts b/test/functional/apps/visualize/_point_series_options.ts index 0d68ea4984ec..dbe26ba09959 100644 --- a/test/functional/apps/visualize/_point_series_options.ts +++ b/test/functional/apps/visualize/_point_series_options.ts @@ -71,56 +71,14 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { it('should show correct chart', async function () { const expectedChartValues = [ [ - 37, - 202, - 740, - 1437, - 1371, - 751, - 188, - 31, - 42, - 202, - 683, - 1361, - 1415, - 707, - 177, - 27, - 32, - 175, - 707, - 1408, - 1355, - 726, - 201, - 29, + 37, 202, 740, 1437, 1371, 751, 188, 31, 42, 202, 683, 1361, 1415, 707, 177, 27, 32, 175, + 707, 1408, 1355, 726, 201, 29, ], [ - 14018300000, - 13284800000, - 13198800000, - 13093400000, - 13067800000, - 12976600000, - 13561800000, - 14339600000, - 14011000000, - 12775300000, - 13304500000, - 12988900000, - 13143500000, - 13244400000, - 12154800000, - 15907300000, - 13757300000, - 13022200000, - 12807300000, - 13375700000, - 13190800000, - 12627500000, - 12731500000, - 13153300000, + 14018300000, 13284800000, 13198800000, 13093400000, 13067800000, 12976600000, + 13561800000, 14339600000, 14011000000, 12775300000, 13304500000, 12988900000, + 13143500000, 13244400000, 12154800000, 15907300000, 13757300000, 13022200000, + 12807300000, 13375700000, 13190800000, 12627500000, 12731500000, 13153300000, ], ]; diff --git a/test/functional/apps/visualize/_tag_cloud.ts b/test/functional/apps/visualize/_tag_cloud.ts index d18c85f3b58b..9380f40e0d36 100644 --- a/test/functional/apps/visualize/_tag_cloud.ts +++ b/test/functional/apps/visualize/_tag_cloud.ts @@ -148,9 +148,9 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await PageObjects.settings.filterField(termsField); await PageObjects.settings.openControlsByName(termsField); await ( - await (await testSubjects.find('formatRow')).findAllByCssSelector( - '[data-test-subj="toggle"]' - ) + await ( + await testSubjects.find('formatRow') + ).findAllByCssSelector('[data-test-subj="toggle"]') )[0].click(); await PageObjects.settings.setFieldFormat('bytes'); await PageObjects.settings.controlChangeSave(); diff --git a/test/functional/apps/visualize/_vertical_bar_chart.ts b/test/functional/apps/visualize/_vertical_bar_chart.ts index 93022b5d2f0e..7c4f989724ad 100644 --- a/test/functional/apps/visualize/_vertical_bar_chart.ts +++ b/test/functional/apps/visualize/_vertical_bar_chart.ts @@ -116,30 +116,8 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { it('should show correct chart', async function () { const expectedChartValues = [ - 37, - 202, - 740, - 1437, - 1371, - 751, - 188, - 31, - 42, - 202, - 683, - 1361, - 1415, - 707, - 177, - 27, - 32, - 175, - 707, - 1408, - 1355, - 726, - 201, - 29, + 37, 202, 740, 1437, 1371, 751, 188, 31, 42, 202, 683, 1361, 1415, 707, 177, 27, 32, 175, + 707, 1408, 1355, 726, 201, 29, ]; // Most recent failure on Jenkins usually indicates the bar chart is still being drawn? @@ -190,67 +168,9 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await PageObjects.timePicker.setAbsoluteRange(fromTime, toTime); let expectedChartValues = [ - 82, - 218, - 341, - 440, - 480, - 517, - 522, - 446, - 403, - 321, - 258, - 172, - 95, - 55, - 38, - 24, - 3, - 4, - 11, - 14, - 17, - 38, - 49, - 115, - 152, - 216, - 315, - 402, - 446, - 513, - 520, - 474, - 421, - 307, - 230, - 170, - 99, - 48, - 30, - 15, - 10, - 2, - 8, - 7, - 17, - 34, - 37, - 104, - 153, - 241, - 313, - 404, - 492, - 512, - 503, - 473, - 379, - 293, - 277, - 156, - 56, + 82, 218, 341, 440, 480, 517, 522, 446, 403, 321, 258, 172, 95, 55, 38, 24, 3, 4, 11, 14, 17, + 38, 49, 115, 152, 216, 315, 402, 446, 513, 520, 474, 421, 307, 230, 170, 99, 48, 30, 15, 10, + 2, 8, 7, 17, 34, 37, 104, 153, 241, 313, 404, 492, 512, 503, 473, 379, 293, 277, 156, 56, ]; // Most recent failure on Jenkins usually indicates the bar chart is still being drawn? @@ -268,65 +188,9 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await PageObjects.visEditor.clickGo(true); expectedChartValues = [ - 218, - 341, - 440, - 480, - 517, - 522, - 446, - 403, - 321, - 258, - 172, - 95, - 55, - 38, - 24, - 3, - 4, - 11, - 14, - 17, - 38, - 49, - 115, - 152, - 216, - 315, - 402, - 446, - 513, - 520, - 474, - 421, - 307, - 230, - 170, - 99, - 48, - 30, - 15, - 10, - 2, - 8, - 7, - 17, - 34, - 37, - 104, - 153, - 241, - 313, - 404, - 492, - 512, - 503, - 473, - 379, - 293, - 277, - 156, + 218, 341, 440, 480, 517, 522, 446, 403, 321, 258, 172, 95, 55, 38, 24, 3, 4, 11, 14, 17, 38, + 49, 115, 152, 216, 315, 402, 446, 513, 520, 474, 421, 307, 230, 170, 99, 48, 30, 15, 10, 2, + 8, 7, 17, 34, 37, 104, 153, 241, 313, 404, 492, 512, 503, 473, 379, 293, 277, 156, ]; // Most recent failure on Jenkins usually indicates the bar chart is still being drawn? diff --git a/test/functional/apps/visualize/_vertical_bar_chart_nontimeindex.ts b/test/functional/apps/visualize/_vertical_bar_chart_nontimeindex.ts index e9f39a45d789..eadc7c58af5a 100644 --- a/test/functional/apps/visualize/_vertical_bar_chart_nontimeindex.ts +++ b/test/functional/apps/visualize/_vertical_bar_chart_nontimeindex.ts @@ -59,30 +59,8 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { it('should show correct chart', async function () { const expectedChartValues = [ - 37, - 202, - 740, - 1437, - 1371, - 751, - 188, - 31, - 42, - 202, - 683, - 1361, - 1415, - 707, - 177, - 27, - 32, - 175, - 707, - 1408, - 1355, - 726, - 201, - 29, + 37, 202, 740, 1437, 1371, 751, 188, 31, 42, 202, 683, 1361, 1415, 707, 177, 27, 32, 175, + 707, 1408, 1355, 726, 201, 29, ]; // Most recent failure on Jenkins usually indicates the bar chart is still being drawn? diff --git a/test/functional/page_objects/visualize_editor_page.ts b/test/functional/page_objects/visualize_editor_page.ts index 50b275d04eab..ce7320828011 100644 --- a/test/functional/page_objects/visualize_editor_page.ts +++ b/test/functional/page_objects/visualize_editor_page.ts @@ -413,9 +413,9 @@ export class VisualizeEditorPageObject extends FtrService { } public async selectXAxisPosition(position: string) { - const option = await (await this.testSubjects.find('categoryAxisPosition')).findByCssSelector( - `option[value="${position}"]` - ); + const option = await ( + await this.testSubjects.find('categoryAxisPosition') + ).findByCssSelector(`option[value="${position}"]`); await option.click(); } diff --git a/test/functional/services/field_editor.ts b/test/functional/services/field_editor.ts index 03f256051b78..27cb8cf010d9 100644 --- a/test/functional/services/field_editor.ts +++ b/test/functional/services/field_editor.ts @@ -31,9 +31,9 @@ export class FieldEditorService extends FtrService { await this.testSubjects.setEuiSwitch('valueRow > toggle', 'uncheck'); } public async typeScript(script: string) { - const editor = await (await this.testSubjects.find('valueRow')).findByClassName( - 'react-monaco-editor-container' - ); + const editor = await ( + await this.testSubjects.find('valueRow') + ).findByClassName('react-monaco-editor-container'); const textarea = await editor.findByClassName('monaco-mouse-cursor-text'); await textarea.click(); diff --git a/test/functional/services/management/management_menu.ts b/test/functional/services/management/management_menu.ts index 2b93fce4daa5..46bd2368e912 100644 --- a/test/functional/services/management/management_menu.ts +++ b/test/functional/services/management/management_menu.ts @@ -19,13 +19,13 @@ export class ManagementMenuService extends FtrService { const sections = []; for (const el of sectionsElements) { - const sectionId = await (await el.findByClassName('euiSideNavItemButton')).getAttribute( - 'data-test-subj' - ); + const sectionId = await ( + await el.findByClassName('euiSideNavItemButton') + ).getAttribute('data-test-subj'); const sectionLinks = await Promise.all( - (await el.findAllByCssSelector('.euiSideNavItem > a.euiSideNavItemButton')).map((item) => - item.getAttribute('data-test-subj') - ) + ( + await el.findAllByCssSelector('.euiSideNavItem > a.euiSideNavItemButton') + ).map((item) => item.getAttribute('data-test-subj')) ); sections.push({ sectionId, sectionLinks }); diff --git a/test/interpreter_functional/snapshots/baseline/partial_test_1.json b/test/interpreter_functional/snapshots/baseline/partial_test_1.json index 082c7b934c17..9877a0d3138c 100644 --- a/test/interpreter_functional/snapshots/baseline/partial_test_1.json +++ b/test/interpreter_functional/snapshots/baseline/partial_test_1.json @@ -1 +1 @@ -{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"bucket":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"maxFontSize":72,"metric":{"accessor":1,"format":{"id":"number","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"single","palette":{"name":"default","type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file +{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"bucket":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"maxFontSize":72,"metric":{"accessor":1,"format":{"id":"number","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"single","palette":{"name":"custom","params":{"colors":["#882E72","#B178A6","#D6C1DE","#1965B0","#5289C7","#7BAFDE","#4EB265","#90C987","#CAE0AB","#F7EE55","#F6C141","#F1932D","#E8601C","#DC050C"],"continuity":"above","gradient":false,"range":"percent","rangeMax":100,"rangeMin":0,"stops":[]},"type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file diff --git a/test/interpreter_functional/snapshots/baseline/tagcloud_all_data.json b/test/interpreter_functional/snapshots/baseline/tagcloud_all_data.json index 9813a3ca036a..5ddf081c54d9 100644 --- a/test/interpreter_functional/snapshots/baseline/tagcloud_all_data.json +++ b/test/interpreter_functional/snapshots/baseline/tagcloud_all_data.json @@ -1 +1 @@ -{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"bucket":{"accessor":1,"format":{"id":"string","params":{}},"type":"vis_dimension"},"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"single","palette":{"name":"default","type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file +{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"bucket":{"accessor":1,"format":{"id":"string","params":{}},"type":"vis_dimension"},"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"single","palette":{"name":"custom","params":{"colors":["#882E72","#B178A6","#D6C1DE","#1965B0","#5289C7","#7BAFDE","#4EB265","#90C987","#CAE0AB","#F7EE55","#F6C141","#F1932D","#E8601C","#DC050C"],"continuity":"above","gradient":false,"range":"percent","rangeMax":100,"rangeMin":0,"stops":[]},"type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file diff --git a/test/interpreter_functional/snapshots/baseline/tagcloud_empty_data.json b/test/interpreter_functional/snapshots/baseline/tagcloud_empty_data.json index 6dd90a4a6ca0..723ebb6e9f46 100644 --- a/test/interpreter_functional/snapshots/baseline/tagcloud_empty_data.json +++ b/test/interpreter_functional/snapshots/baseline/tagcloud_empty_data.json @@ -1 +1 @@ -{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[],"type":"datatable"},"visParams":{"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"single","palette":{"name":"default","type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file +{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[],"type":"datatable"},"visParams":{"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"single","palette":{"name":"custom","params":{"colors":["#882E72","#B178A6","#D6C1DE","#1965B0","#5289C7","#7BAFDE","#4EB265","#90C987","#CAE0AB","#F7EE55","#F6C141","#F1932D","#E8601C","#DC050C"],"continuity":"above","gradient":false,"range":"percent","rangeMax":100,"rangeMin":0,"stops":[]},"type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file diff --git a/test/interpreter_functional/snapshots/baseline/tagcloud_fontsize.json b/test/interpreter_functional/snapshots/baseline/tagcloud_fontsize.json index bef1b10120fe..1655451d41d0 100644 --- a/test/interpreter_functional/snapshots/baseline/tagcloud_fontsize.json +++ b/test/interpreter_functional/snapshots/baseline/tagcloud_fontsize.json @@ -1 +1 @@ -{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"bucket":{"accessor":1,"format":{"id":"string","params":{}},"type":"vis_dimension"},"maxFontSize":40,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":20,"orientation":"single","palette":{"name":"default","type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file +{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"bucket":{"accessor":1,"format":{"id":"string","params":{}},"type":"vis_dimension"},"maxFontSize":40,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":20,"orientation":"single","palette":{"name":"custom","params":{"colors":["#882E72","#B178A6","#D6C1DE","#1965B0","#5289C7","#7BAFDE","#4EB265","#90C987","#CAE0AB","#F7EE55","#F6C141","#F1932D","#E8601C","#DC050C"],"continuity":"above","gradient":false,"range":"percent","rangeMax":100,"rangeMin":0,"stops":[]},"type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file diff --git a/test/interpreter_functional/snapshots/baseline/tagcloud_metric_data.json b/test/interpreter_functional/snapshots/baseline/tagcloud_metric_data.json index bea6dad294e0..f0bfd56ac99b 100644 --- a/test/interpreter_functional/snapshots/baseline/tagcloud_metric_data.json +++ b/test/interpreter_functional/snapshots/baseline/tagcloud_metric_data.json @@ -1 +1 @@ -{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"single","palette":{"name":"default","type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file +{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"single","palette":{"name":"custom","params":{"colors":["#882E72","#B178A6","#D6C1DE","#1965B0","#5289C7","#7BAFDE","#4EB265","#90C987","#CAE0AB","#F7EE55","#F6C141","#F1932D","#E8601C","#DC050C"],"continuity":"above","gradient":false,"range":"percent","rangeMax":100,"rangeMin":0,"stops":[]},"type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file diff --git a/test/interpreter_functional/snapshots/baseline/tagcloud_options.json b/test/interpreter_functional/snapshots/baseline/tagcloud_options.json index c45b063fdb54..ba034fa2e435 100644 --- a/test/interpreter_functional/snapshots/baseline/tagcloud_options.json +++ b/test/interpreter_functional/snapshots/baseline/tagcloud_options.json @@ -1 +1 @@ -{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"bucket":{"accessor":1,"format":{"id":"string","params":{}},"type":"vis_dimension"},"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"multiple","palette":{"name":"default","type":"palette"},"scale":"log","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file +{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"bucket":{"accessor":1,"format":{"id":"string","params":{}},"type":"vis_dimension"},"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"multiple","palette":{"name":"custom","params":{"colors":["#882E72","#B178A6","#D6C1DE","#1965B0","#5289C7","#7BAFDE","#4EB265","#90C987","#CAE0AB","#F7EE55","#F6C141","#F1932D","#E8601C","#DC050C"],"continuity":"above","gradient":false,"range":"percent","rangeMax":100,"rangeMin":0,"stops":[]},"type":"palette"},"scale":"log","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file diff --git a/test/interpreter_functional/snapshots/session/metric_empty_data.json b/test/interpreter_functional/snapshots/session/metric_empty_data.json new file mode 100644 index 000000000000..c318121535c8 --- /dev/null +++ b/test/interpreter_functional/snapshots/session/metric_empty_data.json @@ -0,0 +1 @@ +{"as":"metric_vis","type":"render","value":{"visConfig":{"dimensions":{"metrics":[{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"}]},"metric":{"colorSchema":"Green to Red","colorsRange":[{"from":0,"to":10000,"type":"range"}],"invertColors":false,"labels":{"show":true},"metricColorMode":"None","percentageMode":false,"style":{"bgColor":false,"bgFill":"#000","fontSize":60,"labelColor":false,"subText":""},"useRanges":false}},"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"},{"id":"col-2-1","meta":{"field":"bytes","index":"logstash-*","params":{"id":"bytes","params":null},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{"field":"bytes"},"schema":"metric","type":"max"},"type":"number"},"name":"Max bytes"}],"rows":[],"type":"datatable"},"visType":"metric"}} \ No newline at end of file diff --git a/test/interpreter_functional/snapshots/session/metric_invalid_data.json b/test/interpreter_functional/snapshots/session/metric_invalid_data.json index c7b4a0325dc9..f23b9b091577 100644 --- a/test/interpreter_functional/snapshots/session/metric_invalid_data.json +++ b/test/interpreter_functional/snapshots/session/metric_invalid_data.json @@ -1 +1 @@ -{"as":"metric_vis","type":"render","value":{"visConfig":{"dimensions":{"metrics":[{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"}]},"metric":{"colorSchema":"Green to Red","colorsRange":[{"from":0,"to":10000,"type":"range"}],"invertColors":false,"labels":{"show":true},"metricColorMode":"None","percentageMode":false,"style":{"bgColor":false,"bgFill":"#000","fontSize":60,"labelColor":false,"subText":""},"useRanges":false}},"visData":{"columns":[],"meta":{},"rows":[],"type":"datatable"},"visType":"metric"}} \ No newline at end of file +"[metricVis] > [visdimension] > Column name or index provided is invalid" \ No newline at end of file diff --git a/test/interpreter_functional/snapshots/session/metric_single_metric_data.json b/test/interpreter_functional/snapshots/session/metric_single_metric_data.json new file mode 100644 index 000000000000..f4a8cd1f14e1 --- /dev/null +++ b/test/interpreter_functional/snapshots/session/metric_single_metric_data.json @@ -0,0 +1 @@ +{"as":"metric_vis","type":"render","value":{"visConfig":{"dimensions":{"metrics":[{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"}]},"metric":{"colorSchema":"Green to Red","colorsRange":[{"from":0,"to":10000,"type":"range"}],"invertColors":false,"labels":{"show":true},"metricColorMode":"None","percentageMode":false,"style":{"bgColor":false,"bgFill":"#000","fontSize":60,"labelColor":false,"subText":""},"useRanges":false}},"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"},{"id":"col-2-1","meta":{"field":"bytes","index":"logstash-*","params":{"id":"bytes","params":null},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{"field":"bytes"},"schema":"metric","type":"max"},"type":"number"},"name":"Max bytes"}],"rows":[{"col-0-2":"200","col-1-1":12891,"col-2-1":19986},{"col-0-2":"404","col-1-1":696,"col-2-1":19881},{"col-0-2":"503","col-1-1":417,"col-2-1":0}],"type":"datatable"},"visType":"metric"}} \ No newline at end of file diff --git a/test/interpreter_functional/snapshots/session/partial_test_1.json b/test/interpreter_functional/snapshots/session/partial_test_1.json new file mode 100644 index 000000000000..9877a0d3138c --- /dev/null +++ b/test/interpreter_functional/snapshots/session/partial_test_1.json @@ -0,0 +1 @@ +{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"bucket":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"maxFontSize":72,"metric":{"accessor":1,"format":{"id":"number","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"single","palette":{"name":"custom","params":{"colors":["#882E72","#B178A6","#D6C1DE","#1965B0","#5289C7","#7BAFDE","#4EB265","#90C987","#CAE0AB","#F7EE55","#F6C141","#F1932D","#E8601C","#DC050C"],"continuity":"above","gradient":false,"range":"percent","rangeMax":100,"rangeMin":0,"stops":[]},"type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file diff --git a/test/interpreter_functional/snapshots/session/tagcloud_all_data.json b/test/interpreter_functional/snapshots/session/tagcloud_all_data.json index 9813a3ca036a..5ddf081c54d9 100644 --- a/test/interpreter_functional/snapshots/session/tagcloud_all_data.json +++ b/test/interpreter_functional/snapshots/session/tagcloud_all_data.json @@ -1 +1 @@ -{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"bucket":{"accessor":1,"format":{"id":"string","params":{}},"type":"vis_dimension"},"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"single","palette":{"name":"default","type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file +{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"bucket":{"accessor":1,"format":{"id":"string","params":{}},"type":"vis_dimension"},"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"single","palette":{"name":"custom","params":{"colors":["#882E72","#B178A6","#D6C1DE","#1965B0","#5289C7","#7BAFDE","#4EB265","#90C987","#CAE0AB","#F7EE55","#F6C141","#F1932D","#E8601C","#DC050C"],"continuity":"above","gradient":false,"range":"percent","rangeMax":100,"rangeMin":0,"stops":[]},"type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file diff --git a/test/interpreter_functional/snapshots/session/tagcloud_empty_data.json b/test/interpreter_functional/snapshots/session/tagcloud_empty_data.json index 6dd90a4a6ca0..723ebb6e9f46 100644 --- a/test/interpreter_functional/snapshots/session/tagcloud_empty_data.json +++ b/test/interpreter_functional/snapshots/session/tagcloud_empty_data.json @@ -1 +1 @@ -{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[],"type":"datatable"},"visParams":{"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"single","palette":{"name":"default","type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file +{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[],"type":"datatable"},"visParams":{"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"single","palette":{"name":"custom","params":{"colors":["#882E72","#B178A6","#D6C1DE","#1965B0","#5289C7","#7BAFDE","#4EB265","#90C987","#CAE0AB","#F7EE55","#F6C141","#F1932D","#E8601C","#DC050C"],"continuity":"above","gradient":false,"range":"percent","rangeMax":100,"rangeMin":0,"stops":[]},"type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file diff --git a/test/interpreter_functional/snapshots/session/tagcloud_fontsize.json b/test/interpreter_functional/snapshots/session/tagcloud_fontsize.json index bef1b10120fe..1655451d41d0 100644 --- a/test/interpreter_functional/snapshots/session/tagcloud_fontsize.json +++ b/test/interpreter_functional/snapshots/session/tagcloud_fontsize.json @@ -1 +1 @@ -{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"bucket":{"accessor":1,"format":{"id":"string","params":{}},"type":"vis_dimension"},"maxFontSize":40,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":20,"orientation":"single","palette":{"name":"default","type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file +{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"bucket":{"accessor":1,"format":{"id":"string","params":{}},"type":"vis_dimension"},"maxFontSize":40,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":20,"orientation":"single","palette":{"name":"custom","params":{"colors":["#882E72","#B178A6","#D6C1DE","#1965B0","#5289C7","#7BAFDE","#4EB265","#90C987","#CAE0AB","#F7EE55","#F6C141","#F1932D","#E8601C","#DC050C"],"continuity":"above","gradient":false,"range":"percent","rangeMax":100,"rangeMin":0,"stops":[]},"type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file diff --git a/test/interpreter_functional/snapshots/session/tagcloud_metric_data.json b/test/interpreter_functional/snapshots/session/tagcloud_metric_data.json index bea6dad294e0..f0bfd56ac99b 100644 --- a/test/interpreter_functional/snapshots/session/tagcloud_metric_data.json +++ b/test/interpreter_functional/snapshots/session/tagcloud_metric_data.json @@ -1 +1 @@ -{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"single","palette":{"name":"default","type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file +{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"single","palette":{"name":"custom","params":{"colors":["#882E72","#B178A6","#D6C1DE","#1965B0","#5289C7","#7BAFDE","#4EB265","#90C987","#CAE0AB","#F7EE55","#F6C141","#F1932D","#E8601C","#DC050C"],"continuity":"above","gradient":false,"range":"percent","rangeMax":100,"rangeMin":0,"stops":[]},"type":"palette"},"scale":"linear","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file diff --git a/test/interpreter_functional/snapshots/session/tagcloud_options.json b/test/interpreter_functional/snapshots/session/tagcloud_options.json index c45b063fdb54..ba034fa2e435 100644 --- a/test/interpreter_functional/snapshots/session/tagcloud_options.json +++ b/test/interpreter_functional/snapshots/session/tagcloud_options.json @@ -1 +1 @@ -{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"bucket":{"accessor":1,"format":{"id":"string","params":{}},"type":"vis_dimension"},"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"multiple","palette":{"name":"default","type":"palette"},"scale":"log","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file +{"as":"tagcloud","type":"render","value":{"syncColors":false,"visData":{"columns":[{"id":"col-0-2","meta":{"field":"response.raw","index":"logstash-*","params":{"id":"terms","params":{"id":"string","missingBucketLabel":"Missing","otherBucketLabel":"Other"}},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"2","indexPatternId":"logstash-*","params":{"field":"response.raw","missingBucket":false,"missingBucketLabel":"Missing","order":"desc","orderBy":"1","otherBucket":false,"otherBucketLabel":"Other","size":4},"schema":"segment","type":"terms"},"type":"string"},"name":"response.raw: Descending"},{"id":"col-1-1","meta":{"field":null,"index":"logstash-*","params":{"id":"number"},"source":"esaggs","sourceParams":{"appliedTimeRange":null,"enabled":true,"id":"1","indexPatternId":"logstash-*","params":{},"schema":"metric","type":"count"},"type":"number"},"name":"Count"}],"rows":[{"col-0-2":"200","col-1-1":12891},{"col-0-2":"404","col-1-1":696},{"col-0-2":"503","col-1-1":417}],"type":"datatable"},"visParams":{"bucket":{"accessor":1,"format":{"id":"string","params":{}},"type":"vis_dimension"},"maxFontSize":72,"metric":{"accessor":0,"format":{"id":"string","params":{}},"type":"vis_dimension"},"minFontSize":18,"orientation":"multiple","palette":{"name":"custom","params":{"colors":["#882E72","#B178A6","#D6C1DE","#1965B0","#5289C7","#7BAFDE","#4EB265","#90C987","#CAE0AB","#F7EE55","#F6C141","#F1932D","#E8601C","#DC050C"],"continuity":"above","gradient":false,"range":"percent","rangeMax":100,"rangeMin":0,"stops":[]},"type":"palette"},"scale":"log","showLabel":true},"visType":"tagcloud"}} \ No newline at end of file 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 69011ac74cca..0739c858307c 100644 --- a/test/plugin_functional/plugins/core_plugin_appleave/public/plugin.tsx +++ b/test/plugin_functional/plugins/core_plugin_appleave/public/plugin.tsx @@ -9,7 +9,8 @@ import { Plugin, CoreSetup } from 'kibana/public'; export class CoreAppLeavePlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, deps: {}) { core.application.register({ id: 'appleave1', diff --git a/test/plugin_functional/plugins/core_plugin_b/public/plugin.tsx b/test/plugin_functional/plugins/core_plugin_b/public/plugin.tsx index 5bab0275439d..2fbf57b2a710 100644 --- a/test/plugin_functional/plugins/core_plugin_b/public/plugin.tsx +++ b/test/plugin_functional/plugins/core_plugin_b/public/plugin.tsx @@ -20,7 +20,8 @@ export interface CorePluginBDeps { } export class CorePluginBPlugin - implements Plugin { + implements Plugin +{ constructor(pluginContext: PluginInitializerContext) { window.env = pluginContext.env; } diff --git a/test/plugin_functional/plugins/core_plugin_chromeless/public/plugin.tsx b/test/plugin_functional/plugins/core_plugin_chromeless/public/plugin.tsx index 175bac128b7d..47b33479e45f 100644 --- a/test/plugin_functional/plugins/core_plugin_chromeless/public/plugin.tsx +++ b/test/plugin_functional/plugins/core_plugin_chromeless/public/plugin.tsx @@ -9,7 +9,8 @@ import { Plugin, CoreSetup } from 'kibana/public'; export class CorePluginChromelessPlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, deps: {}) { core.application.register({ id: 'chromeless', diff --git a/test/plugin_functional/plugins/core_plugin_deep_links/public/plugin.tsx b/test/plugin_functional/plugins/core_plugin_deep_links/public/plugin.tsx index 48f11132ffb4..d53810d32c32 100644 --- a/test/plugin_functional/plugins/core_plugin_deep_links/public/plugin.tsx +++ b/test/plugin_functional/plugins/core_plugin_deep_links/public/plugin.tsx @@ -10,7 +10,8 @@ import { Plugin, CoreSetup } from 'kibana/public'; import { DEFAULT_APP_CATEGORIES, AppNavLinkStatus } from '../../../../../src/core/public'; export class CorePluginDeepLinksPlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, deps: {}) { core.application.register({ id: 'deeplinks', diff --git a/test/plugin_functional/plugins/core_plugin_deprecations/public/plugin.tsx b/test/plugin_functional/plugins/core_plugin_deprecations/public/plugin.tsx index bf807145e14b..1ae9b15be97d 100644 --- a/test/plugin_functional/plugins/core_plugin_deprecations/public/plugin.tsx +++ b/test/plugin_functional/plugins/core_plugin_deprecations/public/plugin.tsx @@ -15,7 +15,8 @@ declare global { } export class CorePluginDeprecationsPlugin - implements Plugin { + implements Plugin +{ constructor(pluginContext: PluginInitializerContext) { window.env = pluginContext.env; } diff --git a/test/plugin_functional/plugins/core_plugin_helpmenu/public/plugin.tsx b/test/plugin_functional/plugins/core_plugin_helpmenu/public/plugin.tsx index ba710c4d869b..15357639f155 100644 --- a/test/plugin_functional/plugins/core_plugin_helpmenu/public/plugin.tsx +++ b/test/plugin_functional/plugins/core_plugin_helpmenu/public/plugin.tsx @@ -9,7 +9,8 @@ import { Plugin, CoreSetup } from 'kibana/public'; export class CoreHelpMenuPlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, deps: {}) { core.application.register({ id: 'core_help_menu', diff --git a/test/plugin_functional/plugins/data_search/server/plugin.ts b/test/plugin_functional/plugins/data_search/server/plugin.ts index f6c83a53a805..f2d109642530 100644 --- a/test/plugin_functional/plugins/data_search/server/plugin.ts +++ b/test/plugin_functional/plugins/data_search/server/plugin.ts @@ -15,7 +15,8 @@ export interface DataSearchTestStartDeps { } export class DataSearchTestPlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup) { const router = core.http.createRouter(); diff --git a/test/plugin_functional/plugins/index_patterns/server/index.ts b/test/plugin_functional/plugins/index_patterns/server/index.ts index f776ad9a7622..10111fafe1b0 100644 --- a/test/plugin_functional/plugins/index_patterns/server/index.ts +++ b/test/plugin_functional/plugins/index_patterns/server/index.ts @@ -13,7 +13,5 @@ import { IndexPatternsTestPluginStart, } from './plugin'; -export const plugin: PluginInitializer< - IndexPatternsTestPluginSetup, - IndexPatternsTestPluginStart -> = () => new IndexPatternsTestPlugin(); +export const plugin: PluginInitializer = + () => new IndexPatternsTestPlugin(); diff --git a/test/plugin_functional/plugins/index_patterns/server/plugin.ts b/test/plugin_functional/plugins/index_patterns/server/plugin.ts index 7314419576a3..1fe3326a6d1d 100644 --- a/test/plugin_functional/plugins/index_patterns/server/plugin.ts +++ b/test/plugin_functional/plugins/index_patterns/server/plugin.ts @@ -21,7 +21,8 @@ export class IndexPatternsTestPlugin IndexPatternsTestPluginStart, {}, IndexPatternsTestStartDeps - > { + > +{ public setup(core: CoreSetup) { const router = core.http.createRouter(); diff --git a/test/plugin_functional/plugins/kbn_sample_panel_action/public/plugin.ts b/test/plugin_functional/plugins/kbn_sample_panel_action/public/plugin.ts index 4d3579ca9ba1..b1ff7ba4ee7f 100644 --- a/test/plugin_functional/plugins/kbn_sample_panel_action/public/plugin.ts +++ b/test/plugin_functional/plugins/kbn_sample_panel_action/public/plugin.ts @@ -13,7 +13,8 @@ import { createSamplePanelAction } from './sample_panel_action'; import { createSamplePanelLink } from './sample_panel_link'; export class SampelPanelActionTestPlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, { uiActions }: { uiActions: UiActionsSetup }) { const samplePanelAction = createSamplePanelAction(core.getStartServices); const samplePanelLink = createSamplePanelLink(); diff --git a/test/plugin_functional/plugins/kbn_tp_custom_visualizations/public/plugin.ts b/test/plugin_functional/plugins/kbn_tp_custom_visualizations/public/plugin.ts index df676b28e5db..b1f1cec78bd6 100644 --- a/test/plugin_functional/plugins/kbn_tp_custom_visualizations/public/plugin.ts +++ b/test/plugin_functional/plugins/kbn_tp_custom_visualizations/public/plugin.ts @@ -21,7 +21,8 @@ export interface SetupDependencies { } export class CustomVisualizationsPublicPlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, { expressions, visualizations }: SetupDependencies) { /** * Register an expression function with type "render" for your visualization diff --git a/test/plugin_functional/plugins/kbn_tp_custom_visualizations/public/self_changing_vis_fn.ts b/test/plugin_functional/plugins/kbn_tp_custom_visualizations/public/self_changing_vis_fn.ts index 21f937c07ac0..6176173e2471 100644 --- a/test/plugin_functional/plugins/kbn_tp_custom_visualizations/public/self_changing_vis_fn.ts +++ b/test/plugin_functional/plugins/kbn_tp_custom_visualizations/public/self_changing_vis_fn.ts @@ -32,8 +32,7 @@ export const selfChangingVisFn: SelfChangingVisExpressionFunctionDefinition = { name: 'self_changing_vis', type: 'render', inputTypes: ['kibana_context'], - help: - 'The expression function definition should be registered for a custom visualization to be rendered', + help: 'The expression function definition should be registered for a custom visualization to be rendered', args: { counter: { types: ['number'], diff --git a/test/plugin_functional/plugins/management_test_plugin/public/plugin.tsx b/test/plugin_functional/plugins/management_test_plugin/public/plugin.tsx index 67d54ce40b76..a2cbe6aa5e48 100644 --- a/test/plugin_functional/plugins/management_test_plugin/public/plugin.tsx +++ b/test/plugin_functional/plugins/management_test_plugin/public/plugin.tsx @@ -13,7 +13,8 @@ import { CoreSetup, Plugin } from 'kibana/public'; import { ManagementSetup } from '../../../../../src/plugins/management/public'; export class ManagementTestPlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, { management }: { management: ManagementSetup }) { const testSection = management.sections.section.data; diff --git a/test/plugin_functional/test_suites/core/deprecations.ts b/test/plugin_functional/test_suites/core/deprecations.ts index 25ac5f24a97c..dbaf10008e35 100644 --- a/test/plugin_functional/test_suites/core/deprecations.ts +++ b/test/plugin_functional/test_suites/core/deprecations.ts @@ -254,11 +254,9 @@ export default function ({ getService, getPageObjects }: PluginFunctionalProvide const { deprecations } = await supertest .get('/api/deprecations/') .set('kbn-xsrf', 'true') - .then( - ({ body }): Promise => { - return body; - } - ); + .then(({ body }): Promise => { + return body; + }); const deprecation = deprecations.find( ({ message }) => message === 'SavedObject test-deprecations-plugin is still being used.' diff --git a/test/plugin_functional/test_suites/saved_objects_management/export_transform.ts b/test/plugin_functional/test_suites/saved_objects_management/export_transform.ts index 8437e050091f..90cb27e5babe 100644 --- a/test/plugin_functional/test_suites/saved_objects_management/export_transform.ts +++ b/test/plugin_functional/test_suites/saved_objects_management/export_transform.ts @@ -242,9 +242,9 @@ export default function ({ getService }: PluginFunctionalProviderContext) { .expect(200) .then((resp) => { const objects = parseNdJson(resp.text); - const exportDetails = (objects[ + const exportDetails = objects[ objects.length - 1 - ] as unknown) as SavedObjectsExportResultDetails; + ] as unknown as SavedObjectsExportResultDetails; expect(exportDetails.excludedObjectsCount).to.eql(2); expect(exportDetails.excludedObjects).to.eql([ @@ -287,9 +287,9 @@ export default function ({ getService }: PluginFunctionalProviderContext) { expect([objects[0]].map((obj) => `${obj.type}:${obj.id}`)).to.eql([ 'test-is-exportable:5', ]); - const exportDetails = (objects[ + const exportDetails = objects[ objects.length - 1 - ] as unknown) as SavedObjectsExportResultDetails; + ] as unknown as SavedObjectsExportResultDetails; expect(exportDetails.excludedObjects).to.eql([ { type: 'test-is-exportable', diff --git a/test/plugin_functional/test_suites/telemetry/telemetry.ts b/test/plugin_functional/test_suites/telemetry/telemetry.ts index 8ebc78c9b2f8..97db6593874e 100644 --- a/test/plugin_functional/test_suites/telemetry/telemetry.ts +++ b/test/plugin_functional/test_suites/telemetry/telemetry.ts @@ -17,7 +17,7 @@ export default function ({ getService, getPageObjects }: PluginFunctionalProvide describe('Telemetry service', () => { const checkCanSendTelemetry = (): Promise => { return browser.executeAsync((cb) => { - ((window as unknown) as Record Promise>) + (window as unknown as Record Promise>) ._checkCanSendTelemetry() .then(cb); }); @@ -26,7 +26,7 @@ export default function ({ getService, getPageObjects }: PluginFunctionalProvide after(async () => { await browser.removeLocalStorageItem(KBN_SCREENSHOT_MODE_ENABLED_KEY); await browser.executeAsync((cb) => { - ((window as unknown) as Record Promise>) + (window as unknown as Record Promise>) ._resetTelemetry() .then(() => cb()); }); diff --git a/x-pack/examples/alerting_example/public/components/create_alert.tsx b/x-pack/examples/alerting_example/public/components/create_alert.tsx index 889b0c7f2d7d..de5ffbee6452 100644 --- a/x-pack/examples/alerting_example/public/components/create_alert.tsx +++ b/x-pack/examples/alerting_example/public/components/create_alert.tsx @@ -17,9 +17,10 @@ export const CreateAlert = ({ }: Pick) => { const [alertFlyoutVisible, setAlertFlyoutVisibility] = useState(false); - const onCloseAlertFlyout = useCallback(() => setAlertFlyoutVisibility(false), [ - setAlertFlyoutVisibility, - ]); + const onCloseAlertFlyout = useCallback( + () => setAlertFlyoutVisibility(false), + [setAlertFlyoutVisibility] + ); const AddAlertFlyout = useMemo( () => diff --git a/x-pack/examples/embedded_lens_example/public/app.tsx b/x-pack/examples/embedded_lens_example/public/app.tsx index 55f2b4ccd71e..3921b3a51dc4 100644 --- a/x-pack/examples/embedded_lens_example/public/app.tsx +++ b/x-pack/examples/embedded_lens_example/public/app.tsx @@ -260,10 +260,10 @@ export const App = (props: { {isSaveModalVisible && ( {}} onClose={() => setIsSaveModalVisible(false)} diff --git a/x-pack/examples/embedded_lens_example/public/mount.tsx b/x-pack/examples/embedded_lens_example/public/mount.tsx index ff1e6ef8818f..58ec36322327 100644 --- a/x-pack/examples/embedded_lens_example/public/mount.tsx +++ b/x-pack/examples/embedded_lens_example/public/mount.tsx @@ -10,26 +10,26 @@ import { render, unmountComponentAtNode } from 'react-dom'; import { CoreSetup, AppMountParameters } from 'kibana/public'; import { StartDependencies } from './plugin'; -export const mount = (coreSetup: CoreSetup) => async ({ - element, -}: AppMountParameters) => { - const [core, plugins] = await coreSetup.getStartServices(); - const { App } = await import('./app'); +export const mount = + (coreSetup: CoreSetup) => + async ({ element }: AppMountParameters) => { + const [core, plugins] = await coreSetup.getStartServices(); + const { App } = await import('./app'); - const deps = { - core, - plugins, - }; + const deps = { + core, + plugins, + }; - const defaultIndexPattern = await plugins.data.indexPatterns.getDefault(); + const defaultIndexPattern = await plugins.data.indexPatterns.getDefault(); - const i18nCore = core.i18n; + const i18nCore = core.i18n; - const reactElement = ( - - - - ); - render(reactElement, element); - return () => unmountComponentAtNode(element); -}; + const reactElement = ( + + + + ); + render(reactElement, element); + return () => unmountComponentAtNode(element); + }; diff --git a/x-pack/examples/embedded_lens_example/public/plugin.ts b/x-pack/examples/embedded_lens_example/public/plugin.ts index 4f454ffe5c3c..991c506ed579 100644 --- a/x-pack/examples/embedded_lens_example/public/plugin.ts +++ b/x-pack/examples/embedded_lens_example/public/plugin.ts @@ -21,7 +21,8 @@ export interface StartDependencies { } export class EmbeddedLensExamplePlugin - implements Plugin { + implements Plugin +{ public setup(core: CoreSetup, { developerExamples }: SetupDependencies) { core.application.register({ id: 'embedded_lens_example', @@ -38,8 +39,7 @@ export class EmbeddedLensExamplePlugin links: [ { label: 'README', - href: - 'https://github.com/elastic/kibana/tree/master/x-pack/examples/embedded_lens_example', + href: 'https://github.com/elastic/kibana/tree/master/x-pack/examples/embedded_lens_example', iconType: 'logoGithub', size: 's', target: '_blank', diff --git a/x-pack/examples/ui_actions_enhanced_examples/public/drilldowns/dashboard_hello_world_only_range_select_drilldown/index.tsx b/x-pack/examples/ui_actions_enhanced_examples/public/drilldowns/dashboard_hello_world_only_range_select_drilldown/index.tsx index 81a6f6aa5e66..c7c50fa6dc43 100644 --- a/x-pack/examples/ui_actions_enhanced_examples/public/drilldowns/dashboard_hello_world_only_range_select_drilldown/index.tsx +++ b/x-pack/examples/ui_actions_enhanced_examples/public/drilldowns/dashboard_hello_world_only_range_select_drilldown/index.tsx @@ -24,7 +24,8 @@ const SAMPLE_DASHBOARD_HELLO_WORLD_DRILLDOWN_ONLY_RANGE_SELECT = 'SAMPLE_DASHBOARD_HELLO_WORLD_DRILLDOWN_ONLY_RANGE_SELECT'; export class DashboardHelloWorldOnlyRangeSelectDrilldown - implements Drilldown { + implements Drilldown +{ public readonly id = SAMPLE_DASHBOARD_HELLO_WORLD_DRILLDOWN_ONLY_RANGE_SELECT; public readonly order = 7; diff --git a/x-pack/examples/ui_actions_enhanced_examples/public/drilldowns/dashboard_to_discover_drilldown/drilldown.tsx b/x-pack/examples/ui_actions_enhanced_examples/public/drilldowns/dashboard_to_discover_drilldown/drilldown.tsx index bdaf7e43eaab..d1482c55429f 100644 --- a/x-pack/examples/ui_actions_enhanced_examples/public/drilldowns/dashboard_to_discover_drilldown/drilldown.tsx +++ b/x-pack/examples/ui_actions_enhanced_examples/public/drilldowns/dashboard_to_discover_drilldown/drilldown.tsx @@ -31,7 +31,8 @@ export interface Params { } export class DashboardToDiscoverDrilldown - implements Drilldown { + implements Drilldown +{ constructor(protected readonly params: Params) {} public readonly id = SAMPLE_DASHBOARD_TO_DISCOVER_DRILLDOWN; diff --git a/x-pack/examples/ui_actions_enhanced_examples/public/mount.tsx b/x-pack/examples/ui_actions_enhanced_examples/public/mount.tsx index 711649ed68f5..3fd42488b283 100644 --- a/x-pack/examples/ui_actions_enhanced_examples/public/mount.tsx +++ b/x-pack/examples/ui_actions_enhanced_examples/public/mount.tsx @@ -11,29 +11,29 @@ import { CoreSetup, AppMountParameters } from 'kibana/public'; import { StartDependencies, UiActionsEnhancedExamplesStart } from './plugin'; import { UiActionsExampleAppContextValue, context } from './context'; -export const mount = ( - coreSetup: CoreSetup -) => async ({ appBasePath, element }: AppMountParameters) => { - const [ - core, - plugins, - { managerWithoutEmbeddable, managerWithoutEmbeddableSingleButton, managerWithEmbeddable }, - ] = await coreSetup.getStartServices(); - const { App } = await import('./containers/app'); +export const mount = + (coreSetup: CoreSetup) => + async ({ appBasePath, element }: AppMountParameters) => { + const [ + core, + plugins, + { managerWithoutEmbeddable, managerWithoutEmbeddableSingleButton, managerWithEmbeddable }, + ] = await coreSetup.getStartServices(); + const { App } = await import('./containers/app'); - const deps: UiActionsExampleAppContextValue = { - appBasePath, - core, - plugins, - managerWithoutEmbeddable, - managerWithoutEmbeddableSingleButton, - managerWithEmbeddable, + const deps: UiActionsExampleAppContextValue = { + appBasePath, + core, + plugins, + managerWithoutEmbeddable, + managerWithoutEmbeddableSingleButton, + managerWithEmbeddable, + }; + const reactElement = ( + + + + ); + render(reactElement, element); + return () => unmountComponentAtNode(element); }; - const reactElement = ( - - - - ); - render(reactElement, element); - return () => unmountComponentAtNode(element); -}; diff --git a/x-pack/examples/ui_actions_enhanced_examples/public/plugin.ts b/x-pack/examples/ui_actions_enhanced_examples/public/plugin.ts index 849645074519..d41b18addcca 100644 --- a/x-pack/examples/ui_actions_enhanced_examples/public/plugin.ts +++ b/x-pack/examples/ui_actions_enhanced_examples/public/plugin.ts @@ -58,7 +58,8 @@ export interface UiActionsEnhancedExamplesStart { } export class UiActionsEnhancedExamplesPlugin - implements Plugin { + implements Plugin +{ public setup( core: CoreSetup, { uiActionsEnhanced: uiActions, developerExamples }: SetupDependencies @@ -140,8 +141,7 @@ export class UiActionsEnhancedExamplesPlugin links: [ { label: 'README', - href: - 'https://github.com/elastic/kibana/tree/master/x-pack/examples/ui_actions_enhanced_examples#ui-actions-enhanced-examples', + href: 'https://github.com/elastic/kibana/tree/master/x-pack/examples/ui_actions_enhanced_examples#ui-actions-enhanced-examples', iconType: 'logoGithub', size: 's', target: '_blank', diff --git a/x-pack/plugins/actions/common/alert_history_schema.ts b/x-pack/plugins/actions/common/alert_history_schema.ts index e1c923ab23f4..71781c57fe39 100644 --- a/x-pack/plugins/actions/common/alert_history_schema.ts +++ b/x-pack/plugins/actions/common/alert_history_schema.ts @@ -12,7 +12,14 @@ export const AlertHistoryDefaultIndexName = `${ALERT_HISTORY_PREFIX}default`; export const AlertHistoryEsIndexConnectorId = 'preconfigured-alert-history-es-index'; export const buildAlertHistoryDocument = (variables: Record) => { - const { date, alert: alertVariables, context, params, tags, rule: ruleVariables } = variables as { + const { + date, + alert: alertVariables, + context, + params, + tags, + rule: ruleVariables, + } = variables as { date: string; alert: Record; context: Record; @@ -25,13 +32,22 @@ export const buildAlertHistoryDocument = (variables: Record) => return null; } - const { actionGroup, actionGroupName, id: alertId } = alertVariables as { + const { + actionGroup, + actionGroupName, + id: alertId, + } = alertVariables as { actionGroup: string; actionGroupName: string; id: string; }; - const { id: ruleId, name, spaceId, type } = ruleVariables as { + const { + id: ruleId, + name, + spaceId, + type, + } = ruleVariables as { id: string; name: string; spaceId: string; diff --git a/x-pack/plugins/actions/server/actions_client.test.ts b/x-pack/plugins/actions/server/actions_client.test.ts index 4a35b5c7dfbe..a341cdf58b9e 100644 --- a/x-pack/plugins/actions/server/actions_client.test.ts +++ b/x-pack/plugins/actions/server/actions_client.test.ts @@ -80,7 +80,7 @@ beforeEach(() => { executionEnqueuer, ephemeralExecutionEnqueuer, request, - authorization: (authorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as ActionsAuthorization, auditLogger, }); }); @@ -457,7 +457,7 @@ describe('create()', () => { executionEnqueuer, ephemeralExecutionEnqueuer, request, - authorization: (authorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as ActionsAuthorization, }); const savedObjectCreateResult = { @@ -558,7 +558,7 @@ describe('get()', () => { executionEnqueuer, ephemeralExecutionEnqueuer, request, - authorization: (authorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as ActionsAuthorization, preconfiguredActions: [ { id: 'testPreconfigured', @@ -614,7 +614,7 @@ describe('get()', () => { executionEnqueuer, ephemeralExecutionEnqueuer, request, - authorization: (authorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as ActionsAuthorization, preconfiguredActions: [ { id: 'testPreconfigured', @@ -731,7 +731,7 @@ describe('get()', () => { executionEnqueuer, ephemeralExecutionEnqueuer, request, - authorization: (authorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as ActionsAuthorization, preconfiguredActions: [ { id: 'testPreconfigured', @@ -801,7 +801,7 @@ describe('getAll()', () => { executionEnqueuer, ephemeralExecutionEnqueuer, request, - authorization: (authorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as ActionsAuthorization, preconfiguredActions: [ { id: 'testPreconfigured', @@ -939,7 +939,7 @@ describe('getAll()', () => { executionEnqueuer, ephemeralExecutionEnqueuer, request, - authorization: (authorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as ActionsAuthorization, preconfiguredActions: [ { id: 'testPreconfigured', @@ -1015,7 +1015,7 @@ describe('getBulk()', () => { executionEnqueuer, ephemeralExecutionEnqueuer, request, - authorization: (authorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as ActionsAuthorization, preconfiguredActions: [ { id: 'testPreconfigured', @@ -1147,7 +1147,7 @@ describe('getBulk()', () => { executionEnqueuer, ephemeralExecutionEnqueuer, request, - authorization: (authorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as ActionsAuthorization, preconfiguredActions: [ { id: 'testPreconfigured', @@ -1835,7 +1835,7 @@ describe('isPreconfigured()', () => { executionEnqueuer, ephemeralExecutionEnqueuer, request, - authorization: (authorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as ActionsAuthorization, preconfiguredActions: [ { id: 'testPreconfigured', @@ -1865,7 +1865,7 @@ describe('isPreconfigured()', () => { executionEnqueuer, ephemeralExecutionEnqueuer, request, - authorization: (authorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as ActionsAuthorization, preconfiguredActions: [ { id: 'testPreconfigured', diff --git a/x-pack/plugins/actions/server/actions_client.ts b/x-pack/plugins/actions/server/actions_client.ts index f1bedbe44ece..d6f6037ecd8b 100644 --- a/x-pack/plugins/actions/server/actions_client.ts +++ b/x-pack/plugins/actions/server/actions_client.ts @@ -208,11 +208,8 @@ export class ActionsClient { ); throw error; } - const { - attributes, - references, - version, - } = await this.unsecuredSavedObjectsClient.get('action', id); + const { attributes, references, version } = + await this.unsecuredSavedObjectsClient.get('action', id); const { actionTypeId } = attributes; const { name, config, secrets } = action; const actionType = this.actionTypeRegistry.get(actionTypeId); diff --git a/x-pack/plugins/actions/server/authorization/actions_authorization.test.ts b/x-pack/plugins/actions/server/authorization/actions_authorization.test.ts index 00807c07d6ff..ddf0e126116a 100644 --- a/x-pack/plugins/actions/server/authorization/actions_authorization.test.ts +++ b/x-pack/plugins/actions/server/authorization/actions_authorization.test.ts @@ -28,9 +28,11 @@ function mockSecurity() { const authorization = security.authz; const authentication = security.authc; // typescript is having trouble inferring jest's automocking - (authorization.actions.savedObject.get as jest.MockedFunction< - typeof authorization.actions.savedObject.get - >).mockImplementation(mockAuthorizationAction); + ( + authorization.actions.savedObject.get as jest.MockedFunction< + typeof authorization.actions.savedObject.get + > + ).mockImplementation(mockAuthorizationAction); authorization.mode.useRbacForRequest.mockReturnValue(true); return { authorization, authentication }; } @@ -215,9 +217,9 @@ describe('ensureAuthorized', () => { authorizationMode: AuthorizationMode.Legacy, }); - authentication.getCurrentUser.mockReturnValueOnce(({ + authentication.getCurrentUser.mockReturnValueOnce({ username: 'some-user', - } as unknown) as AuthenticatedUser); + } as unknown as AuthenticatedUser); await actionsAuthorization.ensureAuthorized('execute', 'myType'); diff --git a/x-pack/plugins/actions/server/authorization/audit_logger.mock.ts b/x-pack/plugins/actions/server/authorization/audit_logger.mock.ts index 5cec39569491..0be62fc0f35f 100644 --- a/x-pack/plugins/actions/server/authorization/audit_logger.mock.ts +++ b/x-pack/plugins/actions/server/authorization/audit_logger.mock.ts @@ -8,11 +8,11 @@ import { ActionsAuthorizationAuditLogger } from './audit_logger'; const createActionsAuthorizationAuditLoggerMock = () => { - const mocked = ({ + const mocked = { getAuthorizationMessage: jest.fn(), actionsAuthorizationFailure: jest.fn(), actionsAuthorizationSuccess: jest.fn(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; return mocked; }; diff --git a/x-pack/plugins/actions/server/builtin_action_types/es_index.test.ts b/x-pack/plugins/actions/server/builtin_action_types/es_index.test.ts index 5c0f720e8c5f..738fa236f89c 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/es_index.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/es_index.test.ts @@ -174,8 +174,9 @@ describe('execute()', () => { params, services, }; - const scopedClusterClient = elasticsearchClientMock.createClusterClient().asScoped() - .asCurrentUser; + const scopedClusterClient = elasticsearchClientMock + .createClusterClient() + .asScoped().asCurrentUser; await actionType.executor({ ...executorOptions, services: { ...services, scopedClusterClient }, @@ -553,8 +554,9 @@ describe('execute()', () => { }; const actionId = 'some-id'; - const scopedClusterClient = elasticsearchClientMock.createClusterClient().asScoped() - .asCurrentUser; + const scopedClusterClient = elasticsearchClientMock + .createClusterClient() + .asScoped().asCurrentUser; scopedClusterClient.bulk.mockResolvedValue( elasticsearchClientMock.createSuccessTransportRequestPromise({ took: 0, diff --git a/x-pack/plugins/actions/server/builtin_action_types/jira/index.ts b/x-pack/plugins/actions/server/builtin_action_types/jira/index.ts index aa439787ad96..c8b107094723 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/jira/index.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/jira/index.ts @@ -145,7 +145,8 @@ async function executor( } if (subAction === 'fieldsByIssueType') { - const getFieldsByIssueTypeParams = subActionParams as ExecutorSubActionGetFieldsByIssueTypeParams; + const getFieldsByIssueTypeParams = + subActionParams as ExecutorSubActionGetFieldsByIssueTypeParams; data = await api.fieldsByIssueType({ externalService, params: getFieldsByIssueTypeParams, diff --git a/x-pack/plugins/actions/server/builtin_action_types/jira/service.test.ts b/x-pack/plugins/actions/server/builtin_action_types/jira/service.test.ts index 9430d734287d..af518f0cebc0 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/jira/service.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/jira/service.test.ts @@ -657,8 +657,7 @@ describe('Jira service', () => { logger, method: 'get', configurationUtilities, - url: - 'https://siem-kibana.atlassian.net/rest/api/2/issue/createmeta?projectKeys=CK&expand=projects.issuetypes.fields', + url: 'https://siem-kibana.atlassian.net/rest/api/2/issue/createmeta?projectKeys=CK&expand=projects.issuetypes.fields', }); }); @@ -824,8 +823,7 @@ describe('Jira service', () => { logger, method: 'get', configurationUtilities, - url: - 'https://siem-kibana.atlassian.net/rest/api/2/issue/createmeta?projectKeys=CK&issuetypeIds=10006&expand=projects.issuetypes.fields', + url: 'https://siem-kibana.atlassian.net/rest/api/2/issue/createmeta?projectKeys=CK&issuetypeIds=10006&expand=projects.issuetypes.fields', }); }); diff --git a/x-pack/plugins/actions/server/builtin_action_types/lib/axios_utils.test.ts b/x-pack/plugins/actions/server/builtin_action_types/lib/axios_utils.test.ts index 292471aaf9b6..287f74c6bc70 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/lib/axios_utils.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/lib/axios_utils.test.ts @@ -20,7 +20,7 @@ const TestUrl = 'https://elastic.co/foo/bar/baz'; const logger = loggingSystemMock.create().get() as jest.Mocked; let configurationUtilities = actionsConfigMock.create(); jest.mock('axios'); -const axiosMock = (axios as unknown) as jest.Mock; +const axiosMock = axios as unknown as jest.Mock; describe('addTimeZoneToDate', () => { test('adds timezone with default', () => { diff --git a/x-pack/plugins/actions/server/builtin_action_types/lib/get_custom_agents.ts b/x-pack/plugins/actions/server/builtin_action_types/lib/get_custom_agents.ts index 83d31ae1355d..a98622a374be 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/lib/get_custom_agents.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/lib/get_custom_agents.ts @@ -115,14 +115,14 @@ export function getCustomAgents( // We will though, copy over the calculated ssl options from above, into // the https agent. const httpAgent = new HttpProxyAgent(proxySettings.proxyUrl); - const httpsAgent = (new HttpsProxyAgent({ + const httpsAgent = new HttpsProxyAgent({ host: proxyUrl.hostname, port: Number(proxyUrl.port), protocol: proxyUrl.protocol, headers: proxySettings.proxyHeaders, // do not fail on invalid certs if value is false ...proxyNodeSSLOptions, - }) as unknown) as HttpsAgent; + }) as unknown as HttpsAgent; // vsCode wasn't convinced HttpsProxyAgent is an https.Agent, so we convinced it if (agentOptions) { diff --git a/x-pack/plugins/actions/server/builtin_action_types/resilient/service.test.ts b/x-pack/plugins/actions/server/builtin_action_types/resilient/service.test.ts index 3f7da4a3bf90..ba5554338622 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/resilient/service.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/resilient/service.test.ts @@ -299,8 +299,7 @@ describe('IBM Resilient service', () => { expect(requestMock).toHaveBeenCalledWith({ axios, - url: - 'https://resilient.elastic.co/rest/orgs/201/incidents?text_content_output_format=objects_convert', + url: 'https://resilient.elastic.co/rest/orgs/201/incidents?text_content_output_format=objects_convert', logger, method: 'post', configurationUtilities, diff --git a/x-pack/plugins/actions/server/builtin_action_types/servicenow/index.test.ts b/x-pack/plugins/actions/server/builtin_action_types/servicenow/index.test.ts index 848575798f10..b34284403399 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/servicenow/index.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/servicenow/index.test.ts @@ -70,13 +70,13 @@ describe('ServiceNow', () => { test('it pass the correct comment field key', async () => { const actionId = 'some-action-id'; - const executorOptions = ({ + const executorOptions = { actionId, config, secrets, params, services, - } as unknown) as ServiceNowActionTypeExecutorOptions; + } as unknown as ServiceNowActionTypeExecutorOptions; await actionType.executor(executorOptions); expect((api.pushToService as jest.Mock).mock.calls[0][0].commentFieldKey).toBe( 'work_notes' @@ -105,13 +105,13 @@ describe('ServiceNow', () => { test('it pass the correct comment field key', async () => { const actionId = 'some-action-id'; - const executorOptions = ({ + const executorOptions = { actionId, config, secrets, params, services, - } as unknown) as ServiceNowActionTypeExecutorOptions; + } as unknown as ServiceNowActionTypeExecutorOptions; await actionType.executor(executorOptions); expect((api.pushToService as jest.Mock).mock.calls[0][0].commentFieldKey).toBe( 'work_notes' diff --git a/x-pack/plugins/actions/server/builtin_action_types/servicenow/service.test.ts b/x-pack/plugins/actions/server/builtin_action_types/servicenow/service.test.ts index aab27db85227..37bfb662508a 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/servicenow/service.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/servicenow/service.test.ts @@ -388,8 +388,7 @@ describe('ServiceNow service', () => { axios, logger, configurationUtilities, - url: - 'https://dev102283.service-now.com/api/now/v2/table/sys_dictionary?sysparm_query=name=task^ORname=incident^internal_type=string&active=true&array=false&read_only=false&sysparm_fields=max_length,element,column_label,mandatory', + url: 'https://dev102283.service-now.com/api/now/v2/table/sys_dictionary?sysparm_query=name=task^ORname=incident^internal_type=string&active=true&array=false&read_only=false&sysparm_fields=max_length,element,column_label,mandatory', }); }); @@ -421,8 +420,7 @@ describe('ServiceNow service', () => { axios, logger, configurationUtilities, - url: - 'https://dev102283.service-now.com/api/now/v2/table/sys_dictionary?sysparm_query=name=task^ORname=sn_si_incident^internal_type=string&active=true&array=false&read_only=false&sysparm_fields=max_length,element,column_label,mandatory', + url: 'https://dev102283.service-now.com/api/now/v2/table/sys_dictionary?sysparm_query=name=task^ORname=sn_si_incident^internal_type=string&active=true&array=false&read_only=false&sysparm_fields=max_length,element,column_label,mandatory', }); }); @@ -458,8 +456,7 @@ describe('ServiceNow service', () => { axios, logger, configurationUtilities, - url: - 'https://dev102283.service-now.com/api/now/v2/table/sys_choice?sysparm_query=name=task^ORname=incident^element=priority^ORelement=category&sysparm_fields=label,value,dependent_value,element', + url: 'https://dev102283.service-now.com/api/now/v2/table/sys_choice?sysparm_query=name=task^ORname=incident^element=priority^ORelement=category&sysparm_fields=label,value,dependent_value,element', }); }); @@ -492,8 +489,7 @@ describe('ServiceNow service', () => { axios, logger, configurationUtilities, - url: - 'https://dev102283.service-now.com/api/now/v2/table/sys_choice?sysparm_query=name=task^ORname=sn_si_incident^element=priority^ORelement=category&sysparm_fields=label,value,dependent_value,element', + url: 'https://dev102283.service-now.com/api/now/v2/table/sys_choice?sysparm_query=name=task^ORname=sn_si_incident^element=priority^ORelement=category&sysparm_fields=label,value,dependent_value,element', }); }); diff --git a/x-pack/plugins/actions/server/cleanup_failed_executions/cleanup_tasks.test.ts b/x-pack/plugins/actions/server/cleanup_failed_executions/cleanup_tasks.test.ts index 07c09a2dfef7..451e12b9cf29 100644 --- a/x-pack/plugins/actions/server/cleanup_failed_executions/cleanup_tasks.test.ts +++ b/x-pack/plugins/actions/server/cleanup_failed_executions/cleanup_tasks.test.ts @@ -16,14 +16,14 @@ describe('cleanupTasks', () => { const logger = loggingSystemMock.create().get(); const esClient = elasticsearchServiceMock.createElasticsearchClient(); const spaces = spacesMock.createStart(); - const savedObjectsSerializer = ({ + const savedObjectsSerializer = { generateRawId: jest .fn() .mockImplementation((namespace: string | undefined, type: string, id: string) => { const namespacePrefix = namespace ? `${namespace}:` : ''; return `${namespacePrefix}${type}:${id}`; }), - } as unknown) as SavedObjectsSerializer; + } as unknown as SavedObjectsSerializer; const cleanupTasksOpts: CleanupTasksOpts = { logger, @@ -69,9 +69,9 @@ describe('cleanupTasks', () => { }); it('should delete action_task_params and task objects', async () => { - esClient.bulk.mockResolvedValue(({ + esClient.bulk.mockResolvedValue({ body: { items: [], errors: false, took: 1 }, - } as unknown) as ApiResponse); + } as unknown as ApiResponse); const result = await cleanupTasks({ ...cleanupTasksOpts, tasks: [taskSO], @@ -90,7 +90,7 @@ describe('cleanupTasks', () => { }); it('should not delete the task if the action_task_params failed to delete', async () => { - esClient.bulk.mockResolvedValue(({ + esClient.bulk.mockResolvedValue({ body: { items: [ { @@ -106,7 +106,7 @@ describe('cleanupTasks', () => { errors: true, took: 1, }, - } as unknown) as ApiResponse); + } as unknown as ApiResponse); const result = await cleanupTasks({ ...cleanupTasksOpts, tasks: [taskSO], diff --git a/x-pack/plugins/actions/server/cleanup_failed_executions/find_and_cleanup_tasks.test.ts b/x-pack/plugins/actions/server/cleanup_failed_executions/find_and_cleanup_tasks.test.ts index 81c2a348bc09..e7ac962251f8 100644 --- a/x-pack/plugins/actions/server/cleanup_failed_executions/find_and_cleanup_tasks.test.ts +++ b/x-pack/plugins/actions/server/cleanup_failed_executions/find_and_cleanup_tasks.test.ts @@ -31,7 +31,7 @@ describe('findAndCleanupTasks', () => { const esStart = elasticsearchServiceMock.createStart(); const spaces = spacesMock.createStart(); const soService = savedObjectsServiceMock.createStartContract(); - const coreStartServices = (Promise.resolve([ + const coreStartServices = Promise.resolve([ { savedObjects: { ...soService, @@ -43,7 +43,7 @@ describe('findAndCleanupTasks', () => { spaces, }, {}, - ]) as unknown) as Promise<[CoreStart, ActionsPluginsStart, unknown]>; + ]) as unknown as Promise<[CoreStart, ActionsPluginsStart, unknown]>; const config: ActionsConfig['cleanupFailedExecutionsTask'] = { enabled: true, diff --git a/x-pack/plugins/actions/server/index.test.ts b/x-pack/plugins/actions/server/index.test.ts index 56f3533b47e3..dbe8fca806f1 100644 --- a/x-pack/plugins/actions/server/index.test.ts +++ b/x-pack/plugins/actions/server/index.test.ts @@ -20,7 +20,9 @@ const applyStackAlertDeprecations = (settings: Record = {}) => deprecation, path: CONFIG_PATH, })), - () => ({ message }) => deprecationMessages.push(message) + () => + ({ message }) => + deprecationMessages.push(message) ); return { messages: deprecationMessages, diff --git a/x-pack/plugins/actions/server/lib/errors/preconfigured_action_disabled_modification.ts b/x-pack/plugins/actions/server/lib/errors/preconfigured_action_disabled_modification.ts index e3b3c98a94e0..eec099b21114 100644 --- a/x-pack/plugins/actions/server/lib/errors/preconfigured_action_disabled_modification.ts +++ b/x-pack/plugins/actions/server/lib/errors/preconfigured_action_disabled_modification.ts @@ -12,7 +12,8 @@ export type PreconfiguredActionDisabledFrom = 'update' | 'delete'; export class PreconfiguredActionDisabledModificationError extends Error - implements ErrorThatHandlesItsOwnResponse { + implements ErrorThatHandlesItsOwnResponse +{ public readonly disabledFrom: PreconfiguredActionDisabledFrom; constructor(message: string, disabledFrom: PreconfiguredActionDisabledFrom) { diff --git a/x-pack/plugins/actions/server/lib/mustache_renderer.ts b/x-pack/plugins/actions/server/lib/mustache_renderer.ts index 3cacdf7704a8..1e7f2dd3ab64 100644 --- a/x-pack/plugins/actions/server/lib/mustache_renderer.ts +++ b/x-pack/plugins/actions/server/lib/mustache_renderer.ts @@ -40,7 +40,7 @@ export function renderMustacheObject(params: Params, variables: Variable // The return type signature for `cloneDeep()` ends up taking the return // type signature for the customizer, but rather than pollute the customizer // with casts, seemed better to just do it in one place, here. - return (result as unknown) as Params; + return result as unknown as Params; } // return variables cloned, with a toString() added to objects diff --git a/x-pack/plugins/actions/server/lib/task_runner_factory.test.ts b/x-pack/plugins/actions/server/lib/task_runner_factory.test.ts index 85d819ba09b8..ec0aa48ef291 100644 --- a/x-pack/plugins/actions/server/lib/task_runner_factory.test.ts +++ b/x-pack/plugins/actions/server/lib/task_runner_factory.test.ts @@ -119,9 +119,11 @@ test('executes the task by calling the executor with proper parameters, using gi expect(runnerResult).toBeUndefined(); expect(spaceIdToNamespace).toHaveBeenCalledWith('test'); - expect( - mockedEncryptedSavedObjectsClient.getDecryptedAsInternalUser - ).toHaveBeenCalledWith('action_task_params', '3', { namespace: 'namespace-test' }); + expect(mockedEncryptedSavedObjectsClient.getDecryptedAsInternalUser).toHaveBeenCalledWith( + 'action_task_params', + '3', + { namespace: 'namespace-test' } + ); expect(mockedActionExecutor.execute).toHaveBeenCalledWith({ actionId: '2', @@ -175,9 +177,11 @@ test('executes the task by calling the executor with proper parameters, using st expect(runnerResult).toBeUndefined(); expect(spaceIdToNamespace).toHaveBeenCalledWith('test'); - expect( - mockedEncryptedSavedObjectsClient.getDecryptedAsInternalUser - ).toHaveBeenCalledWith('action_task_params', '3', { namespace: 'namespace-test' }); + expect(mockedEncryptedSavedObjectsClient.getDecryptedAsInternalUser).toHaveBeenCalledWith( + 'action_task_params', + '3', + { namespace: 'namespace-test' } + ); expect(mockedActionExecutor.execute).toHaveBeenCalledWith({ actionId: '9', diff --git a/x-pack/plugins/actions/server/lib/task_runner_factory.ts b/x-pack/plugins/actions/server/lib/task_runner_factory.ts index 9a3856bbf7ce..4f6b9ac2e8b7 100644 --- a/x-pack/plugins/actions/server/lib/task_runner_factory.ts +++ b/x-pack/plugins/actions/server/lib/task_runner_factory.ts @@ -103,7 +103,7 @@ export class TaskRunnerFactory { // Since we're using API keys and accessing elasticsearch can only be done // via a request, we're faking one with the proper authorization headers. - const fakeRequest = KibanaRequest.from(({ + const fakeRequest = KibanaRequest.from({ headers: requestHeaders, path: '/', route: { settings: {} }, @@ -115,7 +115,7 @@ export class TaskRunnerFactory { url: '/', }, }, - } as unknown) as Request); + } as unknown as Request); basePathService.set(fakeRequest, path); @@ -205,21 +205,20 @@ async function getActionTaskParams( const { spaceId } = executorParams; const namespace = spaceIdToNamespace(spaceId); if (isPersistedActionTask(executorParams)) { - const actionTask = await encryptedSavedObjectsClient.getDecryptedAsInternalUser( - ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, - executorParams.actionTaskParamsId, - { namespace } - ); + const actionTask = + await encryptedSavedObjectsClient.getDecryptedAsInternalUser( + ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, + executorParams.actionTaskParamsId, + { namespace } + ); const { attributes: { relatedSavedObjects }, references, } = actionTask; - const { - actionId, - relatedSavedObjects: injectedRelatedSavedObjects, - } = injectSavedObjectReferences(references, relatedSavedObjects as RelatedSavedObjects); + const { actionId, relatedSavedObjects: injectedRelatedSavedObjects } = + injectSavedObjectReferences(references, relatedSavedObjects as RelatedSavedObjects); return { ...actionTask, diff --git a/x-pack/plugins/actions/server/plugin.test.ts b/x-pack/plugins/actions/server/plugin.test.ts index 1ae5eaf882cf..86d2de783ebe 100644 --- a/x-pack/plugins/actions/server/plugin.test.ts +++ b/x-pack/plugins/actions/server/plugin.test.ts @@ -88,8 +88,8 @@ describe('Actions Plugin', () => { ]; expect(handler[0]).toEqual('actions'); - const actionsContextHandler = ((await handler[1]( - ({ + const actionsContextHandler = (await handler[1]( + { core: { savedObjects: { client: {}, @@ -98,10 +98,10 @@ describe('Actions Plugin', () => { client: jest.fn(), }, }, - } as unknown) as RequestHandlerContext, + } as unknown as RequestHandlerContext, httpServerMock.createKibanaRequest(), httpServerMock.createResponseFactory() - )) as unknown) as ActionsApiRequestHandlerContext; + )) as unknown as ActionsApiRequestHandlerContext; actionsContextHandler!.getActionsClient(); }); @@ -115,17 +115,17 @@ describe('Actions Plugin', () => { ]; expect(handler[0]).toEqual('actions'); - const actionsContextHandler = ((await handler[1]( - ({ + const actionsContextHandler = (await handler[1]( + { core: { savedObjects: { client: {}, }, }, - } as unknown) as RequestHandlerContext, + } as unknown as RequestHandlerContext, httpServerMock.createKibanaRequest(), httpServerMock.createResponseFactory() - )) as unknown) as ActionsApiRequestHandlerContext; + )) as unknown as ActionsApiRequestHandlerContext; expect(() => actionsContextHandler!.getActionsClient()).toThrowErrorMatchingInlineSnapshot( `"Unable to create actions client because the Encrypted Saved Objects plugin is missing encryption key. Please set xpack.encryptedSavedObjects.encryptionKey in the kibana.yml or use the bin/kibana-encryption-keys command."` ); diff --git a/x-pack/plugins/actions/server/routes/execute.test.ts b/x-pack/plugins/actions/server/routes/execute.test.ts index 54e10698e5af..322c9aeb1560 100644 --- a/x-pack/plugins/actions/server/routes/execute.test.ts +++ b/x-pack/plugins/actions/server/routes/execute.test.ts @@ -76,9 +76,7 @@ describe('executeActionRoute', () => { const router = httpServiceMock.createRouter(); const actionsClient = actionsClientMock.create(); - actionsClient.execute.mockResolvedValueOnce( - (null as unknown) as ActionTypeExecutorResult - ); + actionsClient.execute.mockResolvedValueOnce(null as unknown as ActionTypeExecutorResult); const [context, req, res] = mockHandlerArguments( { actionsClient }, diff --git a/x-pack/plugins/actions/server/routes/legacy/_mock_handler_arguments.ts b/x-pack/plugins/actions/server/routes/legacy/_mock_handler_arguments.ts index 2a2452b02cc7..c5d0776d6c58 100644 --- a/x-pack/plugins/actions/server/routes/legacy/_mock_handler_arguments.ts +++ b/x-pack/plugins/actions/server/routes/legacy/_mock_handler_arguments.ts @@ -23,7 +23,7 @@ export function mockHandlerArguments( ): [ActionsRequestHandlerContext, KibanaRequest, KibanaResponseFactory] { const listTypes = jest.fn(() => listTypesRes); return [ - ({ + { actions: { listTypes, getActionsClient() { @@ -38,7 +38,7 @@ export function mockHandlerArguments( ); }, }, - } as unknown) as ActionsRequestHandlerContext, + } as unknown as ActionsRequestHandlerContext, req as KibanaRequest, mockResponseFactory(res), ]; @@ -53,5 +53,5 @@ export const mockResponseFactory = (resToMock: Array { const router = httpServiceMock.createRouter(); const actionsClient = actionsClientMock.create(); - actionsClient.execute.mockResolvedValueOnce( - (null as unknown) as ActionTypeExecutorResult - ); + actionsClient.execute.mockResolvedValueOnce(null as unknown as ActionTypeExecutorResult); const [context, req, res] = mockHandlerArguments( { actionsClient }, diff --git a/x-pack/plugins/actions/server/saved_objects/get_import_warnings.test.ts b/x-pack/plugins/actions/server/saved_objects/get_import_warnings.test.ts index de4ccf501637..f52cd1438265 100644 --- a/x-pack/plugins/actions/server/saved_objects/get_import_warnings.test.ts +++ b/x-pack/plugins/actions/server/saved_objects/get_import_warnings.test.ts @@ -46,7 +46,7 @@ describe('getImportWarnings', () => { }, ]; const warnings = getImportWarnings( - (savedObjectConnectors as unknown) as Array> + savedObjectConnectors as unknown as Array> ); expect(warnings[0].message).toBe('1 connector has sensitive information that require updates.'); }); @@ -89,7 +89,7 @@ describe('getImportWarnings', () => { }, ]; const warnings = getImportWarnings( - (savedObjectConnectors as unknown) as Array> + savedObjectConnectors as unknown as Array> ); expect(warnings.length).toBe(0); }); diff --git a/x-pack/plugins/actions/server/usage/actions_usage_collector.test.ts b/x-pack/plugins/actions/server/usage/actions_usage_collector.test.ts index df43cbd084be..6288b022e473 100644 --- a/x-pack/plugins/actions/server/usage/actions_usage_collector.test.ts +++ b/x-pack/plugins/actions/server/usage/actions_usage_collector.test.ts @@ -19,10 +19,10 @@ describe('registerActionsUsageCollector', () => { let usageCollectionMock: jest.Mocked; beforeEach(() => { config = configSchema.validate({}); - usageCollectionMock = ({ + usageCollectionMock = { makeUsageCollector: jest.fn(), registerCollector: jest.fn(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; }); it('should call registerCollector', () => { diff --git a/x-pack/plugins/alerting/public/alert_navigation_registry/alert_navigation_registry.ts b/x-pack/plugins/alerting/public/alert_navigation_registry/alert_navigation_registry.ts index 21f3917f2f07..65b7c1e68e43 100644 --- a/x-pack/plugins/alerting/public/alert_navigation_registry/alert_navigation_registry.ts +++ b/x-pack/plugins/alerting/public/alert_navigation_registry/alert_navigation_registry.ts @@ -11,10 +11,8 @@ import { AlertNavigationHandler } from './types'; const DEFAULT_HANDLER = Symbol('*'); export class AlertNavigationRegistry { - private readonly alertNavigations: Map< - string, - Map - > = new Map(); + private readonly alertNavigations: Map> = + new Map(); public has(consumer: string, alertType: AlertType) { return this.hasTypedHandler(consumer, alertType) || this.hasDefaultHandler(consumer); diff --git a/x-pack/plugins/alerting/server/alerting_authorization_client_factory.test.ts b/x-pack/plugins/alerting/server/alerting_authorization_client_factory.test.ts index 2ba3580745d5..ebd9ef3305a0 100644 --- a/x-pack/plugins/alerting/server/alerting_authorization_client_factory.test.ts +++ b/x-pack/plugins/alerting/server/alerting_authorization_client_factory.test.ts @@ -26,14 +26,15 @@ const features = featuresPluginMock.createStart(); const securityPluginSetup = securityMock.createSetup(); const securityPluginStart = securityMock.createStart(); -const alertingAuthorizationClientFactoryParams: jest.Mocked = { - ruleTypeRegistry: ruleTypeRegistryMock.create(), - getSpace: jest.fn(), - getSpaceId: jest.fn(), - features, -}; +const alertingAuthorizationClientFactoryParams: jest.Mocked = + { + ruleTypeRegistry: ruleTypeRegistryMock.create(), + getSpace: jest.fn(), + getSpaceId: jest.fn(), + features, + }; -const fakeRequest = ({ +const fakeRequest = { app: {}, headers: {}, getBasePath: () => '', @@ -48,7 +49,7 @@ const fakeRequest = ({ }, }, getSavedObjectsClient: () => savedObjectsClient, -} as unknown) as Request; +} as unknown as Request; beforeEach(() => { jest.resetAllMocks(); diff --git a/x-pack/plugins/alerting/server/authorization/alerting_authorization.test.ts b/x-pack/plugins/alerting/server/authorization/alerting_authorization.test.ts index 7f5b06031c18..212d8238f840 100644 --- a/x-pack/plugins/alerting/server/authorization/alerting_authorization.test.ts +++ b/x-pack/plugins/alerting/server/authorization/alerting_authorization.test.ts @@ -47,9 +47,11 @@ function mockSecurity() { const security = securityMock.createSetup(); const authorization = security.authz; // typescript is having trouble inferring jest's automocking - (authorization.actions.alerting.get as jest.MockedFunction< - typeof authorization.actions.alerting.get - >).mockImplementation(mockAuthorizationAction); + ( + authorization.actions.alerting.get as jest.MockedFunction< + typeof authorization.actions.alerting.get + > + ).mockImplementation(mockAuthorizationAction); authorization.mode.useRbacForRequest.mockReturnValue(true); return { authorization }; } @@ -933,16 +935,14 @@ describe('AlertingAuthorization', () => { getSpace, getSpaceId, }); - const { - filter, - ensureRuleTypeIsAuthorized, - } = await alertAuthorization.getFindAuthorizationFilter(AlertingAuthorizationEntity.Rule, { - type: AlertingAuthorizationFilterType.KQL, - fieldNames: { - ruleTypeId: 'ruleId', - consumer: 'consumer', - }, - }); + const { filter, ensureRuleTypeIsAuthorized } = + await alertAuthorization.getFindAuthorizationFilter(AlertingAuthorizationEntity.Rule, { + type: AlertingAuthorizationFilterType.KQL, + fieldNames: { + ruleTypeId: 'ruleId', + consumer: 'consumer', + }, + }); expect(() => ensureRuleTypeIsAuthorized('someMadeUpType', 'myApp', 'rule')).not.toThrow(); expect(filter).toEqual(undefined); }); @@ -1242,16 +1242,14 @@ describe('AlertingAuthorization', () => { getSpaceId, }); ruleTypeRegistry.list.mockReturnValue(setOfAlertTypes); - const { - ensureRuleTypeIsAuthorized, - logSuccessfulAuthorization, - } = await alertAuthorization.getFindAuthorizationFilter(AlertingAuthorizationEntity.Rule, { - type: AlertingAuthorizationFilterType.KQL, - fieldNames: { - ruleTypeId: 'ruleId', - consumer: 'consumer', - }, - }); + const { ensureRuleTypeIsAuthorized, logSuccessfulAuthorization } = + await alertAuthorization.getFindAuthorizationFilter(AlertingAuthorizationEntity.Rule, { + type: AlertingAuthorizationFilterType.KQL, + fieldNames: { + ruleTypeId: 'ruleId', + consumer: 'consumer', + }, + }); expect(() => { ensureRuleTypeIsAuthorized('myAppAlertType', 'myOtherApp', 'rule'); ensureRuleTypeIsAuthorized('mySecondAppAlertType', 'myOtherApp', 'rule'); diff --git a/x-pack/plugins/alerting/server/authorization/alerting_authorization.ts b/x-pack/plugins/alerting/server/authorization/alerting_authorization.ts index 90fe1ff83ad0..271214fa9fc0 100644 --- a/x-pack/plugins/alerting/server/authorization/alerting_authorization.ts +++ b/x-pack/plugins/alerting/server/authorization/alerting_authorization.ts @@ -435,12 +435,8 @@ export class AlertingAuthorization { : // only has some of the required privileges privileges.kibana.reduce((authorizedRuleTypes, { authorized, privilege }) => { if (authorized && privilegeToRuleType.has(privilege)) { - const [ - ruleType, - feature, - hasPrivileges, - isAuthorizedAtProducerLevel, - ] = privilegeToRuleType.get(privilege)!; + const [ruleType, feature, hasPrivileges, isAuthorizedAtProducerLevel] = + privilegeToRuleType.get(privilege)!; ruleType.authorizedConsumers[feature] = mergeHasPrivileges( hasPrivileges, ruleType.authorizedConsumers[feature] @@ -490,8 +486,8 @@ function mergeHasPrivileges(left: HasPrivileges, right?: HasPrivileges): HasPriv } function hasPrivilegeByOperation(operation: ReadOperations | WriteOperations): HasPrivileges { - const read = Object.values(ReadOperations).includes((operation as unknown) as ReadOperations); - const all = Object.values(WriteOperations).includes((operation as unknown) as WriteOperations); + const read = Object.values(ReadOperations).includes(operation as unknown as ReadOperations); + const all = Object.values(WriteOperations).includes(operation as unknown as WriteOperations); return { read: read || all, all, diff --git a/x-pack/plugins/alerting/server/authorization/audit_logger.mock.ts b/x-pack/plugins/alerting/server/authorization/audit_logger.mock.ts index 30fa6c9ef1e2..8e2c072336a1 100644 --- a/x-pack/plugins/alerting/server/authorization/audit_logger.mock.ts +++ b/x-pack/plugins/alerting/server/authorization/audit_logger.mock.ts @@ -8,13 +8,13 @@ import { AlertingAuthorizationAuditLogger } from './audit_logger'; const createAlertingAuthorizationAuditLoggerMock = () => { - const mocked = ({ + const mocked = { getAuthorizationMessage: jest.fn(), logAuthorizationFailure: jest.fn(), logUnscopedAuthorizationFailure: jest.fn(), logAuthorizationSuccess: jest.fn(), logBulkAuthorizationSuccess: jest.fn(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; return mocked; }; diff --git a/x-pack/plugins/alerting/server/health/task.ts b/x-pack/plugins/alerting/server/health/task.ts index 999e76fde696..8d69cbe56513 100644 --- a/x-pack/plugins/alerting/server/health/task.ts +++ b/x-pack/plugins/alerting/server/health/task.ts @@ -72,7 +72,9 @@ export function healthCheckTaskRunner( async run() { try { return await getAlertingHealthStatus( - (await coreStartServices)[0].savedObjects, + ( + await coreStartServices + )[0].savedObjects, state.runs ); } catch (errMsg) { diff --git a/x-pack/plugins/alerting/server/index.test.ts b/x-pack/plugins/alerting/server/index.test.ts index 45a632e0ef4a..b1e64935d7cd 100644 --- a/x-pack/plugins/alerting/server/index.test.ts +++ b/x-pack/plugins/alerting/server/index.test.ts @@ -20,7 +20,9 @@ const applyStackAlertDeprecations = (settings: Record = {}) => deprecation, path: CONFIG_PATH, })), - () => ({ message }) => deprecationMessages.push(message) + () => + ({ message }) => + deprecationMessages.push(message) ); return { messages: deprecationMessages, diff --git a/x-pack/plugins/alerting/server/invalidate_pending_api_keys/task.ts b/x-pack/plugins/alerting/server/invalidate_pending_api_keys/task.ts index 4ef0e8d25c57..f17ed8bc90aa 100644 --- a/x-pack/plugins/alerting/server/invalidate_pending_api_keys/task.ts +++ b/x-pack/plugins/alerting/server/invalidate_pending_api_keys/task.ts @@ -94,7 +94,7 @@ function registerApiKeyInvalidatorTaskDefinition( function getFakeKibanaRequest(basePath: string) { const requestHeaders: Record = {}; - return ({ + return { headers: requestHeaders, getBasePath: () => basePath, path: '/', @@ -107,7 +107,7 @@ function getFakeKibanaRequest(basePath: string) { url: '/', }, }, - } as unknown) as KibanaRequest; + } as unknown as KibanaRequest; } function taskRunner( @@ -122,10 +122,8 @@ function taskRunner( let totalInvalidated = 0; const configResult = await config; try { - const [ - { savedObjects, http }, - { encryptedSavedObjects, security }, - ] = await coreStartServices; + const [{ savedObjects, http }, { encryptedSavedObjects, security }] = + await coreStartServices; const savedObjectsClient = savedObjects.getScopedClient( getFakeKibanaRequest(http.basePath.serverBasePath), { @@ -197,10 +195,11 @@ async function invalidateApiKeys( let totalInvalidated = 0; const apiKeyIds = await Promise.all( apiKeysToInvalidate.saved_objects.map(async (apiKeyObj) => { - const decryptedApiKey = await encryptedSavedObjectsClient.getDecryptedAsInternalUser( - 'api_key_pending_invalidation', - apiKeyObj.id - ); + const decryptedApiKey = + await encryptedSavedObjectsClient.getDecryptedAsInternalUser( + 'api_key_pending_invalidation', + apiKeyObj.id + ); return decryptedApiKey.attributes.apiKeyId; }) ); diff --git a/x-pack/plugins/alerting/server/mocks.ts b/x-pack/plugins/alerting/server/mocks.ts index e9f2b564734d..639ba166e00a 100644 --- a/x-pack/plugins/alerting/server/mocks.ts +++ b/x-pack/plugins/alerting/server/mocks.ts @@ -59,7 +59,7 @@ const createAlertInstanceFactoryMock = < mock.unscheduleActions.mockReturnValue(mock); mock.scheduleActions.mockReturnValue(mock); - return (mock as unknown) as AlertInstanceMock; + return mock as unknown as AlertInstanceMock; }; const createAlertServicesMock = < diff --git a/x-pack/plugins/alerting/server/plugin.test.ts b/x-pack/plugins/alerting/server/plugin.test.ts index 57b55c25e677..4cfa1d91758e 100644 --- a/x-pack/plugins/alerting/server/plugin.test.ts +++ b/x-pack/plugins/alerting/server/plugin.test.ts @@ -222,7 +222,7 @@ describe('Alerting Plugin', () => { taskManager: taskManagerMock.createStart(), }); - const fakeRequest = ({ + const fakeRequest = { headers: {}, getBasePath: () => '', path: '/', @@ -236,7 +236,7 @@ describe('Alerting Plugin', () => { }, }, getSavedObjectsClient: jest.fn(), - } as unknown) as KibanaRequest; + } as unknown as KibanaRequest; startContract.getRulesClientWithRequest(fakeRequest); }); }); @@ -276,7 +276,7 @@ describe('Alerting Plugin', () => { taskManager: taskManagerMock.createStart(), }); - const fakeRequest = ({ + const fakeRequest = { headers: {}, getBasePath: () => '', path: '/', @@ -290,7 +290,7 @@ describe('Alerting Plugin', () => { }, }, getSavedObjectsClient: jest.fn(), - } as unknown) as KibanaRequest; + } as unknown as KibanaRequest; startContract.getAlertingAuthorizationWithRequest(fakeRequest); }); }); diff --git a/x-pack/plugins/alerting/server/routes/_mock_handler_arguments.ts b/x-pack/plugins/alerting/server/routes/_mock_handler_arguments.ts index de1d0d132671..c19beee0e841 100644 --- a/x-pack/plugins/alerting/server/routes/_mock_handler_arguments.ts +++ b/x-pack/plugins/alerting/server/routes/_mock_handler_arguments.ts @@ -35,7 +35,7 @@ export function mockHandlerArguments( ] { const listTypes = jest.fn(() => listTypesRes); return [ - ({ + { alerting: { listTypes, getRulesClient() { @@ -44,7 +44,7 @@ export function mockHandlerArguments( getFrameworkHealth, areApiKeysEnabled: areApiKeysEnabled ? areApiKeysEnabled : () => Promise.resolve(true), }, - } as unknown) as AlertingRequestHandlerContext, + } as unknown as AlertingRequestHandlerContext, req as KibanaRequest, mockResponseFactory(res), ]; @@ -59,5 +59,5 @@ export const mockResponseFactory = (resToMock: Array = await rulesClient.create( - { + const createdRule: SanitizedAlert = + await rulesClient.create({ data: rewriteBodyReq({ ...rule, notify_when: rule.notify_when as AlertNotifyWhenType, }), options: { id: params?.id }, - } - ); + }); return res.ok({ body: rewriteBodyRes(createdRule), ...(shouldWarnId diff --git a/x-pack/plugins/alerting/server/routes/legacy/create.ts b/x-pack/plugins/alerting/server/routes/legacy/create.ts index 2b0d7fedbae2..7d0f67491028 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/create.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/create.ts @@ -85,12 +85,11 @@ export const createAlertRoute = ({ router, licenseState, logger, usageCounter }: }); try { - const alertRes: SanitizedAlert = await rulesClient.create( - { + const alertRes: SanitizedAlert = + await rulesClient.create({ data: { ...alert, notifyWhen }, options: { id: params?.id }, - } - ); + }); return res.ok({ body: alertRes, ...(shouldWarnId diff --git a/x-pack/plugins/alerting/server/rule_type_registry.test.ts b/x-pack/plugins/alerting/server/rule_type_registry.test.ts index 5b80fb301963..f8067a2281f6 100644 --- a/x-pack/plugins/alerting/server/rule_type_registry.test.ts +++ b/x-pack/plugins/alerting/server/rule_type_registry.test.ts @@ -91,7 +91,7 @@ describe('register()', () => { test('throws if AlertType Id isnt a string', () => { const alertType: AlertType = { - id: (123 as unknown) as string, + id: 123 as unknown as string, name: 'Test', actionGroups: [ { @@ -125,10 +125,10 @@ describe('register()', () => { * The type system will ensure you can't use the `recovered` action group * but we also want to ensure this at runtime */ - ({ + { id: 'recovered', name: 'Recovered', - } as unknown) as ActionGroup<'NotReserved'>, + } as unknown as ActionGroup<'NotReserved'>, ], defaultActionGroupId: 'default', minimumLicenseRequired: 'basic', diff --git a/x-pack/plugins/alerting/server/rule_type_registry.ts b/x-pack/plugins/alerting/server/rule_type_registry.ts index a76181680874..3cd21d0c64dd 100644 --- a/x-pack/plugins/alerting/server/rule_type_registry.ts +++ b/x-pack/plugins/alerting/server/rule_type_registry.ts @@ -185,7 +185,7 @@ export class RuleTypeRegistry { this.ruleTypes.set( alertIdSchema.validate(alertType.id), /** stripping the typing is required in order to store the AlertTypes in a Map */ - (normalizedAlertType as unknown) as UntypedNormalizedAlertType + normalizedAlertType as unknown as UntypedNormalizedAlertType ); this.taskManager.registerTaskDefinitions({ [`alerting:${alertType.id}`]: { @@ -245,7 +245,7 @@ export class RuleTypeRegistry { * This means that returning a typed AlertType in `get` is an inherently * unsafe operation. Down casting to `unknown` is the only way to achieve this. */ - return (this.ruleTypes.get(id)! as unknown) as NormalizedAlertType< + return this.ruleTypes.get(id)! as unknown as NormalizedAlertType< Params, ExtractedParams, State, diff --git a/x-pack/plugins/alerting/server/rules_client/rules_client.ts b/x-pack/plugins/alerting/server/rules_client/rules_client.ts index 5a2a124f55ab..b4b071d426bc 100644 --- a/x-pack/plugins/alerting/server/rules_client/rules_client.ts +++ b/x-pack/plugins/alerting/server/rules_client/rules_client.ts @@ -294,11 +294,11 @@ export class RulesClient { await this.validateActions(ruleType, data.actions); // Extract saved object references for this rule - const { references, params: updatedParams, actions } = await this.extractReferences( - ruleType, - data.actions, - validatedAlertTypeParams - ); + const { + references, + params: updatedParams, + actions, + } = await this.extractReferences(ruleType, data.actions, validatedAlertTypeParams); const createTime = Date.now(); const legacyId = Semver.lt(this.kibanaVersion, '8.0.0') ? id : null; @@ -423,10 +423,8 @@ export class RulesClient { }: { id: string; }): Promise> { - const { - saved_object: result, - ...resolveResponse - } = await this.unsecuredSavedObjectsClient.resolve('alert', id); + const { saved_object: result, ...resolveResponse } = + await this.unsecuredSavedObjectsClient.resolve('alert', id); try { await this.authorization.ensureAuthorized({ ruleTypeId: result.attributes.alertTypeId, @@ -621,13 +619,11 @@ export class RulesClient { // Replace this when saved objects supports aggregations https://github.com/elastic/kibana/pull/64002 const alertExecutionStatus = await Promise.all( AlertExecutionStatusValues.map(async (status: string) => { - const { - filter: authorizationFilter, - logSuccessfulAuthorization, - } = await this.authorization.getFindAuthorizationFilter( - AlertingAuthorizationEntity.Rule, - alertingAuthorizationFilterOpts - ); + const { filter: authorizationFilter, logSuccessfulAuthorization } = + await this.authorization.getFindAuthorizationFilter( + AlertingAuthorizationEntity.Rule, + alertingAuthorizationFilterOpts + ); const filter = options.filter ? `${options.filter} and alert.attributes.executionStatus.status:(${status})` : `alert.attributes.executionStatus.status:(${status})`; @@ -665,11 +661,10 @@ export class RulesClient { let attributes: RawAlert; try { - const decryptedAlert = await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser( - 'alert', - id, - { namespace: this.namespace } - ); + const decryptedAlert = + await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser('alert', id, { + namespace: this.namespace, + }); apiKeyToInvalidate = decryptedAlert.attributes.apiKey; taskIdToRemove = decryptedAlert.attributes.scheduledTaskId; attributes = decryptedAlert.attributes; @@ -744,11 +739,10 @@ export class RulesClient { let alertSavedObject: SavedObject; try { - alertSavedObject = await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser( - 'alert', - id, - { namespace: this.namespace } - ); + alertSavedObject = + await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser('alert', id, { + namespace: this.namespace, + }); } catch (e) { // We'll skip invalidating the API key since we failed to load the decrypted saved object this.logger.error( @@ -834,11 +828,11 @@ export class RulesClient { await this.validateActions(ruleType, data.actions); // Extract saved object references for this rule - const { references, params: updatedParams, actions } = await this.extractReferences( - ruleType, - data.actions, - validatedAlertTypeParams - ); + const { + references, + params: updatedParams, + actions, + } = await this.extractReferences(ruleType, data.actions, validatedAlertTypeParams); const username = await this.getUserName(); @@ -923,11 +917,10 @@ export class RulesClient { let version: string | undefined; try { - const decryptedAlert = await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser( - 'alert', - id, - { namespace: this.namespace } - ); + const decryptedAlert = + await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser('alert', id, { + namespace: this.namespace, + }); apiKeyToInvalidate = decryptedAlert.attributes.apiKey; attributes = decryptedAlert.attributes; version = decryptedAlert.version; @@ -1028,11 +1021,10 @@ export class RulesClient { let version: string | undefined; try { - const decryptedAlert = await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser( - 'alert', - id, - { namespace: this.namespace } - ); + const decryptedAlert = + await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser('alert', id, { + namespace: this.namespace, + }); apiKeyToInvalidate = decryptedAlert.attributes.apiKey; attributes = decryptedAlert.attributes; version = decryptedAlert.version; @@ -1146,11 +1138,10 @@ export class RulesClient { let version: string | undefined; try { - const decryptedAlert = await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser( - 'alert', - id, - { namespace: this.namespace } - ); + const decryptedAlert = + await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser('alert', id, { + namespace: this.namespace, + }); apiKeyToInvalidate = decryptedAlert.attributes.apiKey; attributes = decryptedAlert.attributes; version = decryptedAlert.version; diff --git a/x-pack/plugins/alerting/server/rules_client/tests/aggregate.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/aggregate.test.ts index a336b961ace0..537a2a2a4cdc 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/aggregate.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/aggregate.test.ts @@ -32,8 +32,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/tests/create.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/create.test.ts index 7bb0829912a3..2bb92046db68 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/create.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/create.test.ts @@ -40,8 +40,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), @@ -61,9 +61,7 @@ beforeEach(() => { setGlobalDate(); -function getMockData( - overwrites: Record = {} -): CreateOptions<{ +function getMockData(overwrites: Record = {}): CreateOptions<{ bar: boolean; }>['data'] { return { diff --git a/x-pack/plugins/alerting/server/rules_client/tests/delete.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/delete.test.ts index 681af1415f34..4847314a2cea 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/delete.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/delete.test.ts @@ -31,8 +31,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts index 3cfc649cfcc3..6b9b2021db68 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts @@ -32,8 +32,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/tests/enable.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/enable.test.ts index ca3773c4d51e..7b8fbff4fca5 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/enable.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/enable.test.ts @@ -33,8 +33,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/tests/find.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/find.test.ts index cbbce77dc3bf..e151188cf397 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/find.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/find.test.ts @@ -35,8 +35,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/tests/get.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/get.test.ts index 2209322768a7..d61796431a1e 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/get.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/get.test.ts @@ -32,8 +32,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/tests/get_alert_instance_summary.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_instance_summary.test.ts index f8414b08f191..28e432a78d6f 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/get_alert_instance_summary.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_instance_summary.test.ts @@ -35,8 +35,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/tests/get_alert_state.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_state.test.ts index 8f1d11576576..2bc355343ea8 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/get_alert_state.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_state.test.ts @@ -30,8 +30,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/tests/list_alert_types.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/list_alert_types.test.ts index 19296f25a9a6..3ef7cd6f4046 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/list_alert_types.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/list_alert_types.test.ts @@ -34,8 +34,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/tests/mute_all.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/mute_all.test.ts index bea4c33659a1..883885c28aff 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/mute_all.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/mute_all.test.ts @@ -31,8 +31,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/tests/mute_instance.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/mute_instance.test.ts index 40baa663438e..cb19066500bd 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/mute_instance.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/mute_instance.test.ts @@ -31,8 +31,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/tests/resolve.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/resolve.test.ts index 63feb4ff3147..537d890217cf 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/resolve.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/resolve.test.ts @@ -32,8 +32,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/tests/unmute_all.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/unmute_all.test.ts index b863d87f28d6..4d08da7289e4 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/unmute_all.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/unmute_all.test.ts @@ -31,8 +31,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/tests/unmute_instance.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/unmute_instance.test.ts index 6a1cca4a3821..8319c486e965 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/unmute_instance.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/unmute_instance.test.ts @@ -31,8 +31,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/tests/update.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/update.test.ts index b72d8dd621ba..1328b666f96e 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/update.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/update.test.ts @@ -43,8 +43,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client/tests/update_api_key.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/update_api_key.test.ts index 8c99cea9e12c..0ee6d1162eca 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/update_api_key.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/update_api_key.test.ts @@ -32,8 +32,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), diff --git a/x-pack/plugins/alerting/server/rules_client_conflict_retries.test.ts b/x-pack/plugins/alerting/server/rules_client_conflict_retries.test.ts index f4ac4084dc6f..dfc55efad41c 100644 --- a/x-pack/plugins/alerting/server/rules_client_conflict_retries.test.ts +++ b/x-pack/plugins/alerting/server/rules_client_conflict_retries.test.ts @@ -41,8 +41,8 @@ const rulesClientParams: jest.Mocked = { taskManager, ruleTypeRegistry, unsecuredSavedObjectsClient, - authorization: (authorization as unknown) as AlertingAuthorization, - actionsAuthorization: (actionsAuthorization as unknown) as ActionsAuthorization, + authorization: authorization as unknown as AlertingAuthorization, + actionsAuthorization: actionsAuthorization as unknown as ActionsAuthorization, spaceId: 'default', namespace: 'default', getUserName: jest.fn(), @@ -210,8 +210,10 @@ function expectSuccess( // tests to run when the method is expected to fail function expectConflict(success: boolean, err: Error, method: 'update' | 'create' = 'update') { - const conflictErrorMessage = SavedObjectsErrorHelpers.createConflictError('alert', MockAlertId) - .message; + const conflictErrorMessage = SavedObjectsErrorHelpers.createConflictError( + 'alert', + MockAlertId + ).message; expect(`${err}`).toBe(`Error: ${conflictErrorMessage}`); expect(success).toBe(false); diff --git a/x-pack/plugins/alerting/server/rules_client_factory.test.ts b/x-pack/plugins/alerting/server/rules_client_factory.test.ts index 188ec652f40c..6ccde13ff12a 100644 --- a/x-pack/plugins/alerting/server/rules_client_factory.test.ts +++ b/x-pack/plugins/alerting/server/rules_client_factory.test.ts @@ -50,10 +50,11 @@ const rulesClientFactoryParams: jest.Mocked = { actions: actionsMock.createStart(), eventLog: eventLogMock.createStart(), kibanaVersion: '7.10.0', - authorization: (alertingAuthorizationClientFactory as unknown) as AlertingAuthorizationClientFactory, + authorization: + alertingAuthorizationClientFactory as unknown as AlertingAuthorizationClientFactory, }; -const fakeRequest = ({ +const fakeRequest = { app: {}, headers: {}, getBasePath: () => '', @@ -68,16 +69,16 @@ const fakeRequest = ({ }, }, getSavedObjectsClient: () => savedObjectsClient, -} as unknown) as Request; +} as unknown as Request; const actionsAuthorization = actionsAuthorizationMock.create(); beforeEach(() => { jest.resetAllMocks(); rulesClientFactoryParams.actions = actionsMock.createStart(); - (rulesClientFactoryParams.actions as jest.Mocked).getActionsAuthorizationWithRequest.mockReturnValue( - actionsAuthorization - ); + ( + rulesClientFactoryParams.actions as jest.Mocked + ).getActionsAuthorizationWithRequest.mockReturnValue(actionsAuthorization); rulesClientFactoryParams.getSpaceId.mockReturnValue('default'); rulesClientFactoryParams.spaceIdToNamespace.mockReturnValue('default'); }); @@ -89,7 +90,7 @@ test('creates an alerts client with proper constructor arguments when security i savedObjectsService.getScopedClient.mockReturnValue(savedObjectsClient); alertingAuthorizationClientFactory.create.mockReturnValue( - (alertsAuthorization as unknown) as AlertingAuthorization + alertsAuthorization as unknown as AlertingAuthorization ); const logger = { @@ -135,7 +136,7 @@ test('creates an alerts client with proper constructor arguments', async () => { savedObjectsService.getScopedClient.mockReturnValue(savedObjectsClient); alertingAuthorizationClientFactory.create.mockReturnValue( - (alertsAuthorization as unknown) as AlertingAuthorization + alertsAuthorization as unknown as AlertingAuthorization ); factory.create(request, savedObjectsService); @@ -185,9 +186,9 @@ test('getUserName() returns a name when security is enabled', async () => { factory.create(KibanaRequest.from(fakeRequest), savedObjectsService); const constructorCall = jest.requireMock('./rules_client').RulesClient.mock.calls[0][0]; - securityPluginStart.authc.getCurrentUser.mockReturnValueOnce(({ + securityPluginStart.authc.getCurrentUser.mockReturnValueOnce({ username: 'bob', - } as unknown) as AuthenticatedUser); + } as unknown as AuthenticatedUser); const userNameResult = await constructorCall.getUserName(); expect(userNameResult).toEqual('bob'); }); diff --git a/x-pack/plugins/alerting/server/saved_objects/get_import_warnings.test.ts b/x-pack/plugins/alerting/server/saved_objects/get_import_warnings.test.ts index d76e151b8d47..18c26336721f 100644 --- a/x-pack/plugins/alerting/server/saved_objects/get_import_warnings.test.ts +++ b/x-pack/plugins/alerting/server/saved_objects/get_import_warnings.test.ts @@ -71,17 +71,13 @@ describe('getImportWarnings', () => { references: [], }, ]; - const warnings = getImportWarnings( - (savedObjectRules as unknown) as Array> - ); + const warnings = getImportWarnings(savedObjectRules as unknown as Array>); expect(warnings[0].message).toBe('2 rules must be enabled after the import.'); }); it('return no warning messages if no rules were imported', () => { const savedObjectRules = [] as Array>; - const warnings = getImportWarnings( - (savedObjectRules as unknown) as Array> - ); + const warnings = getImportWarnings(savedObjectRules as unknown as Array>); expect(warnings.length).toBe(0); }); }); diff --git a/x-pack/plugins/alerting/server/saved_objects/migrations.test.ts b/x-pack/plugins/alerting/server/saved_objects/migrations.test.ts index e460167b40d2..10e7a92b80da 100644 --- a/x-pack/plugins/alerting/server/saved_objects/migrations.test.ts +++ b/x-pack/plugins/alerting/server/saved_objects/migrations.test.ts @@ -692,8 +692,7 @@ describe('successful migrations', () => { references: [ 'https://www.fireeye.com/blog/threat-research/2018/08/fin7-pursuing-an-enigmatic-and-evasive-global-criminal-operation.html', ], - note: - 'In the event this rule identifies benign domains in your environment, the `destination.domain` field in the rule can be modified to include those domains. Example: `...AND NOT destination.domain:(zoom.us OR benign.domain1 OR benign.domain2)`.', + note: 'In the event this rule identifies benign domains in your environment, the `destination.domain` field in the rule can be modified to include those domains. Example: `...AND NOT destination.domain:(zoom.us OR benign.domain1 OR benign.domain2)`.', version: 1, exceptionsList: null, threshold: { @@ -734,8 +733,7 @@ describe('successful migrations', () => { references: [ 'https://www.fireeye.com/blog/threat-research/2018/08/fin7-pursuing-an-enigmatic-and-evasive-global-criminal-operation.html', ], - note: - 'In the event this rule identifies benign domains in your environment, the `destination.domain` field in the rule can be modified to include those domains. Example: `...AND NOT destination.domain:(zoom.us OR benign.domain1 OR benign.domain2)`.', + note: 'In the event this rule identifies benign domains in your environment, the `destination.domain` field in the rule can be modified to include those domains. Example: `...AND NOT destination.domain:(zoom.us OR benign.domain1 OR benign.domain2)`.', version: 1, exceptionsList: [], threshold: { @@ -806,8 +804,7 @@ describe('successful migrations', () => { references: [ 'https://www.fireeye.com/blog/threat-research/2018/08/fin7-pursuing-an-enigmatic-and-evasive-global-criminal-operation.html', ], - note: - 'In the event this rule identifies benign domains in your environment, the `destination.domain` field in the rule can be modified to include those domains. Example: `...AND NOT destination.domain:(zoom.us OR benign.domain1 OR benign.domain2)`.', + note: 'In the event this rule identifies benign domains in your environment, the `destination.domain` field in the rule can be modified to include those domains. Example: `...AND NOT destination.domain:(zoom.us OR benign.domain1 OR benign.domain2)`.', version: 1, exceptionsList: ['exceptions-list'], }, diff --git a/x-pack/plugins/alerting/server/saved_objects/migrations.ts b/x-pack/plugins/alerting/server/saved_objects/migrations.ts index c0af554cd7a4..3be9199876e0 100644 --- a/x-pack/plugins/alerting/server/saved_objects/migrations.ts +++ b/x-pack/plugins/alerting/server/saved_objects/migrations.ts @@ -306,25 +306,17 @@ function restructureConnectorsThatSupportIncident( }, ] as RawAlertAction[]; } else if (action.actionTypeId === '.jira') { - const { - title, - comments, - description, - issueType, - priority, - labels, - parent, - summary, - } = action.params.subActionParams as { - title: string; - description: string; - issueType: string; - priority?: string; - labels?: string[]; - parent?: string; - comments?: unknown[]; - summary?: string; - }; + const { title, comments, description, issueType, priority, labels, parent, summary } = + action.params.subActionParams as { + title: string; + description: string; + issueType: string; + priority?: string; + labels?: string[]; + parent?: string; + comments?: unknown[]; + summary?: string; + }; return [ ...acc, { diff --git a/x-pack/plugins/alerting/server/saved_objects/partially_update_alert.test.ts b/x-pack/plugins/alerting/server/saved_objects/partially_update_alert.test.ts index d890089132c0..37729dada316 100644 --- a/x-pack/plugins/alerting/server/saved_objects/partially_update_alert.test.ts +++ b/x-pack/plugins/alerting/server/saved_objects/partially_update_alert.test.ts @@ -15,7 +15,8 @@ import { partiallyUpdateAlert, PartiallyUpdateableAlertAttributes } from './part import { savedObjectsClientMock } from '../../../../../src/core/server/mocks'; const MockSavedObjectsClientContract = savedObjectsClientMock.create(); -const MockISavedObjectsRepository = (MockSavedObjectsClientContract as unknown) as jest.Mocked; +const MockISavedObjectsRepository = + MockSavedObjectsClientContract as unknown as jest.Mocked; describe('partially_update_alert', () => { beforeEach(() => { @@ -32,7 +33,7 @@ describe('partially_update_alert', () => { }); test('should work with extraneous attributes ', async () => { - const attributes = (InvalidAttributes as unknown) as PartiallyUpdateableAlertAttributes; + const attributes = InvalidAttributes as unknown as PartiallyUpdateableAlertAttributes; soClient.update.mockResolvedValueOnce(MockUpdateValue); await partiallyUpdateAlert(soClient, MockAlertId, attributes); diff --git a/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts b/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts index 26b17d76553f..bc477136ec11 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner.test.ts @@ -360,48 +360,49 @@ describe('Task Runner', () => { testAgainstEphemeralSupport( 'actionsPlugin.execute is called per alert instance that is scheduled', ( - customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, - enqueueFunction: (options: ExecuteOptions) => Promise - ) => async () => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(new Promise(() => {})); - alertType.executor.mockImplementation( - async ({ - services: executorServices, - }: AlertExecutorOptions< - AlertTypeParams, - AlertTypeState, - AlertInstanceState, - AlertInstanceContext, - string - >) => { - executorServices - .alertInstanceFactory('1') - .scheduleActionsWithSubGroup('default', 'subDefault'); - } - ); - const taskRunner = new TaskRunner( - alertType, - mockedTaskInstance, - customTaskRunnerFactoryInitializerParams - ); - rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ - id: '1', - type: 'alert', - attributes: { - apiKey: Buffer.from('123:abc').toString('base64'), - }, - references: [], - }); - await taskRunner.run(); - expect(enqueueFunction).toHaveBeenCalledTimes(1); - expect((enqueueFunction as jest.Mock).mock.calls[0]).toMatchInlineSnapshot(` + customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, + enqueueFunction: (options: ExecuteOptions) => Promise + ) => + async () => { + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( + true + ); + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( + true + ); + actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(new Promise(() => {})); + alertType.executor.mockImplementation( + async ({ + services: executorServices, + }: AlertExecutorOptions< + AlertTypeParams, + AlertTypeState, + AlertInstanceState, + AlertInstanceContext, + string + >) => { + executorServices + .alertInstanceFactory('1') + .scheduleActionsWithSubGroup('default', 'subDefault'); + } + ); + const taskRunner = new TaskRunner( + alertType, + mockedTaskInstance, + customTaskRunnerFactoryInitializerParams + ); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ + id: '1', + type: 'alert', + attributes: { + apiKey: Buffer.from('123:abc').toString('base64'), + }, + references: [], + }); + await taskRunner.run(); + expect(enqueueFunction).toHaveBeenCalledTimes(1); + expect((enqueueFunction as jest.Mock).mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "apiKey": "MTIzOmFiYw==", @@ -429,180 +430,184 @@ describe('Task Runner', () => { ] `); - const logger = customTaskRunnerFactoryInitializerParams.logger; - expect(logger.debug).toHaveBeenCalledTimes(3); - expect(logger.debug).nthCalledWith(1, 'executing alert test:1 at 1970-01-01T00:00:00.000Z'); - expect(logger.debug).nthCalledWith( - 2, - `alert test:1: 'alert-name' has 1 active alert instances: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"}]` - ); - expect(logger.debug).nthCalledWith( - 3, - 'alertExecutionStatus for test:1: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}' - ); - // alertExecutionStatus for test:1: {\"lastExecutionDate\":\"1970-01-01T00:00:00.000Z\",\"status\":\"error\",\"error\":{\"reason\":\"unknown\",\"message\":\"Cannot read property 'catch' of undefined\"}} - - const eventLogger = customTaskRunnerFactoryInitializerParams.eventLogger; - expect(eventLogger.logEvent).toHaveBeenCalledTimes(5); - expect(eventLogger.logEvent).toHaveBeenNthCalledWith(1, { - '@timestamp': '1970-01-01T00:00:00.000Z', - event: { - action: 'execute-start', - category: ['alerts'], - kind: 'alert', - }, - kibana: { - task: { - schedule_delay: 0, - scheduled: '1970-01-01T00:00:00.000Z', + const logger = customTaskRunnerFactoryInitializerParams.logger; + expect(logger.debug).toHaveBeenCalledTimes(3); + expect(logger.debug).nthCalledWith(1, 'executing alert test:1 at 1970-01-01T00:00:00.000Z'); + expect(logger.debug).nthCalledWith( + 2, + `alert test:1: 'alert-name' has 1 active alert instances: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"}]` + ); + expect(logger.debug).nthCalledWith( + 3, + 'alertExecutionStatus for test:1: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}' + ); + // alertExecutionStatus for test:1: {\"lastExecutionDate\":\"1970-01-01T00:00:00.000Z\",\"status\":\"error\",\"error\":{\"reason\":\"unknown\",\"message\":\"Cannot read property 'catch' of undefined\"}} + + const eventLogger = customTaskRunnerFactoryInitializerParams.eventLogger; + expect(eventLogger.logEvent).toHaveBeenCalledTimes(5); + expect(eventLogger.logEvent).toHaveBeenNthCalledWith(1, { + '@timestamp': '1970-01-01T00:00:00.000Z', + event: { + action: 'execute-start', + category: ['alerts'], + kind: 'alert', }, - saved_objects: [ - { - id: '1', - namespace: undefined, - rel: 'primary', - type: 'alert', - type_id: 'test', - }, - ], - }, - message: `alert execution start: "1"`, - rule: { - category: 'test', - id: '1', - license: 'basic', - ruleset: 'alerts', - }, - }); - expect(eventLogger.logEvent).toHaveBeenNthCalledWith(2, { - event: { - action: 'new-instance', - category: ['alerts'], - kind: 'alert', - duration: 0, - start: '1970-01-01T00:00:00.000Z', - }, - kibana: { - alerting: { - action_group_id: 'default', - action_subgroup: 'subDefault', - instance_id: '1', + kibana: { + task: { + schedule_delay: 0, + scheduled: '1970-01-01T00:00:00.000Z', + }, + saved_objects: [ + { + id: '1', + namespace: undefined, + rel: 'primary', + type: 'alert', + type_id: 'test', + }, + ], }, - saved_objects: [ - { - id: '1', - namespace: undefined, - rel: 'primary', - type: 'alert', - type_id: 'test', - }, - ], - }, - message: "test:1: 'alert-name' created new instance: '1'", - rule: { - category: 'test', - id: '1', - license: 'basic', - name: 'alert-name', - namespace: undefined, - ruleset: 'alerts', - }, - }); - expect(eventLogger.logEvent).toHaveBeenNthCalledWith(3, { - event: { - action: 'active-instance', - category: ['alerts'], - duration: 0, - kind: 'alert', - start: '1970-01-01T00:00:00.000Z', - }, - kibana: { - alerting: { action_group_id: 'default', action_subgroup: 'subDefault', instance_id: '1' }, - saved_objects: [ - { id: '1', namespace: undefined, rel: 'primary', type: 'alert', type_id: 'test' }, - ], - }, - message: - "test:1: 'alert-name' active instance: '1' in actionGroup(subgroup): 'default(subDefault)'", - rule: { - category: 'test', - id: '1', - license: 'basic', - name: 'alert-name', - namespace: undefined, - ruleset: 'alerts', - }, - }); - expect(eventLogger.logEvent).toHaveBeenNthCalledWith(4, { - event: { - action: 'execute-action', - category: ['alerts'], - kind: 'alert', - }, - kibana: { - alerting: { - instance_id: '1', - action_group_id: 'default', - action_subgroup: 'subDefault', + message: `alert execution start: "1"`, + rule: { + category: 'test', + id: '1', + license: 'basic', + ruleset: 'alerts', }, - saved_objects: [ - { - id: '1', - namespace: undefined, - rel: 'primary', - type: 'alert', - type_id: 'test', - }, - { - id: '1', - namespace: undefined, - type: 'action', - type_id: 'action', - }, - ], - }, - message: - "alert: test:1: 'alert-name' instanceId: '1' scheduled actionGroup(subgroup): 'default(subDefault)' action: action:1", - rule: { - category: 'test', - id: '1', - license: 'basic', - name: 'alert-name', - namespace: undefined, - ruleset: 'alerts', - }, - }); - expect(eventLogger.logEvent).toHaveBeenNthCalledWith(5, { - '@timestamp': '1970-01-01T00:00:00.000Z', - event: { action: 'execute', category: ['alerts'], kind: 'alert', outcome: 'success' }, - kibana: { - alerting: { - status: 'active', + }); + expect(eventLogger.logEvent).toHaveBeenNthCalledWith(2, { + event: { + action: 'new-instance', + category: ['alerts'], + kind: 'alert', + duration: 0, + start: '1970-01-01T00:00:00.000Z', }, - task: { - schedule_delay: 0, - scheduled: '1970-01-01T00:00:00.000Z', + kibana: { + alerting: { + action_group_id: 'default', + action_subgroup: 'subDefault', + instance_id: '1', + }, + saved_objects: [ + { + id: '1', + namespace: undefined, + rel: 'primary', + type: 'alert', + type_id: 'test', + }, + ], }, - saved_objects: [ - { - id: '1', - namespace: undefined, - rel: 'primary', - type: 'alert', - type_id: 'test', - }, - ], - }, - message: "alert executed: test:1: 'alert-name'", - rule: { - category: 'test', - id: '1', - license: 'basic', - name: 'alert-name', - ruleset: 'alerts', - }, - }); - } + message: "test:1: 'alert-name' created new instance: '1'", + rule: { + category: 'test', + id: '1', + license: 'basic', + name: 'alert-name', + namespace: undefined, + ruleset: 'alerts', + }, + }); + expect(eventLogger.logEvent).toHaveBeenNthCalledWith(3, { + event: { + action: 'active-instance', + category: ['alerts'], + duration: 0, + kind: 'alert', + start: '1970-01-01T00:00:00.000Z', + }, + kibana: { + alerting: { + action_group_id: 'default', + action_subgroup: 'subDefault', + instance_id: '1', + }, + saved_objects: [ + { id: '1', namespace: undefined, rel: 'primary', type: 'alert', type_id: 'test' }, + ], + }, + message: + "test:1: 'alert-name' active instance: '1' in actionGroup(subgroup): 'default(subDefault)'", + rule: { + category: 'test', + id: '1', + license: 'basic', + name: 'alert-name', + namespace: undefined, + ruleset: 'alerts', + }, + }); + expect(eventLogger.logEvent).toHaveBeenNthCalledWith(4, { + event: { + action: 'execute-action', + category: ['alerts'], + kind: 'alert', + }, + kibana: { + alerting: { + instance_id: '1', + action_group_id: 'default', + action_subgroup: 'subDefault', + }, + saved_objects: [ + { + id: '1', + namespace: undefined, + rel: 'primary', + type: 'alert', + type_id: 'test', + }, + { + id: '1', + namespace: undefined, + type: 'action', + type_id: 'action', + }, + ], + }, + message: + "alert: test:1: 'alert-name' instanceId: '1' scheduled actionGroup(subgroup): 'default(subDefault)' action: action:1", + rule: { + category: 'test', + id: '1', + license: 'basic', + name: 'alert-name', + namespace: undefined, + ruleset: 'alerts', + }, + }); + expect(eventLogger.logEvent).toHaveBeenNthCalledWith(5, { + '@timestamp': '1970-01-01T00:00:00.000Z', + event: { action: 'execute', category: ['alerts'], kind: 'alert', outcome: 'success' }, + kibana: { + alerting: { + status: 'active', + }, + task: { + schedule_delay: 0, + scheduled: '1970-01-01T00:00:00.000Z', + }, + saved_objects: [ + { + id: '1', + namespace: undefined, + rel: 'primary', + type: 'alert', + type_id: 'test', + }, + ], + }, + message: "alert executed: test:1: 'alert-name'", + rule: { + category: 'test', + id: '1', + license: 'basic', + name: 'alert-name', + ruleset: 'alerts', + }, + }); + } ); test('actionsPlugin.execute is skipped if muteAll is true', async () => { @@ -796,66 +801,67 @@ describe('Task Runner', () => { testAgainstEphemeralSupport( 'skips firing actions for active instance if instance is muted', ( - customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, - enqueueFunction: (options: ExecuteOptions) => Promise - ) => async () => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(new Promise(() => {})); - alertType.executor.mockImplementation( - async ({ - services: executorServices, - }: AlertExecutorOptions< - AlertTypeParams, - AlertTypeState, - AlertInstanceState, - AlertInstanceContext, - string - >) => { - executorServices.alertInstanceFactory('1').scheduleActions('default'); - executorServices.alertInstanceFactory('2').scheduleActions('default'); - } - ); - const taskRunner = new TaskRunner( - alertType, - mockedTaskInstance, - customTaskRunnerFactoryInitializerParams - ); - rulesClient.get.mockResolvedValue({ - ...mockedAlertTypeSavedObject, - mutedInstanceIds: ['2'], - }); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ - id: '1', - type: 'alert', - attributes: { - apiKey: Buffer.from('123:abc').toString('base64'), - }, - references: [], - }); - await taskRunner.run(); - expect(enqueueFunction).toHaveBeenCalledTimes(1); - - const logger = customTaskRunnerFactoryInitializerParams.logger; - expect(logger.debug).toHaveBeenCalledTimes(4); - expect(logger.debug).nthCalledWith(1, 'executing alert test:1 at 1970-01-01T00:00:00.000Z'); - expect(logger.debug).nthCalledWith( - 2, - `alert test:1: 'alert-name' has 2 active alert instances: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"},{\"instanceId\":\"2\",\"actionGroup\":\"default\"}]` - ); - expect(logger.debug).nthCalledWith( - 3, - `skipping scheduling of actions for '2' in alert test:1: 'alert-name': instance is muted` - ); - expect(logger.debug).nthCalledWith( - 4, - 'alertExecutionStatus for test:1: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}' - ); - } + customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, + enqueueFunction: (options: ExecuteOptions) => Promise + ) => + async () => { + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( + true + ); + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( + true + ); + actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(new Promise(() => {})); + alertType.executor.mockImplementation( + async ({ + services: executorServices, + }: AlertExecutorOptions< + AlertTypeParams, + AlertTypeState, + AlertInstanceState, + AlertInstanceContext, + string + >) => { + executorServices.alertInstanceFactory('1').scheduleActions('default'); + executorServices.alertInstanceFactory('2').scheduleActions('default'); + } + ); + const taskRunner = new TaskRunner( + alertType, + mockedTaskInstance, + customTaskRunnerFactoryInitializerParams + ); + rulesClient.get.mockResolvedValue({ + ...mockedAlertTypeSavedObject, + mutedInstanceIds: ['2'], + }); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ + id: '1', + type: 'alert', + attributes: { + apiKey: Buffer.from('123:abc').toString('base64'), + }, + references: [], + }); + await taskRunner.run(); + expect(enqueueFunction).toHaveBeenCalledTimes(1); + + const logger = customTaskRunnerFactoryInitializerParams.logger; + expect(logger.debug).toHaveBeenCalledTimes(4); + expect(logger.debug).nthCalledWith(1, 'executing alert test:1 at 1970-01-01T00:00:00.000Z'); + expect(logger.debug).nthCalledWith( + 2, + `alert test:1: 'alert-name' has 2 active alert instances: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"},{\"instanceId\":\"2\",\"actionGroup\":\"default\"}]` + ); + expect(logger.debug).nthCalledWith( + 3, + `skipping scheduling of actions for '2' in alert test:1: 'alert-name': instance is muted` + ); + expect(logger.debug).nthCalledWith( + 4, + 'alertExecutionStatus for test:1: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}' + ); + } ); test('actionsPlugin.execute is not called when notifyWhen=onActionGroupChange and alert instance state does not change', async () => { @@ -1032,193 +1038,196 @@ describe('Task Runner', () => { testAgainstEphemeralSupport( 'actionsPlugin.execute is called when notifyWhen=onActionGroupChange and alert instance state has changed', ( - customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, - enqueueFunction: (options: ExecuteOptions) => Promise - ) => async () => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - alertType.executor.mockImplementation( - async ({ - services: executorServices, - }: AlertExecutorOptions< - AlertTypeParams, - AlertTypeState, - AlertInstanceState, - AlertInstanceContext, - string - >) => { - executorServices.alertInstanceFactory('1').scheduleActions('default'); - } - ); - const taskRunner = new TaskRunner( - alertType, - { - ...mockedTaskInstance, - state: { - ...mockedTaskInstance.state, - alertInstances: { - '1': { - meta: { - lastScheduledActions: { group: 'newGroup', date: new Date().toISOString() }, + customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, + enqueueFunction: (options: ExecuteOptions) => Promise + ) => + async () => { + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( + true + ); + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( + true + ); + alertType.executor.mockImplementation( + async ({ + services: executorServices, + }: AlertExecutorOptions< + AlertTypeParams, + AlertTypeState, + AlertInstanceState, + AlertInstanceContext, + string + >) => { + executorServices.alertInstanceFactory('1').scheduleActions('default'); + } + ); + const taskRunner = new TaskRunner( + alertType, + { + ...mockedTaskInstance, + state: { + ...mockedTaskInstance.state, + alertInstances: { + '1': { + meta: { + lastScheduledActions: { group: 'newGroup', date: new Date().toISOString() }, + }, + state: { bar: false }, }, - state: { bar: false }, }, }, }, - }, - customTaskRunnerFactoryInitializerParams - ); - rulesClient.get.mockResolvedValue({ - ...mockedAlertTypeSavedObject, - notifyWhen: 'onActionGroupChange', - }); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ - id: '1', - type: 'alert', - attributes: { - apiKey: Buffer.from('123:abc').toString('base64'), - }, - references: [], - }); - await taskRunner.run(); - expect(enqueueFunction).toHaveBeenCalledTimes(1); - } + customTaskRunnerFactoryInitializerParams + ); + rulesClient.get.mockResolvedValue({ + ...mockedAlertTypeSavedObject, + notifyWhen: 'onActionGroupChange', + }); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ + id: '1', + type: 'alert', + attributes: { + apiKey: Buffer.from('123:abc').toString('base64'), + }, + references: [], + }); + await taskRunner.run(); + expect(enqueueFunction).toHaveBeenCalledTimes(1); + } ); testAgainstEphemeralSupport( 'actionsPlugin.execute is called when notifyWhen=onActionGroupChange and alert instance state subgroup has changed', ( - customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, - enqueueFunction: (options: ExecuteOptions) => Promise - ) => async () => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - alertType.executor.mockImplementation( - async ({ - services: executorServices, - }: AlertExecutorOptions< - AlertTypeParams, - AlertTypeState, - AlertInstanceState, - AlertInstanceContext, - string - >) => { - executorServices - .alertInstanceFactory('1') - .scheduleActionsWithSubGroup('default', 'subgroup1'); - } - ); - const taskRunner = new TaskRunner( - alertType, - { - ...mockedTaskInstance, - state: { - ...mockedTaskInstance.state, - alertInstances: { - '1': { - meta: { - lastScheduledActions: { - group: 'default', - subgroup: 'newSubgroup', - date: new Date().toISOString(), + customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, + enqueueFunction: (options: ExecuteOptions) => Promise + ) => + async () => { + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( + true + ); + + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( + true + ); + alertType.executor.mockImplementation( + async ({ + services: executorServices, + }: AlertExecutorOptions< + AlertTypeParams, + AlertTypeState, + AlertInstanceState, + AlertInstanceContext, + string + >) => { + executorServices + .alertInstanceFactory('1') + .scheduleActionsWithSubGroup('default', 'subgroup1'); + } + ); + const taskRunner = new TaskRunner( + alertType, + { + ...mockedTaskInstance, + state: { + ...mockedTaskInstance.state, + alertInstances: { + '1': { + meta: { + lastScheduledActions: { + group: 'default', + subgroup: 'newSubgroup', + date: new Date().toISOString(), + }, }, + state: { bar: false }, }, - state: { bar: false }, }, }, }, - }, - customTaskRunnerFactoryInitializerParams - ); - rulesClient.get.mockResolvedValue({ - ...mockedAlertTypeSavedObject, - notifyWhen: 'onActionGroupChange', - }); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ - id: '1', - type: 'alert', - attributes: { - apiKey: Buffer.from('123:abc').toString('base64'), - }, - references: [], - }); - await taskRunner.run(); - expect(enqueueFunction).toHaveBeenCalledTimes(1); - } + customTaskRunnerFactoryInitializerParams + ); + rulesClient.get.mockResolvedValue({ + ...mockedAlertTypeSavedObject, + notifyWhen: 'onActionGroupChange', + }); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ + id: '1', + type: 'alert', + attributes: { + apiKey: Buffer.from('123:abc').toString('base64'), + }, + references: [], + }); + await taskRunner.run(); + expect(enqueueFunction).toHaveBeenCalledTimes(1); + } ); testAgainstEphemeralSupport( 'includes the apiKey in the request used to initialize the actionsClient', ( - customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, - enqueueFunction: (options: ExecuteOptions) => Promise - ) => async () => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(new Promise(() => {})); - alertType.executor.mockImplementation( - async ({ - services: executorServices, - }: AlertExecutorOptions< - AlertTypeParams, - AlertTypeState, - AlertInstanceState, - AlertInstanceContext, - string - >) => { - executorServices.alertInstanceFactory('1').scheduleActions('default'); - } - ); - const taskRunner = new TaskRunner( - alertType, - mockedTaskInstance, - customTaskRunnerFactoryInitializerParams - ); - rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ - id: '1', - type: 'alert', - attributes: { - apiKey: Buffer.from('123:abc').toString('base64'), - }, - references: [], - }); - await taskRunner.run(); - expect( - customTaskRunnerFactoryInitializerParams.actionsPlugin.getActionsClientWithRequest - ).toHaveBeenCalledWith( - expect.objectContaining({ - headers: { - // base64 encoded "123:abc" - authorization: 'ApiKey MTIzOmFiYw==', + customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, + enqueueFunction: (options: ExecuteOptions) => Promise + ) => + async () => { + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( + true + ); + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( + true + ); + actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(new Promise(() => {})); + alertType.executor.mockImplementation( + async ({ + services: executorServices, + }: AlertExecutorOptions< + AlertTypeParams, + AlertTypeState, + AlertInstanceState, + AlertInstanceContext, + string + >) => { + executorServices.alertInstanceFactory('1').scheduleActions('default'); + } + ); + const taskRunner = new TaskRunner( + alertType, + mockedTaskInstance, + customTaskRunnerFactoryInitializerParams + ); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValueOnce({ + id: '1', + type: 'alert', + attributes: { + apiKey: Buffer.from('123:abc').toString('base64'), }, - }) - ); - - const [ - request, - ] = customTaskRunnerFactoryInitializerParams.actionsPlugin.getActionsClientWithRequest.mock.calls[0]; - - expect(customTaskRunnerFactoryInitializerParams.basePathService.set).toHaveBeenCalledWith( - request, - '/' - ); - - expect(enqueueFunction).toHaveBeenCalledTimes(1); - expect((enqueueFunction as jest.Mock).mock.calls[0]).toMatchInlineSnapshot(` + references: [], + }); + await taskRunner.run(); + expect( + customTaskRunnerFactoryInitializerParams.actionsPlugin.getActionsClientWithRequest + ).toHaveBeenCalledWith( + expect.objectContaining({ + headers: { + // base64 encoded "123:abc" + authorization: 'ApiKey MTIzOmFiYw==', + }, + }) + ); + + const [request] = + customTaskRunnerFactoryInitializerParams.actionsPlugin.getActionsClientWithRequest.mock + .calls[0]; + + expect(customTaskRunnerFactoryInitializerParams.basePathService.set).toHaveBeenCalledWith( + request, + '/' + ); + + expect(enqueueFunction).toHaveBeenCalledTimes(1); + expect((enqueueFunction as jest.Mock).mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "apiKey": "MTIzOmFiYw==", @@ -1246,10 +1255,10 @@ describe('Task Runner', () => { ] `); - const eventLogger = customTaskRunnerFactoryInitializerParams.eventLogger; - expect(eventLogger.logEvent).toHaveBeenCalledTimes(5); - expect(eventLogger.startTiming).toHaveBeenCalledTimes(1); - expect(eventLogger.logEvent.mock.calls).toMatchInlineSnapshot(` + const eventLogger = customTaskRunnerFactoryInitializerParams.eventLogger; + expect(eventLogger.logEvent).toHaveBeenCalledTimes(5); + expect(eventLogger.startTiming).toHaveBeenCalledTimes(1); + expect(eventLogger.logEvent.mock.calls).toMatchInlineSnapshot(` Array [ Array [ Object { @@ -1439,75 +1448,76 @@ describe('Task Runner', () => { ], ] `); - } + } ); testAgainstEphemeralSupport( 'fire recovered actions for execution for the alertInstances which is in the recovered state', ( - customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, - enqueueFunction: (options: ExecuteOptions) => Promise - ) => async () => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(new Promise(() => {})); - - alertType.executor.mockImplementation( - async ({ - services: executorServices, - }: AlertExecutorOptions< - AlertTypeParams, - AlertTypeState, - AlertInstanceState, - AlertInstanceContext, - string - >) => { - executorServices.alertInstanceFactory('1').scheduleActions('default'); - } - ); - const taskRunner = new TaskRunner( - alertType, - { - ...mockedTaskInstance, - state: { - ...mockedTaskInstance.state, - alertInstances: { - '1': { - meta: {}, - state: { - bar: false, - start: '1969-12-31T00:00:00.000Z', - duration: 80000000000, + customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, + enqueueFunction: (options: ExecuteOptions) => Promise + ) => + async () => { + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( + true + ); + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( + true + ); + actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(new Promise(() => {})); + + alertType.executor.mockImplementation( + async ({ + services: executorServices, + }: AlertExecutorOptions< + AlertTypeParams, + AlertTypeState, + AlertInstanceState, + AlertInstanceContext, + string + >) => { + executorServices.alertInstanceFactory('1').scheduleActions('default'); + } + ); + const taskRunner = new TaskRunner( + alertType, + { + ...mockedTaskInstance, + state: { + ...mockedTaskInstance.state, + alertInstances: { + '1': { + meta: {}, + state: { + bar: false, + start: '1969-12-31T00:00:00.000Z', + duration: 80000000000, + }, }, - }, - '2': { - meta: {}, - state: { - bar: false, - start: '1969-12-31T06:00:00.000Z', - duration: 70000000000, + '2': { + meta: {}, + state: { + bar: false, + start: '1969-12-31T06:00:00.000Z', + duration: 70000000000, + }, }, }, }, }, - }, - customTaskRunnerFactoryInitializerParams - ); - rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ - id: '1', - type: 'alert', - attributes: { - apiKey: Buffer.from('123:abc').toString('base64'), - }, - references: [], - }); - const runnerResult = await taskRunner.run(); - expect(runnerResult.state.alertInstances).toMatchInlineSnapshot(` + customTaskRunnerFactoryInitializerParams + ); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ + id: '1', + type: 'alert', + attributes: { + apiKey: Buffer.from('123:abc').toString('base64'), + }, + references: [], + }); + const runnerResult = await taskRunner.run(); + expect(runnerResult.state.alertInstances).toMatchInlineSnapshot(` Object { "1": Object { "meta": Object { @@ -1526,26 +1536,26 @@ describe('Task Runner', () => { } `); - const logger = customTaskRunnerFactoryInitializerParams.logger; - expect(logger.debug).toHaveBeenCalledTimes(4); - expect(logger.debug).nthCalledWith(1, 'executing alert test:1 at 1970-01-01T00:00:00.000Z'); - expect(logger.debug).nthCalledWith( - 2, - `alert test:1: 'alert-name' has 1 active alert instances: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"}]` - ); - expect(logger.debug).nthCalledWith( - 3, - `alert test:1: 'alert-name' has 1 recovered alert instances: [\"2\"]` - ); - expect(logger.debug).nthCalledWith( - 4, - 'alertExecutionStatus for test:1: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}' - ); - - const eventLogger = customTaskRunnerFactoryInitializerParams.eventLogger; - expect(eventLogger.logEvent).toHaveBeenCalledTimes(6); - expect(eventLogger.startTiming).toHaveBeenCalledTimes(1); - expect(eventLogger.logEvent.mock.calls).toMatchInlineSnapshot(` + const logger = customTaskRunnerFactoryInitializerParams.logger; + expect(logger.debug).toHaveBeenCalledTimes(4); + expect(logger.debug).nthCalledWith(1, 'executing alert test:1 at 1970-01-01T00:00:00.000Z'); + expect(logger.debug).nthCalledWith( + 2, + `alert test:1: 'alert-name' has 1 active alert instances: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"}]` + ); + expect(logger.debug).nthCalledWith( + 3, + `alert test:1: 'alert-name' has 1 recovered alert instances: [\"2\"]` + ); + expect(logger.debug).nthCalledWith( + 4, + 'alertExecutionStatus for test:1: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}' + ); + + const eventLogger = customTaskRunnerFactoryInitializerParams.eventLogger; + expect(eventLogger.logEvent).toHaveBeenCalledTimes(6); + expect(eventLogger.startTiming).toHaveBeenCalledTimes(1); + expect(eventLogger.logEvent.mock.calls).toMatchInlineSnapshot(` Array [ Array [ Object { @@ -1777,8 +1787,8 @@ describe('Task Runner', () => { ] `); - expect(enqueueFunction).toHaveBeenCalledTimes(2); - expect((enqueueFunction as jest.Mock).mock.calls[0]).toMatchInlineSnapshot(` + expect(enqueueFunction).toHaveBeenCalledTimes(2); + expect((enqueueFunction as jest.Mock).mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "apiKey": "MTIzOmFiYw==", @@ -1805,68 +1815,69 @@ describe('Task Runner', () => { }, ] `); - } + } ); testAgainstEphemeralSupport( 'should skip alertInstances which werent active on the previous execution', ( - customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, - enqueueFunction: (options: ExecuteOptions) => Promise - ) => async () => { - const alertId = 'e558aaad-fd81-46d2-96fc-3bd8fc3dc03f'; - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(new Promise(() => {})); - - alertType.executor.mockImplementation( - async ({ - services: executorServices, - }: AlertExecutorOptions< - AlertTypeParams, - AlertTypeState, - AlertInstanceState, - AlertInstanceContext, - string - >) => { - executorServices.alertInstanceFactory('1').scheduleActions('default'); - - // create an instance, but don't schedule any actions, so it doesn't go active - executorServices.alertInstanceFactory('3'); - } - ); - const taskRunner = new TaskRunner( - alertType, - { - ...mockedTaskInstance, - state: { - ...mockedTaskInstance.state, - alertInstances: { - '1': { meta: {}, state: { bar: false } }, - '2': { meta: {}, state: { bar: false } }, + customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, + enqueueFunction: (options: ExecuteOptions) => Promise + ) => + async () => { + const alertId = 'e558aaad-fd81-46d2-96fc-3bd8fc3dc03f'; + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( + true + ); + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( + true + ); + actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(new Promise(() => {})); + + alertType.executor.mockImplementation( + async ({ + services: executorServices, + }: AlertExecutorOptions< + AlertTypeParams, + AlertTypeState, + AlertInstanceState, + AlertInstanceContext, + string + >) => { + executorServices.alertInstanceFactory('1').scheduleActions('default'); + + // create an instance, but don't schedule any actions, so it doesn't go active + executorServices.alertInstanceFactory('3'); + } + ); + const taskRunner = new TaskRunner( + alertType, + { + ...mockedTaskInstance, + state: { + ...mockedTaskInstance.state, + alertInstances: { + '1': { meta: {}, state: { bar: false } }, + '2': { meta: {}, state: { bar: false } }, + }, + }, + params: { + alertId, }, }, - params: { - alertId, + customTaskRunnerFactoryInitializerParams + ); + rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ + id: alertId, + type: 'alert', + attributes: { + apiKey: Buffer.from('123:abc').toString('base64'), }, - }, - customTaskRunnerFactoryInitializerParams - ); - rulesClient.get.mockResolvedValue(mockedAlertTypeSavedObject); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ - id: alertId, - type: 'alert', - attributes: { - apiKey: Buffer.from('123:abc').toString('base64'), - }, - references: [], - }); - const runnerResult = await taskRunner.run(); - expect(runnerResult.state.alertInstances).toMatchInlineSnapshot(` + references: [], + }); + const runnerResult = await taskRunner.run(); + expect(runnerResult.state.alertInstances).toMatchInlineSnapshot(` Object { "1": Object { "meta": Object { @@ -1883,111 +1894,112 @@ describe('Task Runner', () => { } `); - const logger = customTaskRunnerFactoryInitializerParams.logger; - expect(logger.debug).toHaveBeenCalledWith( - `alert test:${alertId}: 'alert-name' has 1 active alert instances: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"}]` - ); - - expect(logger.debug).nthCalledWith( - 3, - `alert test:${alertId}: 'alert-name' has 1 recovered alert instances: [\"2\"]` - ); - expect(logger.debug).nthCalledWith( - 4, - `alertExecutionStatus for test:${alertId}: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}` - ); - - const eventLogger = customTaskRunnerFactoryInitializerParams.eventLogger; - expect(eventLogger.logEvent).toHaveBeenCalledTimes(6); - expect(enqueueFunction).toHaveBeenCalledTimes(2); - expect((enqueueFunction as jest.Mock).mock.calls[1][0].id).toEqual('1'); - expect((enqueueFunction as jest.Mock).mock.calls[0][0].id).toEqual('2'); - } + const logger = customTaskRunnerFactoryInitializerParams.logger; + expect(logger.debug).toHaveBeenCalledWith( + `alert test:${alertId}: 'alert-name' has 1 active alert instances: [{\"instanceId\":\"1\",\"actionGroup\":\"default\"}]` + ); + + expect(logger.debug).nthCalledWith( + 3, + `alert test:${alertId}: 'alert-name' has 1 recovered alert instances: [\"2\"]` + ); + expect(logger.debug).nthCalledWith( + 4, + `alertExecutionStatus for test:${alertId}: {"lastExecutionDate":"1970-01-01T00:00:00.000Z","status":"active"}` + ); + + const eventLogger = customTaskRunnerFactoryInitializerParams.eventLogger; + expect(eventLogger.logEvent).toHaveBeenCalledTimes(6); + expect(enqueueFunction).toHaveBeenCalledTimes(2); + expect((enqueueFunction as jest.Mock).mock.calls[1][0].id).toEqual('1'); + expect((enqueueFunction as jest.Mock).mock.calls[0][0].id).toEqual('2'); + } ); testAgainstEphemeralSupport( 'fire actions under a custom recovery group when specified on an alert type for alertInstances which are in the recovered state', ( - customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, - enqueueFunction: (options: ExecuteOptions) => Promise - ) => async () => { - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( - true - ); - customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( - true - ); - - actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(new Promise(() => {})); - - const recoveryActionGroup = { - id: 'customRecovered', - name: 'Custom Recovered', - }; - const alertTypeWithCustomRecovery = { - ...alertType, - recoveryActionGroup, - actionGroups: [{ id: 'default', name: 'Default' }, recoveryActionGroup], - }; - - alertTypeWithCustomRecovery.executor.mockImplementation( - async ({ - services: executorServices, - }: AlertExecutorOptions< - AlertTypeParams, - AlertTypeState, - AlertInstanceState, - AlertInstanceContext, - string - >) => { - executorServices.alertInstanceFactory('1').scheduleActions('default'); - } - ); - const taskRunner = new TaskRunner( - alertTypeWithCustomRecovery, - { - ...mockedTaskInstance, - state: { - ...mockedTaskInstance.state, - alertInstances: { - '1': { meta: {}, state: { bar: false } }, - '2': { meta: {}, state: { bar: false } }, - }, - }, - }, - customTaskRunnerFactoryInitializerParams - ); - rulesClient.get.mockResolvedValue({ - ...mockedAlertTypeSavedObject, - actions: [ + customTaskRunnerFactoryInitializerParams: TaskRunnerFactoryInitializerParamsType, + enqueueFunction: (options: ExecuteOptions) => Promise + ) => + async () => { + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionTypeEnabled.mockReturnValue( + true + ); + customTaskRunnerFactoryInitializerParams.actionsPlugin.isActionExecutable.mockReturnValue( + true + ); + + actionsClient.ephemeralEnqueuedExecution.mockResolvedValue(new Promise(() => {})); + + const recoveryActionGroup = { + id: 'customRecovered', + name: 'Custom Recovered', + }; + const alertTypeWithCustomRecovery = { + ...alertType, + recoveryActionGroup, + actionGroups: [{ id: 'default', name: 'Default' }, recoveryActionGroup], + }; + + alertTypeWithCustomRecovery.executor.mockImplementation( + async ({ + services: executorServices, + }: AlertExecutorOptions< + AlertTypeParams, + AlertTypeState, + AlertInstanceState, + AlertInstanceContext, + string + >) => { + executorServices.alertInstanceFactory('1').scheduleActions('default'); + } + ); + const taskRunner = new TaskRunner( + alertTypeWithCustomRecovery, { - group: 'default', - id: '1', - actionTypeId: 'action', - params: { - foo: true, + ...mockedTaskInstance, + state: { + ...mockedTaskInstance.state, + alertInstances: { + '1': { meta: {}, state: { bar: false } }, + '2': { meta: {}, state: { bar: false } }, + }, }, }, - { - group: recoveryActionGroup.id, - id: '2', - actionTypeId: 'action', - params: { - isResolved: true, + customTaskRunnerFactoryInitializerParams + ); + rulesClient.get.mockResolvedValue({ + ...mockedAlertTypeSavedObject, + actions: [ + { + group: 'default', + id: '1', + actionTypeId: 'action', + params: { + foo: true, + }, }, + { + group: recoveryActionGroup.id, + id: '2', + actionTypeId: 'action', + params: { + isResolved: true, + }, + }, + ], + }); + encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ + id: '1', + type: 'alert', + attributes: { + apiKey: Buffer.from('123:abc').toString('base64'), }, - ], - }); - encryptedSavedObjectsClient.getDecryptedAsInternalUser.mockResolvedValue({ - id: '1', - type: 'alert', - attributes: { - apiKey: Buffer.from('123:abc').toString('base64'), - }, - references: [], - }); - const runnerResult = await taskRunner.run(); - expect(runnerResult.state.alertInstances).toMatchInlineSnapshot(` + references: [], + }); + const runnerResult = await taskRunner.run(); + expect(runnerResult.state.alertInstances).toMatchInlineSnapshot(` Object { "1": Object { "meta": Object { @@ -2004,10 +2016,10 @@ describe('Task Runner', () => { } `); - const eventLogger = customTaskRunnerFactoryInitializerParams.eventLogger; - expect(eventLogger.logEvent).toHaveBeenCalledTimes(6); - expect(enqueueFunction).toHaveBeenCalledTimes(2); - expect((enqueueFunction as jest.Mock).mock.calls[0]).toMatchInlineSnapshot(` + const eventLogger = customTaskRunnerFactoryInitializerParams.eventLogger; + expect(eventLogger.logEvent).toHaveBeenCalledTimes(6); + expect(enqueueFunction).toHaveBeenCalledTimes(2); + expect((enqueueFunction as jest.Mock).mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { "apiKey": "MTIzOmFiYw==", @@ -2034,7 +2046,7 @@ describe('Task Runner', () => { }, ] `); - } + } ); test('persists alertInstances passed in from state, only if they are scheduled for execution', async () => { 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 6694146c3e2b..28cc0f2dba4d 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner.ts @@ -135,7 +135,7 @@ export class TaskRunner< const path = addSpaceIdToPath('/', spaceId); - const fakeRequest = KibanaRequest.from(({ + const fakeRequest = KibanaRequest.from({ headers: requestHeaders, path: '/', route: { settings: {} }, @@ -147,7 +147,7 @@ export class TaskRunner< url: '/', }, }, - } as unknown) as Request); + } as unknown as Request); this.context.basePathService.set(fakeRequest, path); @@ -384,7 +384,8 @@ export class TaskRunner< string, AlertInstance ]) => { - const shouldExecuteAction = alertInstance.scheduledActionGroupOrSubgroupHasChanged(); + const shouldExecuteAction = + alertInstance.scheduledActionGroupOrSubgroupHasChanged(); if (!shouldExecuteAction) { this.logger.debug( `skipping scheduling of actions for '${alertInstanceName}' in alert ${alertLabel}: instance is active but action group has not changed` diff --git a/x-pack/plugins/alerting/server/usage/alerts_usage_collector.test.ts b/x-pack/plugins/alerting/server/usage/alerts_usage_collector.test.ts index fcc10d6f0c54..9539f189c4fd 100644 --- a/x-pack/plugins/alerting/server/usage/alerts_usage_collector.test.ts +++ b/x-pack/plugins/alerting/server/usage/alerts_usage_collector.test.ts @@ -16,10 +16,10 @@ describe('registerAlertsUsageCollector', () => { let usageCollectionMock: jest.Mocked; beforeEach(() => { - usageCollectionMock = ({ + usageCollectionMock = { makeUsageCollector: jest.fn(), registerCollector: jest.fn(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; }); it('should call registerCollector', () => { 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 9daf0d50be83..bfc1d9b26f8f 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 @@ -36,9 +36,8 @@ export function getDurationRt({ min, max }: { min?: string; max?: string }) { return either.chain( t.string.validate(input, context), (inputAsString) => { - const inputAsMilliseconds = amountAndUnitToMilliseconds( - inputAsString - ); + const inputAsMilliseconds = + amountAndUnitToMilliseconds(inputAsString); const isValidAmount = inputAsMilliseconds !== undefined && diff --git a/x-pack/plugins/apm/common/apm_telemetry.ts b/x-pack/plugins/apm/common/apm_telemetry.ts index e633834415b3..562dccdfbef2 100644 --- a/x-pack/plugins/apm/common/apm_telemetry.ts +++ b/x-pack/plugins/apm/common/apm_telemetry.ts @@ -49,7 +49,8 @@ export function mergeApmTelemetryMapping( xpackPhoneHomeMapping: Record ) { return produce(xpackPhoneHomeMapping, (draft: Record) => { - draft.mappings.properties.stack_stats.properties.kibana.properties.plugins.properties.apm = getApmTelemetryMapping(); + draft.mappings.properties.stack_stats.properties.kibana.properties.plugins.properties.apm = + getApmTelemetryMapping(); return draft; }); } diff --git a/x-pack/plugins/apm/common/search_strategies/constants.ts b/x-pack/plugins/apm/common/search_strategies/constants.ts index b1bd321e1c91..58203c93e5a4 100644 --- a/x-pack/plugins/apm/common/search_strategies/constants.ts +++ b/x-pack/plugins/apm/common/search_strategies/constants.ts @@ -9,6 +9,7 @@ export const APM_SEARCH_STRATEGIES = { APM_FAILED_TRANSACTIONS_CORRELATIONS: 'apmFailedTransactionsCorrelations', APM_LATENCY_CORRELATIONS: 'apmLatencyCorrelations', } as const; -export type ApmSearchStrategies = typeof APM_SEARCH_STRATEGIES[keyof typeof APM_SEARCH_STRATEGIES]; +export type ApmSearchStrategies = + typeof APM_SEARCH_STRATEGIES[keyof typeof APM_SEARCH_STRATEGIES]; export const DEFAULT_PERCENTILE_THRESHOLD = 95; diff --git a/x-pack/plugins/apm/common/search_strategies/failed_transactions_correlations/types.ts b/x-pack/plugins/apm/common/search_strategies/failed_transactions_correlations/types.ts index de4c5c396961..857e1e9dbe95 100644 --- a/x-pack/plugins/apm/common/search_strategies/failed_transactions_correlations/types.ts +++ b/x-pack/plugins/apm/common/search_strategies/failed_transactions_correlations/types.ts @@ -25,14 +25,15 @@ export interface FailedTransactionsCorrelation extends FieldValuePair { histogram: HistogramItem[]; } -export type FailedTransactionsCorrelationsImpactThreshold = typeof FAILED_TRANSACTIONS_IMPACT_THRESHOLD[keyof typeof FAILED_TRANSACTIONS_IMPACT_THRESHOLD]; +export type FailedTransactionsCorrelationsImpactThreshold = + typeof FAILED_TRANSACTIONS_IMPACT_THRESHOLD[keyof typeof FAILED_TRANSACTIONS_IMPACT_THRESHOLD]; export interface FailedTransactionsCorrelationsParams { percentileThreshold: number; } -export type FailedTransactionsCorrelationsRequestParams = FailedTransactionsCorrelationsParams & - SearchStrategyClientParams; +export type FailedTransactionsCorrelationsRequestParams = + FailedTransactionsCorrelationsParams & SearchStrategyClientParams; export interface FailedTransactionsCorrelationsRawResponse extends RawResponseBase { diff --git a/x-pack/plugins/apm/common/utils/join_by_key/index.ts b/x-pack/plugins/apm/common/utils/join_by_key/index.ts index 7a332cd22bc8..b6da95039815 100644 --- a/x-pack/plugins/apm/common/utils/join_by_key/index.ts +++ b/x-pack/plugins/apm/common/utils/join_by_key/index.ts @@ -28,10 +28,9 @@ type JoinedReturnType< T extends Record, U extends UnionToIntersection > = Array< - Partial & - { - [k in keyof T]: T[k]; - } + Partial & { + [k in keyof T]: T[k]; + } >; type ArrayOrSingle = T | T[]; diff --git a/x-pack/plugins/apm/public/application/application.test.tsx b/x-pack/plugins/apm/public/application/application.test.tsx index 144da47828bf..5f66e90e9129 100644 --- a/x-pack/plugins/apm/public/application/application.test.tsx +++ b/x-pack/plugins/apm/public/application/application.test.tsx @@ -41,11 +41,8 @@ describe('renderApp', () => { }); it('renders the app', () => { - const { - core, - config, - observabilityRuleTypeRegistry, - } = mockApmPluginContextValue; + const { core, config, observabilityRuleTypeRegistry } = + mockApmPluginContextValue; const plugins = { licensing: { license$: new Observable() }, @@ -67,7 +64,7 @@ describe('renderApp', () => { const data = dataPluginMock.createStartContract(); const embeddable = embeddablePluginMock.createStartContract(); - const pluginsStart = ({ + const pluginsStart = { data, embeddable, observability: { @@ -91,18 +88,18 @@ describe('renderApp', () => { get: () => `/basepath`, }, } as HttpStart, - docLinks: ({ + docLinks: { DOC_LINK_VERSION: '0', ELASTIC_WEBSITE_URL: 'https://www.elastic.co/', links: { apm: {}, observability: { guide: '' }, }, - } as unknown) as DocLinksStart, - } as unknown) as ApmPluginStartDeps; + } as unknown as DocLinksStart, + } as unknown as ApmPluginStartDeps; jest.spyOn(window, 'scrollTo').mockReturnValueOnce(undefined); - createCallApmApi((core as unknown) as CoreStart); + createCallApmApi(core as unknown as CoreStart); jest .spyOn(window.console, 'warn') diff --git a/x-pack/plugins/apm/public/components/alerting/alerting_flyout/index.tsx b/x-pack/plugins/apm/public/components/alerting/alerting_flyout/index.tsx index fa56c44d8d37..36f96f901f1f 100644 --- a/x-pack/plugins/apm/public/components/alerting/alerting_flyout/index.tsx +++ b/x-pack/plugins/apm/public/components/alerting/alerting_flyout/index.tsx @@ -44,9 +44,10 @@ export function AlertingFlyout(props: Props) { const { services } = useKibana(); const initialValues = getInitialAlertValues(alertType, serviceName); - const onCloseAddFlyout = useCallback(() => setAddFlyoutVisibility(false), [ - setAddFlyoutVisibility, - ]); + const onCloseAddFlyout = useCallback( + () => setAddFlyoutVisibility(false), + [setAddFlyoutVisibility] + ); const addAlertFlyout = useMemo( () => diff --git a/x-pack/plugins/apm/public/components/alerting/error_count_alert_trigger/index.stories.tsx b/x-pack/plugins/apm/public/components/alerting/error_count_alert_trigger/index.stories.tsx index 0f7e3340eaee..b6ee1a61cea5 100644 --- a/x-pack/plugins/apm/public/components/alerting/error_count_alert_trigger/index.stories.tsx +++ b/x-pack/plugins/apm/public/components/alerting/error_count_alert_trigger/index.stories.tsx @@ -10,9 +10,9 @@ import { AlertParams, ErrorCountAlertTrigger } from '.'; import { CoreStart } from '../../../../../../../src/core/public'; import { createKibanaReactContext } from '../../../../../../../src/plugins/kibana_react/public'; -const KibanaReactContext = createKibanaReactContext(({ +const KibanaReactContext = createKibanaReactContext({ notifications: { toasts: { add: () => {} } }, -} as unknown) as Partial); +} as unknown as Partial); export default { title: 'alerting/ErrorCountAlertTrigger', diff --git a/x-pack/plugins/apm/public/components/alerting/get_alerting_capabilities.test.ts b/x-pack/plugins/apm/public/components/alerting/get_alerting_capabilities.test.ts index 3477b7de843d..7fabd1c1ff87 100644 --- a/x-pack/plugins/apm/public/components/alerting/get_alerting_capabilities.test.ts +++ b/x-pack/plugins/apm/public/components/alerting/get_alerting_capabilities.test.ts @@ -15,7 +15,7 @@ describe('getAlertingCapabilities', () => { expect( getAlertingCapabilities( {} as ApmPluginSetupDeps, - ({ apm: {} } as unknown) as Capabilities + { apm: {} } as unknown as Capabilities ).isAlertingAvailable ).toEqual(false); }); diff --git a/x-pack/plugins/apm/public/components/alerting/register_apm_alerts.ts b/x-pack/plugins/apm/public/components/alerting/register_apm_alerts.ts index 4fc2dcefc9c5..3d444c1cf7a3 100644 --- a/x-pack/plugins/apm/public/components/alerting/register_apm_alerts.ts +++ b/x-pack/plugins/apm/public/components/alerting/register_apm_alerts.ts @@ -34,8 +34,10 @@ const SERVICE_ENVIRONMENT = 'service.environment'; const SERVICE_NAME = 'service.name'; const TRANSACTION_TYPE = 'transaction.type'; -const ALERT_EVALUATION_THRESHOLD: typeof ALERT_EVALUATION_THRESHOLD_TYPED = ALERT_EVALUATION_THRESHOLD_NON_TYPED; -const ALERT_EVALUATION_VALUE: typeof ALERT_EVALUATION_VALUE_TYPED = ALERT_EVALUATION_VALUE_NON_TYPED; +const ALERT_EVALUATION_THRESHOLD: typeof ALERT_EVALUATION_THRESHOLD_TYPED = + ALERT_EVALUATION_THRESHOLD_NON_TYPED; +const ALERT_EVALUATION_VALUE: typeof ALERT_EVALUATION_VALUE_TYPED = + ALERT_EVALUATION_VALUE_NON_TYPED; const ALERT_SEVERITY: typeof ALERT_SEVERITY_TYPED = ALERT_SEVERITY_NON_TYPED; const format = ({ diff --git a/x-pack/plugins/apm/public/components/alerting/transaction_duration_alert_trigger/index.stories.tsx b/x-pack/plugins/apm/public/components/alerting/transaction_duration_alert_trigger/index.stories.tsx index 8eb0be8eb4b3..3570630d35ee 100644 --- a/x-pack/plugins/apm/public/components/alerting/transaction_duration_alert_trigger/index.stories.tsx +++ b/x-pack/plugins/apm/public/components/alerting/transaction_duration_alert_trigger/index.stories.tsx @@ -11,9 +11,9 @@ import { AlertParams, TransactionDurationAlertTrigger } from '.'; import { CoreStart } from '../../../../../../../src/core/public'; import { createKibanaReactContext } from '../../../../../../../src/plugins/kibana_react/public'; -const KibanaReactContext = createKibanaReactContext(({ +const KibanaReactContext = createKibanaReactContext({ notifications: { toasts: { add: () => {} } }, -} as unknown) as Partial); +} as unknown as Partial); export default { title: 'alerting/TransactionDurationAlertTrigger', diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/ActionMenu/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/ActionMenu/index.tsx index 4e6544a20f30..a3c85b866ed6 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/ActionMenu/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/ActionMenu/index.tsx @@ -42,11 +42,11 @@ export function UXActionMenu({ const uxExploratoryViewLink = createExploratoryViewUrl( { - 'ux-series': ({ + 'ux-series': { dataType: 'ux', isNew: true, time: { from: rangeFrom, to: rangeTo }, - } as unknown) as SeriesUrl, + } as unknown as SeriesUrl, }, http?.basePath.get() ); diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/RumHome.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/RumHome.tsx index 0371f7eb669e..505fd5c1020b 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/RumHome.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/RumHome.tsx @@ -33,29 +33,30 @@ export function RumHome() { const envStyle = isSmall ? {} : { maxWidth: 500 }; - const noDataConfig: KibanaPageTemplateProps['noDataConfig'] = !rumHasData?.hasData - ? { - solution: i18n.translate('xpack.apm.ux.overview.solutionName', { - defaultMessage: 'Observability', - }), - actions: { - beats: { - title: i18n.translate('xpack.apm.ux.overview.beatsCard.title', { - defaultMessage: 'Add RUM data', - }), - description: i18n.translate( - 'xpack.apm.ux.overview.beatsCard.description', - { - defaultMessage: - 'Use the RUM (JS) agent to collect user experience data.', - } - ), - href: core.http.basePath.prepend(`/app/home#/tutorial/apm`), + const noDataConfig: KibanaPageTemplateProps['noDataConfig'] = + !rumHasData?.hasData + ? { + solution: i18n.translate('xpack.apm.ux.overview.solutionName', { + defaultMessage: 'Observability', + }), + actions: { + beats: { + title: i18n.translate('xpack.apm.ux.overview.beatsCard.title', { + defaultMessage: 'Add RUM data', + }), + description: i18n.translate( + 'xpack.apm.ux.overview.beatsCard.description', + { + defaultMessage: + 'Use the RUM (JS) agent to collect user experience data.', + } + ), + href: core.http.basePath.prepend(`/app/home#/tutorial/apm`), + }, }, - }, - docsLink: core.docLinks.links.observability.guide, - } - : undefined; + docsLink: core.docLinks.links.observability.guide, + } + : undefined; return ( diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/SelectableUrlList.test.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/SelectableUrlList.test.tsx index 330cb56b2bbb..f4f7a179c813 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/SelectableUrlList.test.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/SelectableUrlList.test.tsx @@ -90,11 +90,10 @@ describe('SelectableUrlList', () => { }); it('hides popover on escape', async () => { - const { - getByText, - getByLabelText, - queryByText, - } = render(, { customHistory }); + const { getByText, getByLabelText, queryByText } = render( + , + { customHistory } + ); const input = getByLabelText(I18LABELS.filterByUrl); fireEvent.click(input); diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/index.tsx index 4f35cb96dada..efecf02d25e8 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/index.tsx @@ -61,11 +61,8 @@ export function URLSearch({ }: Props) { const { uxUiFilters, urlParams } = useUrlParams(); - const { - transactionUrl, - transactionUrlExcluded, - ...restFilters - } = uxUiFilters; + const { transactionUrl, transactionUrlExcluded, ...restFilters } = + uxUiFilters; const { searchTerm, percentile } = urlParams; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/EmbeddedMap.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/EmbeddedMap.tsx index 1ba1685ca17a..b468b5c91338 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/EmbeddedMap.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/EmbeddedMap.tsx @@ -63,9 +63,8 @@ export function EmbeddedMapComponent() { MapEmbeddable | ErrorEmbeddable | undefined >(); - const embeddableRoot: React.RefObject = useRef( - null - ); + const embeddableRoot: React.RefObject = + useRef(null); const { services: { embeddable: embeddablePlugin }, diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/__mocks__/regions_layer.mock.ts b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/__mocks__/regions_layer.mock.ts index 94de1c088562..52bd024d8116 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/__mocks__/regions_layer.mock.ts +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/__mocks__/regions_layer.mock.ts @@ -51,8 +51,7 @@ export const mockLayerList = [ fieldMetaOptions: { isEnabled: true, sigma: 3 }, type: 'ORDINAL', field: { - name: - '__kbnjoin__avg_of_transaction.duration.us__3657625d-17b0-41ef-99ba-3a2b2938655c', + name: '__kbnjoin__avg_of_transaction.duration.us__3657625d-17b0-41ef-99ba-3a2b2938655c', origin: 'join', }, useCustomColorRamp: false, @@ -121,8 +120,7 @@ export const mockLayerList = [ fieldMetaOptions: { isEnabled: true, sigma: 3 }, type: 'ORDINAL', field: { - name: - '__kbnjoin__avg_of_transaction.duration.us__e62a1b9c-d7ff-4fd4-a0f6-0fdc44bb9e41', + name: '__kbnjoin__avg_of_transaction.duration.us__e62a1b9c-d7ff-4fd4-a0f6-0fdc44bb9e41', origin: 'join', }, useCustomColorRamp: false, diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/utils/test_helper.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/utils/test_helper.tsx index 42ea3894ea67..d8438de4a7e1 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/utils/test_helper.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/utils/test_helper.tsx @@ -16,7 +16,7 @@ import { EuiThemeProvider } from '../../../../../../../../src/plugins/kibana_rea import { KibanaContextProvider } from '../../../../../../../../src/plugins/kibana_react/public'; import { UrlParamsProvider } from '../../../../context/url_params_context/url_params_context'; -export const core = ({ +export const core = { http: { basePath: { prepend: jest.fn(), @@ -26,7 +26,7 @@ export const core = ({ get: (key: string) => true, get$: (key: string) => of(true), }, -} as unknown) as CoreStart; +} as unknown as CoreStart; export const render = ( component: React.ReactNode, diff --git a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/index.stories.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/index.stories.tsx index 02ecf902f00a..a779be24b293 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/index.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/index.stories.tsx @@ -22,7 +22,7 @@ storiesOf( module ) .addDecorator((storyFn) => { - const coreMock = ({} as unknown) as CoreStart; + const coreMock = {} as unknown as CoreStart; // mock createCallApmApi(coreMock); @@ -37,7 +37,7 @@ storiesOf( return ( {storyFn()} diff --git a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/ConfirmDeleteModal.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/ConfirmDeleteModal.tsx index 3e3bc892e651..66be766437de 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/ConfirmDeleteModal.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/ConfirmDeleteModal.tsx @@ -16,7 +16,8 @@ import { } from '../../../../../services/rest/createCallApmApi'; import { useApmPluginContext } from '../../../../../context/apm_plugin/use_apm_plugin_context'; -type Config = APIReturnType<'GET /api/apm/settings/agent-configuration'>['configurations'][0]; +type Config = + APIReturnType<'GET /api/apm/settings/agent-configuration'>['configurations'][0]; interface Props { config: Config; diff --git a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/index.tsx index 3ab5c25ed3dc..4804e52b16d4 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/index.tsx @@ -28,7 +28,8 @@ import { ITableColumn, ManagedTable } from '../../../../shared/managed_table'; import { TimestampTooltip } from '../../../../shared/TimestampTooltip'; import { ConfirmDeleteModal } from './ConfirmDeleteModal'; -type Config = APIReturnType<'GET /api/apm/settings/agent-configuration'>['configurations'][0]; +type Config = + APIReturnType<'GET /api/apm/settings/agent-configuration'>['configurations'][0]; interface Props { status: FETCH_STATUS; diff --git a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/index.tsx index f7cfc56bf4ea..f443e9e016cb 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/index.tsx @@ -25,7 +25,11 @@ import { AgentConfigurationList } from './List'; const INITIAL_DATA = { configurations: [] }; export function AgentConfigurations() { - const { refetch, data = INITIAL_DATA, status } = useFetcher( + const { + refetch, + data = INITIAL_DATA, + status, + } = useFetcher( (callApmApi) => callApmApi({ endpoint: 'GET /api/apm/settings/agent-configuration' }), [], diff --git a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/add_environments.tsx b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/add_environments.tsx index 89e5dfcbdadf..a60e685eacbd 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/add_environments.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/add_environments.tsx @@ -34,7 +34,8 @@ interface Props { onCancel: () => void; } -type ApiResponse = APIReturnType<'GET /api/apm/settings/anomaly-detection/environments'>; +type ApiResponse = + APIReturnType<'GET /api/apm/settings/anomaly-detection/environments'>; const INITIAL_DATA: ApiResponse = { environments: [] }; export function AddEnvironments({ diff --git a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/index.tsx index 7293fb81f330..0fe7f9360de0 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/index.tsx @@ -16,7 +16,8 @@ import { LicensePrompt } from '../../../shared/license_prompt'; import { useLicenseContext } from '../../../../context/license/use_license_context'; import { APIReturnType } from '../../../../services/rest/createCallApmApi'; -export type AnomalyDetectionApiResponse = APIReturnType<'GET /api/apm/settings/anomaly-detection/jobs'>; +export type AnomalyDetectionApiResponse = + APIReturnType<'GET /api/apm/settings/anomaly-detection/jobs'>; const DEFAULT_VALUE: AnomalyDetectionApiResponse = { jobs: [], @@ -31,7 +32,11 @@ export function AnomalyDetection() { const [viewAddEnvironments, setViewAddEnvironments] = useState(false); - const { refetch, data = DEFAULT_VALUE, status } = useFetcher( + const { + refetch, + data = DEFAULT_VALUE, + status, + } = useFetcher( (callApmApi) => { if (canGetJobs) { return callApmApi({ diff --git a/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/helper.test.ts b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/helper.test.ts index 449968b82943..e1a18784559f 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/helper.test.ts +++ b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/helper.test.ts @@ -84,10 +84,10 @@ describe('Custom link helper', () => { }); describe('replaceTemplateVariables', () => { - const transaction = ({ + const transaction = { service: { name: 'foo' }, trace: { id: '123' }, - } as unknown) as Transaction; + } as unknown as Transaction; it('replaces template variables', () => { expect( @@ -115,7 +115,7 @@ describe('Custom link helper', () => { expect( replaceTemplateVariables( 'https://elastic.co?service.name={{service.name}}&trace.id={{trace.id}}', - ({} as unknown) as Transaction + {} as unknown as Transaction ) ).toEqual(expectedResult); }); diff --git a/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/link_preview.stories.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/link_preview.stories.tsx index 3bf17a733bf8..cbab496a188f 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/link_preview.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/link_preview.stories.tsx @@ -21,12 +21,12 @@ export function Example({ label, url, }: ComponentProps) { - const coreMock = ({ + const coreMock = { http: { get: async () => ({ transaction: { id: '0' } }), }, uiSettings: { get: () => false }, - } as unknown) as CoreStart; + } as unknown as CoreStart; createCallApmApi(coreMock); diff --git a/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/link_preview.test.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/link_preview.test.tsx index d88cef0702a8..f44b4d1c1205 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/link_preview.test.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/link_preview.test.tsx @@ -24,8 +24,10 @@ export const removeExternalLinkText = (str: string) => describe('LinkPreview', () => { const getElementValue = (container: HTMLElement, id: string) => getNodeText( - ((getByTestId(container, id) as HTMLDivElement) - .children as HTMLCollection)[0] as HTMLDivElement + ( + (getByTestId(container, id) as HTMLDivElement) + .children as HTMLCollection + )[0] as HTMLDivElement ); it('shows label and url default values', () => { diff --git a/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/index.test.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/index.test.tsx index 22fbfb04734b..c2860c1b6977 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/index.test.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/index.test.tsx @@ -32,13 +32,13 @@ const data = { }; function getMockAPMContext({ canSave }: { canSave: boolean }) { - return ({ + return { ...mockApmPluginContextValue, core: { ...mockApmPluginContextValue.core, application: { capabilities: { apm: { save: canSave }, ml: {} } }, }, - } as unknown) as ApmPluginContextValue; + } as unknown as ApmPluginContextValue; } describe('CustomLink', () => { diff --git a/x-pack/plugins/apm/public/components/app/Settings/schema/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/schema/index.tsx index 0c95648a1cef..6b7538e61c13 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/schema/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/schema/index.tsx @@ -19,7 +19,8 @@ import { } from '../../../../services/rest/createCallApmApi'; import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context'; -type FleetMigrationCheckResponse = APIReturnType<'GET /api/apm/fleet/migration_check'>; +type FleetMigrationCheckResponse = + APIReturnType<'GET /api/apm/fleet/migration_check'>; const APM_DATA_STREAMS_MIGRATION_STATUS_LS = { value: '', @@ -27,13 +28,11 @@ const APM_DATA_STREAMS_MIGRATION_STATUS_LS = { }; export function Schema() { - const [ - apmDataStreamsMigrationStatus, - setApmDataStreamsMigrationStatus, - ] = useLocalStorage( - 'apm.dataStreamsMigrationStatus', - APM_DATA_STREAMS_MIGRATION_STATUS_LS - ); + const [apmDataStreamsMigrationStatus, setApmDataStreamsMigrationStatus] = + useLocalStorage( + 'apm.dataStreamsMigrationStatus', + APM_DATA_STREAMS_MIGRATION_STATUS_LS + ); const { toasts } = useApmPluginContext().core.notifications; const [isSwitchActive, setIsSwitchActive] = useState(false); diff --git a/x-pack/plugins/apm/public/components/app/Settings/schema/schema.stories.tsx b/x-pack/plugins/apm/public/components/app/Settings/schema/schema.stories.tsx index 67eae5376a74..f546eed14bf9 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/schema/schema.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/schema/schema.stories.tsx @@ -77,7 +77,7 @@ export default { } else { window.localStorage.removeItem('apm.dataStreamsMigrationStatus'); } - const coreMock = ({ + const coreMock = { http: { basePath: { prepend: () => {} }, get: () => { @@ -90,7 +90,7 @@ export default { }, }, uiSettings: { get: () => '' }, - } as unknown) as CoreStart; + } as unknown as CoreStart; createCallApmApi(coreMock); diff --git a/x-pack/plugins/apm/public/components/app/TraceLink/get_redirect_to_transaction_detail_page_url.test.ts b/x-pack/plugins/apm/public/components/app/TraceLink/get_redirect_to_transaction_detail_page_url.test.ts index 08d216971b5b..21b2f487fba9 100644 --- a/x-pack/plugins/apm/public/components/app/TraceLink/get_redirect_to_transaction_detail_page_url.test.ts +++ b/x-pack/plugins/apm/public/components/app/TraceLink/get_redirect_to_transaction_detail_page_url.test.ts @@ -9,7 +9,7 @@ import { getRedirectToTransactionDetailPageUrl } from './get_redirect_to_transac import { parse } from 'url'; describe('getRedirectToTransactionDetailPageUrl', () => { - const transaction = ({ + const transaction = { '@timestamp': '2020-01-01T00:01:00.000Z', service: { name: 'opbeans-node' }, trace: { id: 'trace_id' }, @@ -19,7 +19,7 @@ describe('getRedirectToTransactionDetailPageUrl', () => { type: 'request', duration: { us: 5000 }, }, - } as unknown) as any; + } as unknown as any; const url = getRedirectToTransactionDetailPageUrl({ transaction }); diff --git a/x-pack/plugins/apm/public/components/app/TraceLink/trace_link.test.tsx b/x-pack/plugins/apm/public/components/app/TraceLink/trace_link.test.tsx index db08e4f9f02c..ffeab11e1f27 100644 --- a/x-pack/plugins/apm/public/components/app/TraceLink/trace_link.test.tsx +++ b/x-pack/plugins/apm/public/components/app/TraceLink/trace_link.test.tsx @@ -23,13 +23,13 @@ function Wrapper({ children }: { children?: ReactNode }) { {children} diff --git a/x-pack/plugins/apm/public/components/app/correlations/failed_transactions_correlations.tsx b/x-pack/plugins/apm/public/components/app/correlations/failed_transactions_correlations.tsx index 2c911c9aa962..c497ce434180 100644 --- a/x-pack/plugins/apm/public/components/app/correlations/failed_transactions_correlations.tsx +++ b/x-pack/plugins/apm/public/components/app/correlations/failed_transactions_correlations.tsx @@ -84,10 +84,8 @@ export function FailedTransactionsCorrelations({ progress.isRunning ); - const [ - selectedSignificantTerm, - setSelectedSignificantTerm, - ] = useState(null); + const [selectedSignificantTerm, setSelectedSignificantTerm] = + useState(null); const selectedTerm = selectedSignificantTerm ?? response.failedTransactionsCorrelations?.[0]; @@ -334,9 +332,8 @@ export function FailedTransactionsCorrelations({ } }, [progress.error, notifications.toasts]); - const [sortField, setSortField] = useState< - keyof FailedTransactionsCorrelation - >('normalizedScore'); + const [sortField, setSortField] = + useState('normalizedScore'); const [sortDirection, setSortDirection] = useState('desc'); const onTableChange = useCallback(({ sort }) => { @@ -373,7 +370,8 @@ export function FailedTransactionsCorrelations({ const showSummaryBadge = inspectEnabled && (progress.isRunning || correlationTerms.length > 0); - const transactionDistributionChartData: TransactionDistributionChartData[] = []; + const transactionDistributionChartData: TransactionDistributionChartData[] = + []; if (Array.isArray(overallHistogram)) { transactionDistributionChartData.push({ diff --git a/x-pack/plugins/apm/public/components/app/correlations/latency_correlations.test.tsx b/x-pack/plugins/apm/public/components/app/correlations/latency_correlations.test.tsx index c1fb1beb1918..523d8b1840fc 100644 --- a/x-pack/plugins/apm/public/components/app/correlations/latency_correlations.test.tsx +++ b/x-pack/plugins/apm/public/components/app/correlations/latency_correlations.test.tsx @@ -61,9 +61,9 @@ function Wrapper({ search: fromQuery({ transactionName: 'the-transaction-name' }), }); - const mockPluginContext = (merge({}, mockApmPluginContextValue, { + const mockPluginContext = merge({}, mockApmPluginContextValue, { core: { http: { get: httpGet } }, - }) as unknown) as ApmPluginContextValue; + }) as unknown as ApmPluginContextValue; return ( diff --git a/x-pack/plugins/apm/public/components/app/correlations/latency_correlations.tsx b/x-pack/plugins/apm/public/components/app/correlations/latency_correlations.tsx index 44a1122298d5..167df0fd10b4 100644 --- a/x-pack/plugins/apm/public/components/app/correlations/latency_correlations.tsx +++ b/x-pack/plugins/apm/public/components/app/correlations/latency_correlations.tsx @@ -88,10 +88,8 @@ export function LatencyCorrelations({ onFilter }: { onFilter: () => void }) { } }, [progress.error, notifications.toasts]); - const [ - selectedSignificantTerm, - setSelectedSignificantTerm, - ] = useState(null); + const [selectedSignificantTerm, setSelectedSignificantTerm] = + useState(null); const selectedHistogram = useMemo( () => @@ -106,119 +104,117 @@ export function LatencyCorrelations({ onFilter }: { onFilter: () => void }) { const history = useHistory(); const trackApmEvent = useUiTracker({ app: 'apm' }); - const mlCorrelationColumns: Array< - EuiBasicTableColumn - > = useMemo( - () => [ - { - width: '116px', - field: 'correlation', - name: ( - - <> - {i18n.translate( - 'xpack.apm.correlations.latencyCorrelations.correlationsTable.correlationLabel', + const mlCorrelationColumns: Array> = + useMemo( + () => [ + { + width: '116px', + field: 'correlation', + name: ( + - - - ), - render: (_, { correlation }) => { - return
{asPreciseDecimal(correlation, 2)}
; + > + <> + {i18n.translate( + 'xpack.apm.correlations.latencyCorrelations.correlationsTable.correlationLabel', + { + defaultMessage: 'Correlation', + } + )} + + +
+ ), + render: (_, { correlation }) => { + return
{asPreciseDecimal(correlation, 2)}
; + }, + sortable: true, }, - sortable: true, - }, - { - field: 'fieldName', - name: i18n.translate( - 'xpack.apm.correlations.latencyCorrelations.correlationsTable.fieldNameLabel', - { defaultMessage: 'Field name' } - ), - sortable: true, - }, - { - field: 'fieldValue', - name: i18n.translate( - 'xpack.apm.correlations.latencyCorrelations.correlationsTable.fieldValueLabel', - { defaultMessage: 'Field value' } - ), - render: (_, { fieldValue }) => String(fieldValue).slice(0, 50), - sortable: true, - }, - { - width: '100px', - actions: [ - { - name: i18n.translate( - 'xpack.apm.correlations.latencyCorrelations.correlationsTable.filterLabel', - { defaultMessage: 'Filter' } - ), - description: i18n.translate( - 'xpack.apm.correlations.latencyCorrelations.correlationsTable.filterDescription', - { defaultMessage: 'Filter by value' } - ), - icon: 'plusInCircle', - type: 'icon', - onClick: (term: LatencyCorrelation) => { - push(history, { - query: { - kuery: `${term.fieldName}:"${term.fieldValue}"`, - }, - }); - onFilter(); - trackApmEvent({ metric: 'correlations_term_include_filter' }); + { + field: 'fieldName', + name: i18n.translate( + 'xpack.apm.correlations.latencyCorrelations.correlationsTable.fieldNameLabel', + { defaultMessage: 'Field name' } + ), + sortable: true, + }, + { + field: 'fieldValue', + name: i18n.translate( + 'xpack.apm.correlations.latencyCorrelations.correlationsTable.fieldValueLabel', + { defaultMessage: 'Field value' } + ), + render: (_, { fieldValue }) => String(fieldValue).slice(0, 50), + sortable: true, + }, + { + width: '100px', + actions: [ + { + name: i18n.translate( + 'xpack.apm.correlations.latencyCorrelations.correlationsTable.filterLabel', + { defaultMessage: 'Filter' } + ), + description: i18n.translate( + 'xpack.apm.correlations.latencyCorrelations.correlationsTable.filterDescription', + { defaultMessage: 'Filter by value' } + ), + icon: 'plusInCircle', + type: 'icon', + onClick: (term: LatencyCorrelation) => { + push(history, { + query: { + kuery: `${term.fieldName}:"${term.fieldValue}"`, + }, + }); + onFilter(); + trackApmEvent({ metric: 'correlations_term_include_filter' }); + }, }, - }, - { - name: i18n.translate( - 'xpack.apm.correlations.latencyCorrelations.correlationsTable.excludeLabel', - { defaultMessage: 'Exclude' } - ), - description: i18n.translate( - 'xpack.apm.correlations.latencyCorrelations.correlationsTable.excludeDescription', - { defaultMessage: 'Filter out value' } - ), - icon: 'minusInCircle', - type: 'icon', - onClick: (term: LatencyCorrelation) => { - push(history, { - query: { - kuery: `not ${term.fieldName}:"${term.fieldValue}"`, - }, - }); - onFilter(); - trackApmEvent({ metric: 'correlations_term_exclude_filter' }); + { + name: i18n.translate( + 'xpack.apm.correlations.latencyCorrelations.correlationsTable.excludeLabel', + { defaultMessage: 'Exclude' } + ), + description: i18n.translate( + 'xpack.apm.correlations.latencyCorrelations.correlationsTable.excludeDescription', + { defaultMessage: 'Filter out value' } + ), + icon: 'minusInCircle', + type: 'icon', + onClick: (term: LatencyCorrelation) => { + push(history, { + query: { + kuery: `not ${term.fieldName}:"${term.fieldValue}"`, + }, + }); + onFilter(); + trackApmEvent({ metric: 'correlations_term_exclude_filter' }); + }, }, - }, - ], - name: i18n.translate( - 'xpack.apm.correlations.latencyCorrelations.correlationsTable.actionsLabel', - { defaultMessage: 'Filter' } - ), - }, - ], - [history, onFilter, trackApmEvent] - ); + ], + name: i18n.translate( + 'xpack.apm.correlations.latencyCorrelations.correlationsTable.actionsLabel', + { defaultMessage: 'Filter' } + ), + }, + ], + [history, onFilter, trackApmEvent] + ); - const [sortField, setSortField] = useState( - 'correlation' - ); + const [sortField, setSortField] = + useState('correlation'); const [sortDirection, setSortDirection] = useState('desc'); const onTableChange = useCallback(({ sort }) => { @@ -242,7 +238,8 @@ export function LatencyCorrelations({ onFilter }: { onFilter: () => void }) { histogramTerms.length < 1 && (progressNormalized === 1 || !progress.isRunning); - const transactionDistributionChartData: TransactionDistributionChartData[] = []; + const transactionDistributionChartData: TransactionDistributionChartData[] = + []; if (Array.isArray(overallHistogram)) { transactionDistributionChartData.push({ diff --git a/x-pack/plugins/apm/public/components/app/error_group_details/Distribution/index.stories.tsx b/x-pack/plugins/apm/public/components/app/error_group_details/Distribution/index.stories.tsx index d434a155c9cf..4601f1db0277 100644 --- a/x-pack/plugins/apm/public/components/app/error_group_details/Distribution/index.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/error_group_details/Distribution/index.stories.tsx @@ -18,9 +18,9 @@ export default { component: ErrorDistribution, decorators: [ (Story: ComponentType) => { - const apmPluginContextMock = ({ + const apmPluginContextMock = { observabilityRuleTypeRegistry: { getFormatter: () => undefined }, - } as unknown) as ApmPluginContextValue; + } as unknown as ApmPluginContextValue; const kibanaContextServices = { uiSettings: { get: () => {} }, diff --git a/x-pack/plugins/apm/public/components/app/error_group_details/Distribution/index.tsx b/x-pack/plugins/apm/public/components/app/error_group_details/Distribution/index.tsx index fa458b95d0d8..b6fc0d4fcf65 100644 --- a/x-pack/plugins/apm/public/components/app/error_group_details/Distribution/index.tsx +++ b/x-pack/plugins/apm/public/components/app/error_group_details/Distribution/index.tsx @@ -31,9 +31,11 @@ import { getAlertAnnotations } from '../../../shared/charts/helper/get_alert_ann import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context'; import { LazyAlertsFlyout } from '../../../../../../observability/public'; -const ALERT_RULE_TYPE_ID: typeof ALERT_RULE_TYPE_ID_TYPED = ALERT_RULE_TYPE_ID_NON_TYPED; +const ALERT_RULE_TYPE_ID: typeof ALERT_RULE_TYPE_ID_TYPED = + ALERT_RULE_TYPE_ID_NON_TYPED; -type ErrorDistributionAPIResponse = APIReturnType<'GET /api/apm/services/{serviceName}/errors/distribution'>; +type ErrorDistributionAPIResponse = + APIReturnType<'GET /api/apm/services/{serviceName}/errors/distribution'>; interface FormattedBucket { x0: number; diff --git a/x-pack/plugins/apm/public/components/app/error_group_details/detail_view/exception_stacktrace.stories.tsx b/x-pack/plugins/apm/public/components/app/error_group_details/detail_view/exception_stacktrace.stories.tsx index 9468202edf4d..7ce38891d81f 100644 --- a/x-pack/plugins/apm/public/components/app/error_group_details/detail_view/exception_stacktrace.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/error_group_details/detail_view/exception_stacktrace.stories.tsx @@ -585,8 +585,7 @@ JavaWithLongLines.args = { module: 'org.apache.tomcat.util.threads', }, ], - type: - 'org.springframework.http.converter.HttpMessageNotWritableException', + type: 'org.springframework.http.converter.HttpMessageNotWritableException', message: 'Could not write JSON: Null return value from advice does not match primitive return type for: public abstract double co.elastic.apm.opbeans.repositories.Numbers.getRevenue(); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Null return value from advice does not match primitive return type for: public abstract double co.elastic.apm.opbeans.repositories.Numbers.getRevenue() (through reference chain: co.elastic.apm.opbeans.repositories.Stats["numbers"]->com.sun.proxy.$Proxy128["revenue"])', }, diff --git a/x-pack/plugins/apm/public/components/app/error_group_overview/List/index.tsx b/x-pack/plugins/apm/public/components/app/error_group_overview/List/index.tsx index 81d1208e6cbf..d42c77c06b0a 100644 --- a/x-pack/plugins/apm/public/components/app/error_group_overview/List/index.tsx +++ b/x-pack/plugins/apm/public/components/app/error_group_overview/List/index.tsx @@ -47,7 +47,8 @@ const Culprit = euiStyled.div` font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; `; -type ErrorGroupItem = APIReturnType<'GET /api/apm/services/{serviceName}/errors'>['errorGroups'][0]; +type ErrorGroupItem = + APIReturnType<'GET /api/apm/services/{serviceName}/errors'>['errorGroups'][0]; interface Props { items: ErrorGroupItem[]; diff --git a/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx b/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx index 0b505c4f5ade..7cd9c7c8e199 100644 --- a/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx @@ -159,16 +159,11 @@ function useServicesFetcher() { export function ServiceInventory() { const { core } = useApmPluginContext(); - const { - mainStatisticsData, - mainStatisticsStatus, - comparisonData, - } = useServicesFetcher(); + const { mainStatisticsData, mainStatisticsStatus, comparisonData } = + useServicesFetcher(); - const { - anomalyDetectionJobsData, - anomalyDetectionJobsStatus, - } = useAnomalyDetectionJobsContext(); + const { anomalyDetectionJobsData, anomalyDetectionJobsStatus } = + useAnomalyDetectionJobsContext(); const [userHasDismissedCallout, setUserHasDismissedCallout] = useLocalStorage( 'apm.userHasDismissedServiceInventoryMlCallout', diff --git a/x-pack/plugins/apm/public/components/app/service_inventory/service_inventory.test.tsx b/x-pack/plugins/apm/public/components/app/service_inventory/service_inventory.test.tsx index 2ff3f2702cb5..945d977e3036 100644 --- a/x-pack/plugins/apm/public/components/app/service_inventory/service_inventory.test.tsx +++ b/x-pack/plugins/apm/public/components/app/service_inventory/service_inventory.test.tsx @@ -35,7 +35,7 @@ const addWarning = jest.fn(); const httpGet = jest.fn(); function wrapper({ children }: { children?: ReactNode }) { - const mockPluginContext = (merge({}, mockApmPluginContextValue, { + const mockPluginContext = merge({}, mockApmPluginContextValue, { core: { http: { get: httpGet, @@ -46,7 +46,7 @@ function wrapper({ children }: { children?: ReactNode }) { }, }, }, - }) as unknown) as ApmPluginContextValue; + }) as unknown as ApmPluginContextValue; return ( diff --git a/x-pack/plugins/apm/public/components/app/service_inventory/service_list/index.tsx b/x-pack/plugins/apm/public/components/app/service_inventory/service_list/index.tsx index 17dfee35e221..9c1893b76f7d 100644 --- a/x-pack/plugins/apm/public/components/app/service_inventory/service_list/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_inventory/service_list/index.tsx @@ -45,7 +45,8 @@ import { HealthBadge } from './HealthBadge'; type ServiceListAPIResponse = APIReturnType<'GET /api/apm/services'>; type Items = ServiceListAPIResponse['items']; -type ServicesDetailedStatisticsAPIResponse = APIReturnType<'GET /api/apm/services/detailed_statistics'>; +type ServicesDetailedStatisticsAPIResponse = + APIReturnType<'GET /api/apm/services/detailed_statistics'>; type ServiceListItem = ValuesType; diff --git a/x-pack/plugins/apm/public/components/app/service_map/Popover/Popover.stories.tsx b/x-pack/plugins/apm/public/components/app/service_map/Popover/Popover.stories.tsx index 33973956a65b..d6300b7c80f1 100644 --- a/x-pack/plugins/apm/public/components/app/service_map/Popover/Popover.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/service_map/Popover/Popover.stories.tsx @@ -28,7 +28,7 @@ const stories: Meta = { component: Popover, decorators: [ (StoryComponent) => { - const coreMock = ({ + const coreMock = { http: { get: () => { return { @@ -44,7 +44,7 @@ const stories: Meta = { }, notifications: { toasts: { add: () => {} } }, uiSettings: { get: () => ({}) }, - } as unknown) as CoreStart; + } as unknown as CoreStart; const KibanaReactContext = createKibanaReactContext(coreMock); diff --git a/x-pack/plugins/apm/public/components/app/service_map/__stories__/cytoscape_example_data.stories.tsx b/x-pack/plugins/apm/public/components/app/service_map/__stories__/cytoscape_example_data.stories.tsx index 109e22240868..8189668ad6ef 100644 --- a/x-pack/plugins/apm/public/components/app/service_map/__stories__/cytoscape_example_data.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/service_map/__stories__/cytoscape_example_data.stories.tsx @@ -48,11 +48,11 @@ const stories: Meta<{}> = { component: Cytoscape, decorators: [ (StoryComponent, { globals }) => { - const KibanaReactContext = createKibanaReactContext(({ + const KibanaReactContext = createKibanaReactContext({ uiSettings: { get: () => globals.euiTheme && globals.euiTheme.includes('dark'), }, - } as unknown) as Partial); + } as unknown as Partial); return ( diff --git a/x-pack/plugins/apm/public/components/app/service_map/index.tsx b/x-pack/plugins/apm/public/components/app/service_map/index.tsx index 97b4f548f4bf..7499eb9cd658 100644 --- a/x-pack/plugins/apm/public/components/app/service_map/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_map/index.tsx @@ -111,7 +111,11 @@ export function ServiceMap({ const serviceName = useServiceName(); - const { data = { elements: [] }, status, error } = useFetcher( + const { + data = { elements: [] }, + status, + error, + } = useFetcher( (callApmApi) => { // When we don't have a license or a valid license, don't make the request. if (!license || !isActivePlatinumLicense(license)) { diff --git a/x-pack/plugins/apm/public/components/app/service_map/use_cytoscape_event_handlers.test.tsx b/x-pack/plugins/apm/public/components/app/service_map/use_cytoscape_event_handlers.test.tsx index 775cdd9b09d9..3deb1f49cf18 100644 --- a/x-pack/plugins/apm/public/components/app/service_map/use_cytoscape_event_handlers.test.tsx +++ b/x-pack/plugins/apm/public/components/app/service_map/use_cytoscape_event_handlers.test.tsx @@ -17,9 +17,9 @@ jest.mock('../../../../../observability/public'); cytoscape.use(dagre); -const theme = ({ +const theme = { eui: { avatarSizing: { l: { size: 10 } } }, -} as unknown) as EuiTheme; +} as unknown as EuiTheme; describe('useCytoscapeEventHandlers', () => { describe('when cytoscape is undefined', () => { @@ -38,13 +38,12 @@ describe('useCytoscapeEventHandlers', () => { }); // Mock the chain that leads to layout run - jest.spyOn(cy, 'elements').mockReturnValueOnce(({ + jest.spyOn(cy, 'elements').mockReturnValueOnce({ difference: () => - (({ - layout: () => - (({ run: () => {} } as unknown) as cytoscape.Layouts), - } as unknown) as cytoscape.CollectionReturnValue), - } as unknown) as cytoscape.CollectionReturnValue); + ({ + layout: () => ({ run: () => {} } as unknown as cytoscape.Layouts), + } as unknown as cytoscape.CollectionReturnValue), + } as unknown as cytoscape.CollectionReturnValue); renderHook(() => useCytoscapeEventHandlers({ serviceName: 'test', cy, theme }) @@ -62,12 +61,12 @@ describe('useCytoscapeEventHandlers', () => { const run = jest.fn(); // Mock the chain that leads to layout run - jest.spyOn(cy, 'elements').mockReturnValueOnce(({ + jest.spyOn(cy, 'elements').mockReturnValueOnce({ difference: () => - (({ - layout: () => (({ run } as unknown) as cytoscape.Layouts), - } as unknown) as cytoscape.CollectionReturnValue), - } as unknown) as cytoscape.CollectionReturnValue); + ({ + layout: () => ({ run } as unknown as cytoscape.Layouts), + } as unknown as cytoscape.CollectionReturnValue), + } as unknown as cytoscape.CollectionReturnValue); renderHook(() => useCytoscapeEventHandlers({ cy, theme })); cy.trigger('custom:data'); @@ -124,9 +123,9 @@ describe('useCytoscapeEventHandlers', () => { describe('when a drag ends', () => { it('changes the cursor to pointer', () => { const cy = cytoscape({ elements: [{ data: { id: 'test' } }] }); - const container = ({ + const container = { style: { cursor: 'grabbing' }, - } as unknown) as HTMLElement; + } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); renderHook(() => useCytoscapeEventHandlers({ cy, theme })); @@ -151,9 +150,9 @@ describe('useCytoscapeEventHandlers', () => { it('sets the cursor to pointer', () => { const cy = cytoscape({ elements: [{ data: { id: 'test' } }] }); - const container = ({ + const container = { style: { cursor: 'default' }, - } as unknown) as HTMLElement; + } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); renderHook(() => useCytoscapeEventHandlers({ cy, theme })); @@ -195,9 +194,9 @@ describe('useCytoscapeEventHandlers', () => { it('sets the cursor to the default', () => { const cy = cytoscape({ elements: [{ data: { id: 'test' } }] }); - const container = ({ + const container = { style: { cursor: 'pointer' }, - } as unknown) as HTMLElement; + } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); renderHook(() => useCytoscapeEventHandlers({ cy, theme })); @@ -216,9 +215,9 @@ describe('useCytoscapeEventHandlers', () => { { data: { id: 'b' } }, ], }); - const container = ({ + const container = { style: { cursor: 'default' }, - } as unknown) as HTMLElement; + } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); renderHook(() => useCytoscapeEventHandlers({ cy, theme })); @@ -273,9 +272,9 @@ describe('useCytoscapeEventHandlers', () => { describe('when a tap starts', () => { it('sets the cursor to grabbing', () => { const cy = cytoscape({}); - const container = ({ + const container = { style: { cursor: 'grab' }, - } as unknown) as HTMLElement; + } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); renderHook(() => useCytoscapeEventHandlers({ cy, theme })); @@ -287,9 +286,9 @@ describe('useCytoscapeEventHandlers', () => { describe('when the target is a node', () => { it('does not change the cursor', () => { const cy = cytoscape({ elements: [{ data: { id: 'test' } }] }); - const container = ({ + const container = { style: { cursor: 'grab' }, - } as unknown) as HTMLElement; + } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); renderHook(() => useCytoscapeEventHandlers({ cy, theme })); @@ -303,9 +302,9 @@ describe('useCytoscapeEventHandlers', () => { describe('when a tap ends', () => { it('sets the cursor to the default', () => { const cy = cytoscape({}); - const container = ({ + const container = { style: { cursor: 'grabbing' }, - } as unknown) as HTMLElement; + } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); renderHook(() => useCytoscapeEventHandlers({ cy, theme })); @@ -317,9 +316,9 @@ describe('useCytoscapeEventHandlers', () => { describe('when the target is a node', () => { it('does not change the cursor', () => { const cy = cytoscape({ elements: [{ data: { id: 'test' } }] }); - const container = ({ + const container = { style: { cursor: 'pointer' }, - } as unknown) as HTMLElement; + } as unknown as HTMLElement; jest.spyOn(cy, 'container').mockReturnValueOnce(container); renderHook(() => useCytoscapeEventHandlers({ cy, theme })); diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview.test.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview.test.tsx index b3c1afb32b0f..62cefa5de47f 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview.test.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview.test.tsx @@ -34,11 +34,11 @@ import { uiSettingsServiceMock } from '../../../../../../../src/core/public/mock const uiSettings = uiSettingsServiceMock.create().setup({} as any); -const KibanaReactContext = createKibanaReactContext(({ +const KibanaReactContext = createKibanaReactContext({ notifications: { toasts: { add: () => {} } }, uiSettings, usageCollection: { reportUiCounter: () => {} }, -} as unknown) as Partial); +} as unknown as Partial); const mockParams = { rangeFrom: 'now-15m', @@ -52,7 +52,7 @@ const location = { }; function Wrapper({ children }: { children?: ReactNode }) { - const value = ({ + const value = { ...mockApmPluginContextValue, core: { ...mockApmPluginContextValue.core, @@ -61,7 +61,7 @@ function Wrapper({ children }: { children?: ReactNode }) { get: () => {}, }, }, - } as unknown) as ApmPluginContextValue; + } as unknown as ApmPluginContextValue; return ( @@ -102,15 +102,17 @@ describe('ServiceOverview', () => { 'GET /api/apm/services/{serviceName}/error_groups/main_statistics': { error_groups: [] as any[], }, - 'GET /api/apm/services/{serviceName}/transactions/groups/main_statistics': { - transactionGroups: [] as any[], - totalTransactionGroups: 0, - isAggregationAccurate: true, - }, + 'GET /api/apm/services/{serviceName}/transactions/groups/main_statistics': + { + transactionGroups: [] as any[], + totalTransactionGroups: 0, + isAggregationAccurate: true, + }, 'GET /api/apm/services/{serviceName}/dependencies': { serviceDependencies: [], }, - 'GET /api/apm/services/{serviceName}/service_overview_instances/main_statistics': [], + 'GET /api/apm/services/{serviceName}/service_overview_instances/main_statistics': + [], 'GET /api/apm/services/{serviceName}/transactions/charts/latency': { currentPeriod: { overallAvgDuration: null, diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/get_columns.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/get_columns.tsx index 23c0f49cdafa..86f1907365bf 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/get_columns.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/get_columns.tsx @@ -15,8 +15,10 @@ import { ErrorDetailLink } from '../../../shared/Links/apm/ErrorDetailLink'; import { TimestampTooltip } from '../../../shared/TimestampTooltip'; import { TruncateWithTooltip } from '../../../shared/truncate_with_tooltip'; -type ErrorGroupMainStatistics = APIReturnType<'GET /api/apm/services/{serviceName}/error_groups/main_statistics'>; -type ErrorGroupDetailedStatistics = APIReturnType<'GET /api/apm/services/{serviceName}/error_groups/detailed_statistics'>; +type ErrorGroupMainStatistics = + APIReturnType<'GET /api/apm/services/{serviceName}/error_groups/main_statistics'>; +type ErrorGroupDetailedStatistics = + APIReturnType<'GET /api/apm/services/{serviceName}/error_groups/detailed_statistics'>; export function getColumns({ serviceName, diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/index.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/index.tsx index bfcd20b22301..ebf634fd6b18 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/index.tsx @@ -29,8 +29,10 @@ import { useTimeRange } from '../../../../hooks/use_time_range'; interface Props { serviceName: string; } -type ErrorGroupMainStatistics = APIReturnType<'GET /api/apm/services/{serviceName}/error_groups/main_statistics'>; -type ErrorGroupDetailedStatistics = APIReturnType<'GET /api/apm/services/{serviceName}/error_groups/detailed_statistics'>; +type ErrorGroupMainStatistics = + APIReturnType<'GET /api/apm/services/{serviceName}/error_groups/main_statistics'>; +type ErrorGroupDetailedStatistics = + APIReturnType<'GET /api/apm/services/{serviceName}/error_groups/detailed_statistics'>; type SortDirection = 'asc' | 'desc'; type SortField = 'name' | 'lastSeen' | 'occurrences'; diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_chart_and_table.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_chart_and_table.tsx index 87a4d4b7b87f..ab42d9b80634 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_chart_and_table.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_chart_and_table.tsx @@ -27,8 +27,10 @@ interface ServiceOverviewInstancesChartAndTableProps { serviceName: string; } -type ApiResponseMainStats = APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/main_statistics'>; -type ApiResponseDetailedStats = APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/detailed_statistics'>; +type ApiResponseMainStats = + APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/main_statistics'>; +type ApiResponseDetailedStats = + APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/detailed_statistics'>; const INITIAL_STATE_MAIN_STATS = { currentPeriodItems: [] as ApiResponseMainStats['currentPeriod'], @@ -164,49 +166,48 @@ export function ServiceOverviewInstancesChartAndTable({ direction ).slice(pageIndex * PAGE_SIZE, (pageIndex + 1) * PAGE_SIZE); - const { - data: detailedStatsData = INITIAL_STATE_DETAILED_STATISTICS, - } = useFetcher( - (callApmApi) => { - if ( - !start || - !end || - !transactionType || - !latencyAggregationType || - !currentPeriodItemsCount - ) { - return; - } - - return callApmApi({ - endpoint: - 'GET /api/apm/services/{serviceName}/service_overview_instances/detailed_statistics', - params: { - path: { - serviceName, - }, - query: { - environment, - kuery, - latencyAggregationType, - start, - end, - numBuckets: 20, - transactionType, - serviceNodeIds: JSON.stringify( - currentPeriodOrderedItems.map((item) => item.serviceNodeName) - ), - comparisonStart, - comparisonEnd, + const { data: detailedStatsData = INITIAL_STATE_DETAILED_STATISTICS } = + useFetcher( + (callApmApi) => { + if ( + !start || + !end || + !transactionType || + !latencyAggregationType || + !currentPeriodItemsCount + ) { + return; + } + + return callApmApi({ + endpoint: + 'GET /api/apm/services/{serviceName}/service_overview_instances/detailed_statistics', + params: { + path: { + serviceName, + }, + query: { + environment, + kuery, + latencyAggregationType, + start, + end, + numBuckets: 20, + transactionType, + serviceNodeIds: JSON.stringify( + currentPeriodOrderedItems.map((item) => item.serviceNodeName) + ), + comparisonStart, + comparisonEnd, + }, }, - }, - }); - }, - // only fetches detailed statistics when requestId is invalidated by main statistics api call - // eslint-disable-next-line react-hooks/exhaustive-deps - [requestId], - { preservePreviousData: false } - ); + }); + }, + // only fetches detailed statistics when requestId is invalidated by main statistics api call + // eslint-disable-next-line react-hooks/exhaustive-deps + [requestId], + { preservePreviousData: false } + ); return ( <> diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/get_columns.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/get_columns.tsx index 97a92cb9e057..3a80e0b07532 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/get_columns.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/get_columns.tsx @@ -32,9 +32,12 @@ import { getLatencyColumnLabel } from '../../../shared/transactions_table/get_la import { TruncateWithTooltip } from '../../../shared/truncate_with_tooltip'; import { InstanceActionsMenu } from './instance_actions_menu'; -type ServiceInstanceMainStatistics = APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/main_statistics'>; -type MainStatsServiceInstanceItem = ServiceInstanceMainStatistics['currentPeriod'][0]; -type ServiceInstanceDetailedStatistics = APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/detailed_statistics'>; +type ServiceInstanceMainStatistics = + APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/main_statistics'>; +type MainStatsServiceInstanceItem = + ServiceInstanceMainStatistics['currentPeriod'][0]; +type ServiceInstanceDetailedStatistics = + APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/detailed_statistics'>; export function getColumns({ serviceName, diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/index.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/index.tsx index 1df6803fdbbb..a8a93e8d4473 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/index.tsx @@ -28,9 +28,12 @@ import { InstanceDetails } from './intance_details'; import { useApmParams } from '../../../../hooks/use_apm_params'; import { useBreakpoints } from '../../../../hooks/use_breakpoints'; -type ServiceInstanceMainStatistics = APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/main_statistics'>; -type MainStatsServiceInstanceItem = ServiceInstanceMainStatistics['currentPeriod'][0]; -type ServiceInstanceDetailedStatistics = APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/detailed_statistics'>; +type ServiceInstanceMainStatistics = + APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/main_statistics'>; +type MainStatsServiceInstanceItem = + ServiceInstanceMainStatistics['currentPeriod'][0]; +type ServiceInstanceDetailedStatistics = + APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/detailed_statistics'>; export interface TableOptions { pageIndex: number; @@ -75,10 +78,8 @@ export function ServiceOverviewInstancesTable({ urlParams: { latencyAggregationType, comparisonEnabled }, } = useUrlParams(); - const [ - itemIdToOpenActionMenuRowMap, - setItemIdToOpenActionMenuRowMap, - ] = useState>({}); + const [itemIdToOpenActionMenuRowMap, setItemIdToOpenActionMenuRowMap] = + useState>({}); const [itemIdToExpandedRowMap, setItemIdToExpandedRowMap] = useState< Record diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/instance_actions_menu/menu_sections.ts b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/instance_actions_menu/menu_sections.ts index 0e78e44eedf7..cd7e64ae3966 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/instance_actions_menu/menu_sections.ts +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/instance_actions_menu/menu_sections.ts @@ -16,7 +16,8 @@ import { SectionRecord, } from '../../../../shared/transaction_action_menu/sections_helper'; -type InstaceDetails = APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/details/{serviceNodeName}'>; +type InstaceDetails = + APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/details/{serviceNodeName}'>; function getInfraMetricsQuery(timestamp?: string) { if (!timestamp) { diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/instance_details.test.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/instance_details.test.tsx index 219c46ea0a94..3a0ed21ca980 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/instance_details.test.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/instance_details.test.tsx @@ -15,7 +15,8 @@ import { import { InstanceDetails } from './intance_details'; import * as useInstanceDetailsFetcher from './use_instance_details_fetcher'; -type ServiceInstanceDetails = APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/details/{serviceNodeName}'>; +type ServiceInstanceDetails = + APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/details/{serviceNodeName}'>; describe('InstanceDetails', () => { it('renders loading spinner when data is being fetched', () => { diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/intance_details.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/intance_details.tsx index 1bfc92f159b5..7a194039e0d4 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/intance_details.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/intance_details.tsx @@ -33,7 +33,8 @@ import { pushNewItemToKueryBar } from '../../../shared/kuery_bar/utils'; import { getCloudIcon, getContainerIcon } from '../../../shared/service_icons'; import { useInstanceDetailsFetcher } from './use_instance_details_fetcher'; -type ServiceInstanceDetails = APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/details/{serviceNodeName}'>; +type ServiceInstanceDetails = + APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/details/{serviceNodeName}'>; interface Props { serviceName: string; diff --git a/x-pack/plugins/apm/public/components/app/service_profiling/index.tsx b/x-pack/plugins/apm/public/components/app/service_profiling/index.tsx index 4149b426e038..15caa833764b 100644 --- a/x-pack/plugins/apm/public/components/app/service_profiling/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_profiling/index.tsx @@ -18,7 +18,8 @@ import { APIReturnType } from '../../../services/rest/createCallApmApi'; import { ServiceProfilingFlamegraph } from './service_profiling_flamegraph'; import { ServiceProfilingTimeline } from './service_profiling_timeline'; -type ApiResponse = APIReturnType<'GET /api/apm/services/{serviceName}/profiling/timeline'>; +type ApiResponse = + APIReturnType<'GET /api/apm/services/{serviceName}/profiling/timeline'>; const DEFAULT_DATA: ApiResponse = { profilingTimeline: [] }; export function ServiceProfiling() { @@ -62,9 +63,11 @@ export function ServiceProfiling() { } const availableValueTypes = profilingTimeline.reduce((set, point) => { - (Object.keys(point.valueTypes).filter( - (type) => type !== 'unknown' - ) as ProfilingValueType[]) + ( + Object.keys(point.valueTypes).filter( + (type) => type !== 'unknown' + ) as ProfilingValueType[] + ) .filter((type) => point.valueTypes[type] > 0) .forEach((type) => { set.add(type); diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/distribution/index.test.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/distribution/index.test.tsx index 9a38e0fcf628..9057d4c6667b 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/distribution/index.test.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/distribution/index.test.tsx @@ -59,9 +59,9 @@ function Wrapper({ search: fromQuery({ transactionName: 'the-transaction-name' }), }); - const mockPluginContext = (merge({}, mockApmPluginContextValue, { + const mockPluginContext = merge({}, mockApmPluginContextValue, { core: { http: { get: httpGet } }, - }) as unknown) as ApmPluginContextValue; + }) as unknown as ApmPluginContextValue; return ( diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/distribution/index.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/distribution/index.tsx index d77d337db2de..ca162be92cda 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/distribution/index.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/distribution/index.tsx @@ -138,7 +138,8 @@ export function TransactionDistribution({ trackApmEvent({ metric: 'transaction_distribution_chart_clear_selection' }); }; - const transactionDistributionChartData: TransactionDistributionChartData[] = []; + const transactionDistributionChartData: TransactionDistributionChartData[] = + []; if (Array.isArray(overallHistogram)) { transactionDistributionChartData.push({ diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/use_waterfall_fetcher.ts b/x-pack/plugins/apm/public/components/app/transaction_details/use_waterfall_fetcher.ts index 1506580d7b9e..12bb8dbe12e4 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/use_waterfall_fetcher.ts +++ b/x-pack/plugins/apm/public/components/app/transaction_details/use_waterfall_fetcher.ts @@ -28,7 +28,11 @@ export function useWaterfallFetcher() { const { start, end } = useTimeRange({ rangeFrom, rangeTo }); - const { data = INITIAL_DATA, status, error } = useFetcher( + const { + data = INITIAL_DATA, + status, + error, + } = useFetcher( (callApmApi) => { if (traceId && start && end) { return callApmApi({ @@ -46,10 +50,10 @@ export function useWaterfallFetcher() { [traceId, start, end] ); - const waterfall = useMemo(() => getWaterfall(data, transactionId), [ - data, - transactionId, - ]); + const waterfall = useMemo( + () => getWaterfall(data, transactionId), + [data, transactionId] + ); return { waterfall, status, error }; } diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/span_flyout/span_flyout.stories.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/span_flyout/span_flyout.stories.tsx index c736f9df214b..33a0069e19ef 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/span_flyout/span_flyout.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/span_flyout/span_flyout.stories.tsx @@ -145,8 +145,7 @@ TransactionSpan.args = { }, service: { node: { - name: - '399a87146c0036592f6ee78553324b10c00757e024143913c97993384751e15e', + name: '399a87146c0036592f6ee78553324b10c00757e024143913c97993384751e15e', }, environment: 'production', framework: { diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/transaction_flyout/transaction_flyout.stories.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/transaction_flyout/transaction_flyout.stories.tsx index 7e2365ffb8af..33f1de91b61c 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/transaction_flyout/transaction_flyout.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/transaction_flyout/transaction_flyout.stories.tsx @@ -98,8 +98,7 @@ Example.args = { }, service: { node: { - name: - '4810e1f4da909044f1f6f56be41a542dc59784948f059769d6a590952deca405', + name: '4810e1f4da909044f1f6f56be41a542dc59784948f059769d6a590952deca405', }, environment: 'production', framework: { diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_helpers/waterfall_helpers.test.ts b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_helpers/waterfall_helpers.test.ts index 3e0c5034f37a..8c96c48f47d7 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_helpers/waterfall_helpers.test.ts +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_helpers/waterfall_helpers.test.ts @@ -85,7 +85,7 @@ describe('waterfall_helpers', () => { }, timestamp: { us: 1549324795785760 }, } as Span, - ({ + { parent: { id: 'mySpanIdD' }, processor: { event: 'transaction' }, trace: { id: 'myTraceId' }, @@ -103,10 +103,10 @@ describe('waterfall_helpers', () => { }, }, timestamp: { us: 1549324795823304 }, - } as unknown) as Transaction, + } as unknown as Transaction, ]; const errorDocs = [ - ({ + { processor: { event: 'error' }, parent: { id: 'myTransactionId1' }, timestamp: { us: 1549324795810000 }, @@ -124,7 +124,7 @@ describe('waterfall_helpers', () => { name: 'ruby', version: '2', }, - } as unknown) as APMError, + } as unknown as APMError, ]; it('should return full waterfall', () => { @@ -500,22 +500,22 @@ describe('waterfall_helpers', () => { { docType: 'transaction', id: 'a', - doc: ({ + doc: { transaction: { id: 'a' }, timestamp: { us: 10 }, - } as unknown) as Transaction, + } as unknown as Transaction, } as IWaterfallSpanOrTransaction, { docType: 'span', id: 'b', parentId: 'a', - doc: ({ + doc: { span: { id: 'b', }, parent: { id: 'a' }, timestamp: { us: 20 }, - } as unknown) as Span, + } as unknown as Span, } as IWaterfallSpanOrTransaction, ]; const childrenByParentId = groupBy(items, (hit) => diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfallContainer.stories.data.ts b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfallContainer.stories.data.ts index 1e58c1bd00a2..87150cdfc83a 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfallContainer.stories.data.ts +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfallContainer.stories.data.ts @@ -86,8 +86,7 @@ export const simpleTrace = { }, service: { node: { - name: - '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', + name: '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, environment: 'production', name: 'opbeans-java', @@ -192,8 +191,7 @@ export const simpleTrace = { '@timestamp': '2020-03-23T15:04:28.787Z', service: { node: { - name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', + name: 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', framework: { @@ -257,8 +255,7 @@ export const simpleTrace = { '@timestamp': '2020-03-23T15:04:28.788Z', service: { node: { - name: - 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', + name: 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', }, environment: 'production', framework: { @@ -338,8 +335,7 @@ export const simpleTrace = { }, service: { node: { - name: - '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', + name: '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, environment: 'production', name: 'opbeans-java', @@ -363,8 +359,7 @@ export const simpleTrace = { architecture: 'amd64', }, connection: { - hash: - "{service.environment:'production'}/{service.name:'opbeans-java'}/{span.subtype:'http'}/{destination.address:'opbeans-go'}/{span.type:'external'}", + hash: "{service.environment:'production'}/{service.name:'opbeans-java'}/{span.subtype:'http'}/{destination.address:'opbeans-go'}/{span.type:'external'}", }, transaction: { id: '49809ad3c26adf74', @@ -415,8 +410,7 @@ export const simpleTrace = { '@timestamp': '2020-03-23T15:04:28.787Z', service: { node: { - name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', + name: 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', name: 'opbeans-go', @@ -482,8 +476,7 @@ export const simpleTrace = { '@timestamp': '2020-03-23T15:04:28.790Z', service: { node: { - name: - 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', + name: 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', }, environment: 'production', framework: { @@ -536,7 +529,7 @@ export const simpleTrace = { errorDocs: [], } as TraceAPIResponse; -export const traceWithErrors = ({ +export const traceWithErrors = { traceDocs: [ { container: { @@ -588,8 +581,7 @@ export const traceWithErrors = ({ }, service: { node: { - name: - '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', + name: '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, environment: 'production', name: 'opbeans-java', @@ -694,8 +686,7 @@ export const traceWithErrors = ({ '@timestamp': '2020-03-23T15:04:28.787Z', service: { node: { - name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', + name: 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', framework: { @@ -759,8 +750,7 @@ export const traceWithErrors = ({ '@timestamp': '2020-03-23T15:04:28.788Z', service: { node: { - name: - 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', + name: 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', }, environment: 'production', framework: { @@ -840,8 +830,7 @@ export const traceWithErrors = ({ }, service: { node: { - name: - '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', + name: '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, environment: 'production', name: 'opbeans-java', @@ -865,8 +854,7 @@ export const traceWithErrors = ({ architecture: 'amd64', }, connection: { - hash: - "{service.environment:'production'}/{service.name:'opbeans-java'}/{span.subtype:'http'}/{destination.address:'opbeans-go'}/{span.type:'external'}", + hash: "{service.environment:'production'}/{service.name:'opbeans-java'}/{span.subtype:'http'}/{destination.address:'opbeans-go'}/{span.type:'external'}", }, transaction: { id: '49809ad3c26adf74', @@ -917,8 +905,7 @@ export const traceWithErrors = ({ '@timestamp': '2020-03-23T15:04:28.787Z', service: { node: { - name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', + name: 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', name: 'opbeans-go', @@ -984,8 +971,7 @@ export const traceWithErrors = ({ '@timestamp': '2020-03-23T15:04:28.790Z', service: { node: { - name: - 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', + name: 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', }, environment: 'production', framework: { @@ -1063,8 +1049,7 @@ export const traceWithErrors = ({ '@timestamp': '2020-03-23T16:04:28.787Z', service: { node: { - name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', + name: 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', name: 'opbeans-go', @@ -1113,8 +1098,7 @@ export const traceWithErrors = ({ '@timestamp': '2020-03-23T16:04:28.790Z', service: { node: { - name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', + name: 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', name: 'opbeans-python', @@ -1133,7 +1117,7 @@ export const traceWithErrors = ({ }, }, ], -} as unknown) as TraceAPIResponse; +} as unknown as TraceAPIResponse; export const traceChildStartBeforeParent = { traceDocs: [ @@ -1187,8 +1171,7 @@ export const traceChildStartBeforeParent = { }, service: { node: { - name: - '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', + name: '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, environment: 'production', name: 'opbeans-java', @@ -1293,8 +1276,7 @@ export const traceChildStartBeforeParent = { '@timestamp': '2020-03-23T15:04:28.787Z', service: { node: { - name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', + name: 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', framework: { @@ -1358,8 +1340,7 @@ export const traceChildStartBeforeParent = { '@timestamp': '2020-03-23T15:04:28.788Z', service: { node: { - name: - 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', + name: 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', }, environment: 'production', framework: { @@ -1439,8 +1420,7 @@ export const traceChildStartBeforeParent = { }, service: { node: { - name: - '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', + name: '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, environment: 'production', name: 'opbeans-java', @@ -1464,8 +1444,7 @@ export const traceChildStartBeforeParent = { architecture: 'amd64', }, connection: { - hash: - "{service.environment:'production'}/{service.name:'opbeans-java'}/{span.subtype:'http'}/{destination.address:'opbeans-go'}/{span.type:'external'}", + hash: "{service.environment:'production'}/{service.name:'opbeans-java'}/{span.subtype:'http'}/{destination.address:'opbeans-go'}/{span.type:'external'}", }, transaction: { id: '49809ad3c26adf74', @@ -1516,8 +1495,7 @@ export const traceChildStartBeforeParent = { '@timestamp': '2020-03-23T15:04:28.787Z', service: { node: { - name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', + name: 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', name: 'opbeans-go', @@ -1583,8 +1561,7 @@ export const traceChildStartBeforeParent = { '@timestamp': '2020-03-23T15:04:28.790Z', service: { node: { - name: - 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', + name: 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', }, environment: 'production', framework: { @@ -1684,8 +1661,7 @@ export const inferredSpans = { }, service: { node: { - name: - 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', + name: 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, environment: 'production', name: 'opbeans-java', @@ -1800,8 +1776,7 @@ export const inferredSpans = { }, service: { node: { - name: - 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', + name: 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, environment: 'production', name: 'opbeans-java', @@ -1878,8 +1853,7 @@ export const inferredSpans = { }, service: { node: { - name: - 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', + name: 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, environment: 'production', name: 'opbeans-java', @@ -1979,8 +1953,7 @@ export const inferredSpans = { }, service: { node: { - name: - 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', + name: 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, environment: 'production', name: 'opbeans-java', @@ -2057,8 +2030,7 @@ export const inferredSpans = { }, service: { node: { - name: - 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', + name: 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, environment: 'production', name: 'opbeans-java', @@ -2139,8 +2111,7 @@ export const inferredSpans = { }, service: { node: { - name: - 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', + name: 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, environment: 'production', name: 'opbeans-java', @@ -2237,8 +2208,7 @@ export const inferredSpans = { }, service: { node: { - name: - 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', + name: 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, environment: 'production', name: 'opbeans-java', diff --git a/x-pack/plugins/apm/public/components/app/transaction_overview/transaction_overview.test.tsx b/x-pack/plugins/apm/public/components/app/transaction_overview/transaction_overview.test.tsx index 9c145e95dbf1..e031af646418 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_overview/transaction_overview.test.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_overview/transaction_overview.test.tsx @@ -24,10 +24,10 @@ import { import { fromQuery } from '../../shared/Links/url_helpers'; import { TransactionOverview } from './'; -const KibanaReactContext = createKibanaReactContext(({ +const KibanaReactContext = createKibanaReactContext({ uiSettings: { get: () => true }, usageCollection: { reportUiCounter: () => {} }, -} as unknown) as Partial); +} as unknown as Partial); const history = createMemoryHistory(); jest.spyOn(history, 'push'); diff --git a/x-pack/plugins/apm/public/components/fleet_integration/apm_policy_form/index.tsx b/x-pack/plugins/apm/public/components/fleet_integration/apm_policy_form/index.tsx index 51944fdbddec..06e0e958bf69 100644 --- a/x-pack/plugins/apm/public/components/fleet_integration/apm_policy_form/index.tsx +++ b/x-pack/plugins/apm/public/components/fleet_integration/apm_policy_form/index.tsx @@ -32,21 +32,17 @@ export function APMPolicyForm({ isCloudPolicy, updateAPMPolicy, }: Props) { - const { - apmSettings, - rumSettings, - tlsSettings, - agentAuthorizationSettings, - } = useMemo(() => { - return { - apmSettings: getApmSettings({ isCloudPolicy }), - rumSettings: getRUMSettings(), - tlsSettings: getTLSSettings(), - agentAuthorizationSettings: getAgentAuthorizationSettings({ - isCloudPolicy, - }), - }; - }, [isCloudPolicy]); + const { apmSettings, rumSettings, tlsSettings, agentAuthorizationSettings } = + useMemo(() => { + return { + apmSettings: getApmSettings({ isCloudPolicy }), + rumSettings: getRUMSettings(), + tlsSettings: getTLSSettings(), + agentAuthorizationSettings: getAgentAuthorizationSettings({ + isCloudPolicy, + }), + }; + }, [isCloudPolicy]); function handleFormChange(key: string, value: any) { // Merge new key/value with the rest of fields diff --git a/x-pack/plugins/apm/public/components/routing/templates/apm_service_template/analyze_data_button.stories.tsx b/x-pack/plugins/apm/public/components/routing/templates/apm_service_template/analyze_data_button.stories.tsx index d9d3b50e0369..836b31bc5dfd 100644 --- a/x-pack/plugins/apm/public/components/routing/templates/apm_service_template/analyze_data_button.stories.tsx +++ b/x-pack/plugins/apm/public/components/routing/templates/apm_service_template/analyze_data_button.stories.tsx @@ -29,12 +29,12 @@ export default { (StoryComponent: ComponentType, { args }: StoryContext) => { const { agentName, canShowDashboard, environment, serviceName } = args; - const KibanaContext = createKibanaReactContext(({ + const KibanaContext = createKibanaReactContext({ application: { capabilities: { dashboard: { show: canShowDashboard } }, }, http: { basePath: { get: () => '' } }, - } as unknown) as Partial); + } as unknown as Partial); return ( `/basepath`, }, } as HttpStart, - docLinks: ({ + docLinks: { DOC_LINK_VERSION: '0', ELASTIC_WEBSITE_URL: 'https://www.elastic.co/', links: { apm: {}, observability: { guide: '' }, }, - } as unknown) as DocLinksStart, + } as unknown as DocLinksStart, } as Partial); function Wrapper({ children }: { children?: ReactNode }) { @@ -53,9 +53,9 @@ function Wrapper({ children }: { children?: ReactNode }) { describe('Settings', () => { it('renders', async () => { - const routerProps = ({ + const routerProps = { location, - } as unknown) as RouteComponentProps<{}>; + } as unknown as RouteComponentProps<{}>; expect(() => render( 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 fa59d651061f..6772438fed01 100644 --- a/x-pack/plugins/apm/public/components/shared/DatePicker/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/DatePicker/index.tsx @@ -78,7 +78,8 @@ export function DatePicker() { } // read time from state and update the url - const timePickerSharedState = plugins.data.query.timefilter.timefilter.getTime(); + const timePickerSharedState = + plugins.data.query.timefilter.timefilter.getTime(); history.replace({ ...location, diff --git a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLExplorerLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLExplorerLink.tsx index c1247441099b..11b29f00155f 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLExplorerLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLExplorerLink.tsx @@ -39,9 +39,10 @@ export function useExplorerHref({ jobId }: { jobId: string }) { } = useApmPluginContext(); const { urlParams } = useUrlParams(); - const timePickerRefreshIntervalDefaults = core.uiSettings.get( - UI_SETTINGS.TIMEPICKER_REFRESH_INTERVAL_DEFAULTS - ); + const timePickerRefreshIntervalDefaults = + core.uiSettings.get( + UI_SETTINGS.TIMEPICKER_REFRESH_INTERVAL_DEFAULTS + ); const { // hardcoding a custom default of 1 hour since the default kibana timerange of 15 minutes is shorter than the ML interval diff --git a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLManageJobsLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLManageJobsLink.tsx index ede1c33a341d..5c8d46420409 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLManageJobsLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLManageJobsLink.tsx @@ -26,9 +26,10 @@ export function MLManageJobsLink({ children, external }: Props) { const { urlParams } = useUrlParams(); - const timePickerRefreshIntervalDefaults = core.uiSettings.get( - UI_SETTINGS.TIMEPICKER_REFRESH_INTERVAL_DEFAULTS - ); + const timePickerRefreshIntervalDefaults = + core.uiSettings.get( + UI_SETTINGS.TIMEPICKER_REFRESH_INTERVAL_DEFAULTS + ); const { // hardcoding a custom default of 1 hour since the default kibana timerange of 15 minutes is shorter than the ML interval diff --git a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLSingleMetricLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLSingleMetricLink.tsx index 24812cf2feae..a36beccd16be 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLSingleMetricLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLSingleMetricLink.tsx @@ -55,9 +55,10 @@ export function useSingleMetricHref({ } = useApmPluginContext(); const { urlParams } = useUrlParams(); - const timePickerRefreshIntervalDefaults = core.uiSettings.get( - UI_SETTINGS.TIMEPICKER_REFRESH_INTERVAL_DEFAULTS - ); + const timePickerRefreshIntervalDefaults = + core.uiSettings.get( + UI_SETTINGS.TIMEPICKER_REFRESH_INTERVAL_DEFAULTS + ); const { // hardcoding a custom default of 1 hour since the default kibana timerange of 15 minutes is shorter than the ML interval diff --git a/x-pack/plugins/apm/public/components/shared/MetadataTable/ErrorMetadata/ErrorMetadata.test.tsx b/x-pack/plugins/apm/public/components/shared/MetadataTable/ErrorMetadata/ErrorMetadata.test.tsx index 9be47b7d1083..f936941923e4 100644 --- a/x-pack/plugins/apm/public/components/shared/MetadataTable/ErrorMetadata/ErrorMetadata.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/MetadataTable/ErrorMetadata/ErrorMetadata.test.tsx @@ -29,7 +29,7 @@ const renderOptions = { }; function getError() { - return ({ + return { labels: { someKey: 'labels value' }, http: { someKey: 'http value' }, host: { someKey: 'host value' }, @@ -47,7 +47,7 @@ function getError() { someKey: 'custom value', }, }, - } as unknown) as APMError; + } as unknown as APMError; } describe('ErrorMetadata', () => { diff --git a/x-pack/plugins/apm/public/components/shared/MetadataTable/MetadataTable.test.tsx b/x-pack/plugins/apm/public/components/shared/MetadataTable/MetadataTable.test.tsx index f21dbf3ae12e..7ccde6a9a74d 100644 --- a/x-pack/plugins/apm/public/components/shared/MetadataTable/MetadataTable.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/MetadataTable/MetadataTable.test.tsx @@ -27,7 +27,7 @@ const renderOptions = { describe('MetadataTable', () => { it('shows sections', () => { - const sectionsWithRows = ([ + const sectionsWithRows = [ { key: 'foo', label: 'Foo', required: true }, { key: 'bar', @@ -39,7 +39,7 @@ describe('MetadataTable', () => { { key: 'props.B', value: 'B' }, ], }, - ] as unknown) as SectionsWithRows; + ] as unknown as SectionsWithRows; const output = render( , renderOptions @@ -56,13 +56,13 @@ describe('MetadataTable', () => { }); describe('required sections', () => { it('shows "empty state message" if no data is available', () => { - const sectionsWithRows = ([ + const sectionsWithRows = [ { key: 'foo', label: 'Foo', required: true, }, - ] as unknown) as SectionsWithRows; + ] as unknown as SectionsWithRows; const output = render( , renderOptions diff --git a/x-pack/plugins/apm/public/components/shared/MetadataTable/SpanMetadata/SpanMetadata.test.tsx b/x-pack/plugins/apm/public/components/shared/MetadataTable/SpanMetadata/SpanMetadata.test.tsx index 308d55b2925c..46eaba1e9e11 100644 --- a/x-pack/plugins/apm/public/components/shared/MetadataTable/SpanMetadata/SpanMetadata.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/MetadataTable/SpanMetadata/SpanMetadata.test.tsx @@ -31,7 +31,7 @@ const renderOptions = { describe('SpanMetadata', () => { describe('render', () => { it('renders', () => { - const span = ({ + const span = { agent: { ephemeral_id: 'ed8e3a4f-21d2-4a1f-bbc7-fa2064d94225', name: 'java', @@ -47,14 +47,14 @@ describe('SpanMetadata', () => { queue: { name: 'queue name' }, }, }, - } as unknown) as Span; + } as unknown as Span; const output = render(, renderOptions); expectTextsInDocument(output, ['Service', 'Agent', 'Message']); }); }); describe('when a span is presented', () => { it('renders the span', () => { - const span = ({ + const span = { agent: { ephemeral_id: 'ed8e3a4f-21d2-4a1f-bbc7-fa2064d94225', name: 'java', @@ -75,14 +75,14 @@ describe('SpanMetadata', () => { queue: { name: 'queue name' }, }, }, - } as unknown) as Span; + } as unknown as Span; const output = render(, renderOptions); expectTextsInDocument(output, ['Service', 'Agent', 'Span', 'Message']); }); }); describe('when there is no id inside span', () => { it('does not show the section', () => { - const span = ({ + const span = { agent: { ephemeral_id: 'ed8e3a4f-21d2-4a1f-bbc7-fa2064d94225', name: 'java', @@ -98,7 +98,7 @@ describe('SpanMetadata', () => { subtype: 'http', type: 'external', }, - } as unknown) as Span; + } as unknown as Span; const output = render(, renderOptions); expectTextsInDocument(output, ['Service', 'Agent']); expectTextsNotInDocument(output, ['Span', 'Message']); diff --git a/x-pack/plugins/apm/public/components/shared/MetadataTable/TransactionMetadata/TransactionMetadata.test.tsx b/x-pack/plugins/apm/public/components/shared/MetadataTable/TransactionMetadata/TransactionMetadata.test.tsx index fa4e802cc7d6..08253f04777d 100644 --- a/x-pack/plugins/apm/public/components/shared/MetadataTable/TransactionMetadata/TransactionMetadata.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/MetadataTable/TransactionMetadata/TransactionMetadata.test.tsx @@ -29,7 +29,7 @@ const renderOptions = { }; function getTransaction() { - return ({ + return { labels: { someKey: 'labels value' }, http: { someKey: 'http value' }, host: { someKey: 'host value' }, @@ -51,7 +51,7 @@ function getTransaction() { queue: { name: 'queue name' }, }, }, - } as unknown) as Transaction; + } as unknown as Transaction; } describe('TransactionMetadata', () => { diff --git a/x-pack/plugins/apm/public/components/shared/MetadataTable/helper.test.ts b/x-pack/plugins/apm/public/components/shared/MetadataTable/helper.test.ts index 87a94f48e947..770b35e7d17f 100644 --- a/x-pack/plugins/apm/public/components/shared/MetadataTable/helper.test.ts +++ b/x-pack/plugins/apm/public/components/shared/MetadataTable/helper.test.ts @@ -15,7 +15,7 @@ describe('MetadataTable Helper', () => { HTTP, { ...SERVICE, properties: ['environment'] }, ]; - const apmDoc = ({ + const apmDoc = { http: { headers: { Connection: 'close', @@ -27,7 +27,7 @@ describe('MetadataTable Helper', () => { framework: { name: 'express' }, environment: 'production', }, - } as unknown) as Transaction; + } as unknown as Transaction; const metadataItems = getSectionsWithRows(sections, apmDoc); it('returns flattened data and required section', () => { diff --git a/x-pack/plugins/apm/public/components/shared/MetadataTable/helper.ts b/x-pack/plugins/apm/public/components/shared/MetadataTable/helper.ts index c7910a5b1e4c..d9169d06735c 100644 --- a/x-pack/plugins/apm/public/components/shared/MetadataTable/helper.ts +++ b/x-pack/plugins/apm/public/components/shared/MetadataTable/helper.ts @@ -24,11 +24,10 @@ export const getSectionsWithRows = ( apmDoc, section.key ) as Record; - const filteredData: - | Record - | undefined = section.properties - ? pick(sectionData, section.properties) - : sectionData; + const filteredData: Record | undefined = + section.properties + ? pick(sectionData, section.properties) + : sectionData; const rows: KeyValuePair[] = flattenObject(filteredData, section.key); return { ...section, rows }; diff --git a/x-pack/plugins/apm/public/components/shared/apm_header_action_menu/anomaly_detection_setup_link.test.tsx b/x-pack/plugins/apm/public/components/shared/apm_header_action_menu/anomaly_detection_setup_link.test.tsx index 6a6ba3f9529f..0520cfa39a74 100644 --- a/x-pack/plugins/apm/public/components/shared/apm_header_action_menu/anomaly_detection_setup_link.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/apm_header_action_menu/anomaly_detection_setup_link.test.tsx @@ -36,14 +36,14 @@ async function renderTooltipAnchor({ // wait for tooltip text to be in the DOM await waitFor(() => { - const toolTipText = baseElement.querySelector('.euiToolTipPopover') - ?.textContent; + const toolTipText = + baseElement.querySelector('.euiToolTipPopover')?.textContent; expect(toolTipText).not.toBe(undefined); }); } - const toolTipText = baseElement.querySelector('.euiToolTipPopover') - ?.textContent; + const toolTipText = + baseElement.querySelector('.euiToolTipPopover')?.textContent; return { toolTipText, toolTipAnchor }; } diff --git a/x-pack/plugins/apm/public/components/shared/apm_header_action_menu/anomaly_detection_setup_link.tsx b/x-pack/plugins/apm/public/components/shared/apm_header_action_menu/anomaly_detection_setup_link.tsx index f0c71265b70b..c84cbc9a4b10 100644 --- a/x-pack/plugins/apm/public/components/shared/apm_header_action_menu/anomaly_detection_setup_link.tsx +++ b/x-pack/plugins/apm/public/components/shared/apm_header_action_menu/anomaly_detection_setup_link.tsx @@ -26,7 +26,8 @@ import { useTheme } from '../../../hooks/use_theme'; import { APIReturnType } from '../../../services/rest/createCallApmApi'; import { getAPMHref } from '../Links/apm/APMLink'; -export type AnomalyDetectionApiResponse = APIReturnType<'GET /api/apm/settings/anomaly-detection/jobs'>; +export type AnomalyDetectionApiResponse = + APIReturnType<'GET /api/apm/settings/anomaly-detection/jobs'>; const DEFAULT_DATA = { jobs: [], hasLegacyJobs: false }; diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/error_marker.test.tsx b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/error_marker.test.tsx index fdb97ea4fadd..cef97c46fd2e 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/error_marker.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/error_marker.test.tsx @@ -26,7 +26,7 @@ function Wrapper({ children }: { children?: ReactNode }) { } describe('ErrorMarker', () => { - const mark = ({ + const mark = { id: 'agent', offset: 10000, type: 'errorMark', @@ -44,7 +44,7 @@ describe('ErrorMarker', () => { service: { name: 'bar' }, }, serviceColor: '#fff', - } as unknown) as ErrorMark; + } as unknown as ErrorMark; function openPopover(errorMark: ErrorMark) { const component = renderWithTheme(, { @@ -114,7 +114,7 @@ describe('ErrorMarker', () => { describe('when the error message is not longer than 240 characters', () => { it('truncates the error message text', () => { - const newMark = ({ + const newMark = { ...mark, error: { ...mark.error, @@ -125,7 +125,7 @@ describe('ErrorMarker', () => { }, }, }, - } as unknown) as ErrorMark; + } as unknown as ErrorMark; const component = openPopover(newMark); const errorLink = component.getByTestId('errorLink') as HTMLAnchorElement; expect(errorLink.innerHTML).toHaveLength(5); diff --git a/x-pack/plugins/apm/public/components/shared/charts/helper/get_alert_annotations.test.tsx b/x-pack/plugins/apm/public/components/shared/charts/helper/get_alert_annotations.test.tsx index 2b463d1cdd06..e63f7fbc79ab 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/helper/get_alert_annotations.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/helper/get_alert_annotations.test.tsx @@ -35,9 +35,9 @@ type Alert = ValuesType< const euiColorDanger = 'red'; const euiColorWarning = 'yellow'; -const theme = ({ +const theme = { eui: { euiColorDanger, euiColorWarning }, -} as unknown) as EuiTheme; +} as unknown as EuiTheme; const alert: Alert = { [ALERT_RULE_TYPE_ID]: ['apm.transaction_duration'], [ALERT_EVALUATION_VALUE]: [2057657.39], @@ -62,10 +62,11 @@ const alert: Alert = { [ALERT_RULE_CATEGORY]: ['Latency threshold'], }; const chartStartTime = new Date(alert[ALERT_START]![0] as string).getTime(); -const getFormatter: ObservabilityRuleTypeRegistry['getFormatter'] = () => () => ({ - link: '/', - reason: 'a good reason', -}); +const getFormatter: ObservabilityRuleTypeRegistry['getFormatter'] = + () => () => ({ + link: '/', + reason: 'a good reason', + }); const selectedAlertId = undefined; const setSelectedAlertId = jest.fn(); @@ -127,8 +128,8 @@ describe('getAlertAnnotations', () => { describe('with no formatter', () => { it('uses the rule type', () => { - const getNoFormatter: ObservabilityRuleTypeRegistry['getFormatter'] = () => - undefined; + const getNoFormatter: ObservabilityRuleTypeRegistry['getFormatter'] = + () => undefined; expect( getAlertAnnotations({ diff --git a/x-pack/plugins/apm/public/components/shared/charts/helper/get_alert_annotations.tsx b/x-pack/plugins/apm/public/components/shared/charts/helper/get_alert_annotations.tsx index 4aef5f6e56b9..39e1ce59de4b 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/helper/get_alert_annotations.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/helper/get_alert_annotations.tsx @@ -41,7 +41,8 @@ const ALERT_DURATION: typeof ALERT_DURATION_TYPED = ALERT_DURATION_NON_TYPED; const ALERT_SEVERITY: typeof ALERT_SEVERITY_TYPED = ALERT_SEVERITY_NON_TYPED; const ALERT_START: typeof ALERT_START_TYPED = ALERT_START_NON_TYPED; const ALERT_UUID: typeof ALERT_UUID_TYPED = ALERT_UUID_NON_TYPED; -const ALERT_RULE_TYPE_ID: typeof ALERT_RULE_TYPE_ID_TYPED = ALERT_RULE_TYPE_ID_NON_TYPED; +const ALERT_RULE_TYPE_ID: typeof ALERT_RULE_TYPE_ID_TYPED = + ALERT_RULE_TYPE_ID_NON_TYPED; const ALERT_RULE_NAME: typeof ALERT_RULE_NAME_TYPED = ALERT_RULE_NAME_NON_TYPED; type Alert = ValuesType< diff --git a/x-pack/plugins/apm/public/components/shared/charts/helper/helper.test.ts b/x-pack/plugins/apm/public/components/shared/charts/helper/helper.test.ts index b8d67f71a9ba..647064f88b5d 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/helper/helper.test.ts +++ b/x-pack/plugins/apm/public/components/shared/charts/helper/helper.test.ts @@ -11,12 +11,12 @@ import { Coordinate, TimeSeries } from '../../../../../typings/timeseries'; describe('Chart helper', () => { describe('onBrushEnd', () => { - const history = ({ + const history = { push: jest.fn(), location: { search: '', }, - } as unknown) as History; + } as unknown as History; it("doesn't push a new history when x is not defined", () => { onBrushEnd({ x: undefined, history }); expect(history.push).not.toBeCalled(); diff --git a/x-pack/plugins/apm/public/components/shared/charts/instances_latency_distribution_chart/custom_tooltip.stories.tsx b/x-pack/plugins/apm/public/components/shared/charts/instances_latency_distribution_chart/custom_tooltip.stories.tsx index ae3c871e25a1..d39770b68d5b 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/instances_latency_distribution_chart/custom_tooltip.stories.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/instances_latency_distribution_chart/custom_tooltip.stories.tsx @@ -11,13 +11,15 @@ import { APIReturnType } from '../../../../services/rest/createCallApmApi'; import { getDurationFormatter } from '../../../../../common/utils/formatters'; import { CustomTooltip } from './custom_tooltip'; -type ServiceInstanceMainStatistics = APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/main_statistics'>; -type MainStatsServiceInstanceItem = ServiceInstanceMainStatistics['currentPeriod'][0]; +type ServiceInstanceMainStatistics = + APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/main_statistics'>; +type MainStatsServiceInstanceItem = + ServiceInstanceMainStatistics['currentPeriod'][0]; function getLatencyFormatter(props: TooltipInfo) { const maxLatency = Math.max( ...props.values.map((value) => { - const datum = (value.datum as unknown) as MainStatsServiceInstanceItem; + const datum = value.datum as unknown as MainStatsServiceInstanceItem; return datum.latency ?? 0; }) ); @@ -37,8 +39,7 @@ export function Example(props: TooltipInfo) { Example.args = { header: { seriesIdentifier: { - key: - 'groupId{__global__}spec{Instances}yAccessor{(index:0)}splitAccessors{}', + key: 'groupId{__global__}spec{Instances}yAccessor{(index:0)}splitAccessors{}', specId: 'Instances', yAccessor: '(index:0)', splitAccessors: {}, @@ -65,8 +66,7 @@ Example.args = { values: [ { seriesIdentifier: { - key: - 'groupId{__global__}spec{Instances}yAccessor{(index:0)}splitAccessors{}', + key: 'groupId{__global__}spec{Instances}yAccessor{(index:0)}splitAccessors{}', specId: 'Instances', }, valueAccessor: 'y1', @@ -98,8 +98,7 @@ export function MultipleInstances(props: TooltipInfo) { MultipleInstances.args = { header: { seriesIdentifier: { - key: - 'groupId{__global__}spec{Instances}yAccessor{(index:0)}splitAccessors{}', + key: 'groupId{__global__}spec{Instances}yAccessor{(index:0)}splitAccessors{}', specId: 'Instances', yAccessor: '(index:0)', splitAccessors: {}, @@ -126,8 +125,7 @@ MultipleInstances.args = { values: [ { seriesIdentifier: { - key: - 'groupId{__global__}spec{Instances}yAccessor{(index:0)}splitAccessors{}', + key: 'groupId{__global__}spec{Instances}yAccessor{(index:0)}splitAccessors{}', specId: 'Instances', }, valueAccessor: 'y1', @@ -150,8 +148,7 @@ MultipleInstances.args = { }, { seriesIdentifier: { - key: - 'groupId{__global__}spec{Instances}yAccessor{(index:0)}splitAccessors{}', + key: 'groupId{__global__}spec{Instances}yAccessor{(index:0)}splitAccessors{}', specId: 'Instances', }, valueAccessor: 'y1', diff --git a/x-pack/plugins/apm/public/components/shared/charts/instances_latency_distribution_chart/custom_tooltip.tsx b/x-pack/plugins/apm/public/components/shared/charts/instances_latency_distribution_chart/custom_tooltip.tsx index a0197c2f50c9..7289ffddd0ea 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/instances_latency_distribution_chart/custom_tooltip.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/instances_latency_distribution_chart/custom_tooltip.tsx @@ -17,8 +17,10 @@ import { } from '../../../../../common/utils/formatters'; import { useTheme } from '../../../../hooks/use_theme'; -type ServiceInstanceMainStatistics = APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/main_statistics'>; -type MainStatsServiceInstanceItem = ServiceInstanceMainStatistics['currentPeriod'][0]; +type ServiceInstanceMainStatistics = + APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/main_statistics'>; +type MainStatsServiceInstanceItem = + ServiceInstanceMainStatistics['currentPeriod'][0]; const latencyLabel = i18n.translate( 'xpack.apm.instancesLatencyDistributionChartTooltipLatencyLabel', @@ -51,7 +53,7 @@ function SingleInstanceCustomTooltip({ }) { const value = values[0]; const { color } = value; - const datum = (value.datum as unknown) as MainStatsServiceInstanceItem; + const datum = value.datum as unknown as MainStatsServiceInstanceItem; const { latency, serviceNodeName, throughput } = datum; return ( @@ -122,7 +124,7 @@ function MultipleInstanceCustomTooltip({
{values.map((value) => { const { color } = value; - const datum = (value.datum as unknown) as MainStatsServiceInstanceItem; + const datum = value.datum as unknown as MainStatsServiceInstanceItem; const { latency, serviceNodeName, throughput } = datum; return (
diff --git a/x-pack/plugins/apm/public/components/shared/charts/instances_latency_distribution_chart/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/instances_latency_distribution_chart/index.tsx index b7d1d37d2c0d..5c974664eb1d 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/instances_latency_distribution_chart/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/instances_latency_distribution_chart/index.tsx @@ -36,7 +36,8 @@ import { ChartContainer } from '../chart_container'; import { getResponseTimeTickFormatter } from '../transaction_charts/helper'; import { CustomTooltip } from './custom_tooltip'; -type ApiResponseMainStats = APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/main_statistics'>; +type ApiResponseMainStats = + APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/main_statistics'>; export interface InstancesLatencyDistributionChartProps { height: number; diff --git a/x-pack/plugins/apm/public/components/shared/charts/latency_chart/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/latency_chart/index.tsx index 20c623d6792e..3cee9c22174a 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/latency_chart/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/latency_chart/index.tsx @@ -29,7 +29,8 @@ import { MLHeader } from '../../../shared/charts/transaction_charts/ml_header'; import * as urlHelpers from '../../../shared/Links/url_helpers'; import { getComparisonChartTheme } from '../../time_comparison/get_time_range_comparison'; -const ALERT_RULE_TYPE_ID: typeof ALERT_RULE_TYPE_ID_TYPED = ALERT_RULE_TYPE_ID_NON_TYPED; +const ALERT_RULE_TYPE_ID: typeof ALERT_RULE_TYPE_ID_TYPED = + ALERT_RULE_TYPE_ID_NON_TYPED; interface Props { height?: number; @@ -55,20 +56,14 @@ export function LatencyChart({ height, kuery, environment }: Props) { const { latencyAggregationType, comparisonEnabled } = urlParams; const license = useLicenseContext(); - const { - latencyChartsData, - latencyChartsStatus, - } = useTransactionLatencyChartsFetcher({ - kuery, - environment, - }); + const { latencyChartsData, latencyChartsStatus } = + useTransactionLatencyChartsFetcher({ + kuery, + environment, + }); - const { - currentPeriod, - previousPeriod, - anomalyTimeseries, - mlJobId, - } = latencyChartsData; + const { currentPeriod, previousPeriod, anomalyTimeseries, mlJobId } = + latencyChartsData; const { alerts } = useApmServiceContext(); diff --git a/x-pack/plugins/apm/public/components/shared/charts/latency_chart/latency_chart.stories.tsx b/x-pack/plugins/apm/public/components/shared/charts/latency_chart/latency_chart.stories.tsx index 5afc853beb31..511b605e3c22 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/latency_chart/latency_chart.stories.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/latency_chart/latency_chart.stories.tsx @@ -61,7 +61,7 @@ export default { const { alertsResponse, latencyChartResponse } = args as Args; const serviceName = 'testService'; - const apmPluginContextMock = ({ + const apmPluginContextMock = { core: { notifications: { toasts: { addWarning: () => {}, addDanger: () => {} }, @@ -81,7 +81,7 @@ export default { }, plugins: { observability: { isAlertingExperienceEnabled: () => true } }, observabilityRuleTypeRegistry: { getFormatter: () => undefined }, - } as unknown) as ApmPluginContextValue; + } as unknown as ApmPluginContextValue; createCallApmApi(apmPluginContextMock.core); diff --git a/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/use_transaction_breakdown.ts b/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/use_transaction_breakdown.ts index 789461379d04..e814459fbf51 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/use_transaction_breakdown.ts +++ b/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/use_transaction_breakdown.ts @@ -30,7 +30,11 @@ export function useTransactionBreakdown({ const { transactionType, serviceName } = useApmServiceContext(); - const { data = { timeseries: undefined }, error, status } = useFetcher( + const { + data = { timeseries: undefined }, + error, + status, + } = useFetcher( (callApmApi) => { if (serviceName && start && end && transactionType) { return callApmApi({ diff --git a/x-pack/plugins/apm/public/components/shared/charts/transaction_charts/helper.test.ts b/x-pack/plugins/apm/public/components/shared/charts/transaction_charts/helper.test.ts index 3c65cce50d16..20d0388b0f33 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/transaction_charts/helper.test.ts +++ b/x-pack/plugins/apm/public/components/shared/charts/transaction_charts/helper.test.ts @@ -36,14 +36,14 @@ describe('transaction chart helper', () => { }); it('returns zero for invalid y coordinate', () => { - const timeSeries = ([ + const timeSeries = [ { data: [{ x: 1 }, { x: 2 }, { x: 3, y: -1 }] }, - ] as unknown) as Array>; + ] as unknown as Array>; expect(getMaxY(timeSeries)).toEqual(0); }); it('returns the max y coordinate', () => { - const timeSeries = ([ + const timeSeries = [ { data: [ { x: 1, y: 10 }, @@ -51,7 +51,7 @@ describe('transaction chart helper', () => { { x: 3, y: 1 }, ], }, - ] as unknown) as Array>; + ] as unknown as Array>; expect(getMaxY(timeSeries)).toEqual(10); }); }); diff --git a/x-pack/plugins/apm/public/components/shared/charts/transaction_error_rate_chart/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/transaction_error_rate_chart/index.tsx index ae24a5e53444..88788c7c3d39 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/transaction_error_rate_chart/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/transaction_error_rate_chart/index.tsx @@ -35,7 +35,8 @@ interface Props { environment: string; } -type ErrorRate = APIReturnType<'GET /api/apm/services/{serviceName}/transactions/charts/error_rate'>; +type ErrorRate = + APIReturnType<'GET /api/apm/services/{serviceName}/transactions/charts/error_rate'>; const INITIAL_STATE: ErrorRate = { currentPeriod: { diff --git a/x-pack/plugins/apm/public/components/shared/key_value_filter_list/index.tsx b/x-pack/plugins/apm/public/components/shared/key_value_filter_list/index.tsx index d28cc1646f16..c1fb78546605 100644 --- a/x-pack/plugins/apm/public/components/shared/key_value_filter_list/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/key_value_filter_list/index.tsx @@ -107,7 +107,7 @@ export function KeyValueFilterList({ { defaultMessage: 'Filter by value' } )} > - + {value} diff --git a/x-pack/plugins/apm/public/components/shared/kuery_bar/Typeahead/index.js b/x-pack/plugins/apm/public/components/shared/kuery_bar/Typeahead/index.js index f441497209c3..f8f51679a519 100644 --- a/x-pack/plugins/apm/public/components/shared/kuery_bar/Typeahead/index.js +++ b/x-pack/plugins/apm/public/components/shared/kuery_bar/Typeahead/index.js @@ -157,13 +157,8 @@ export class Typeahead extends Component { }; render() { - const { - disabled, - isLoading, - placeholder, - prepend, - suggestions, - } = this.props; + const { disabled, isLoading, placeholder, prepend, suggestions } = + this.props; return ( {} } } }, -} as unknown) as ApmPluginContextValue; +} as unknown as ApmPluginContextValue; export default { title: 'shared/LicensePrompt', @@ -36,6 +36,5 @@ export function Example({ } Example.args = { showBetaBadge: false, - text: - 'To create Feature name, you must be subscribed to an Elastic X license or above.', + text: 'To create Feature name, you must be subscribed to an Elastic X license or above.', } as ComponentProps; diff --git a/x-pack/plugins/apm/public/components/shared/managed_table/index.tsx b/x-pack/plugins/apm/public/components/shared/managed_table/index.tsx index 54f0aebbe818..f1776abe83e9 100644 --- a/x-pack/plugins/apm/public/components/shared/managed_table/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/managed_table/index.tsx @@ -149,7 +149,7 @@ function UnoptimizedManagedTable(props: Props) { } noItemsMessage={showNoItemsMessage} items={renderedItems} - columns={(columns as unknown) as Array>} // EuiBasicTableColumn is stricter than ITableColumn + columns={columns as unknown as Array>} // EuiBasicTableColumn is stricter than ITableColumn sorting={sort} onChange={onTableChange} {...(paginationProps ? { pagination: paginationProps } : {})} diff --git a/x-pack/plugins/apm/public/components/shared/service_icons/cloud_details.tsx b/x-pack/plugins/apm/public/components/shared/service_icons/cloud_details.tsx index 2e8fcfa1df67..2c706fa863a9 100644 --- a/x-pack/plugins/apm/public/components/shared/service_icons/cloud_details.tsx +++ b/x-pack/plugins/apm/public/components/shared/service_icons/cloud_details.tsx @@ -11,7 +11,8 @@ import { i18n } from '@kbn/i18n'; import React from 'react'; import { APIReturnType } from '../../../services/rest/createCallApmApi'; -type ServiceDetailsReturnType = APIReturnType<'GET /api/apm/services/{serviceName}/metadata/details'>; +type ServiceDetailsReturnType = + APIReturnType<'GET /api/apm/services/{serviceName}/metadata/details'>; interface Props { cloud: ServiceDetailsReturnType['cloud']; diff --git a/x-pack/plugins/apm/public/components/shared/service_icons/container_details.tsx b/x-pack/plugins/apm/public/components/shared/service_icons/container_details.tsx index b590a67409d9..75f7c23a7808 100644 --- a/x-pack/plugins/apm/public/components/shared/service_icons/container_details.tsx +++ b/x-pack/plugins/apm/public/components/shared/service_icons/container_details.tsx @@ -12,7 +12,8 @@ import React from 'react'; import { asInteger } from '../../../../common/utils/formatters'; import { APIReturnType } from '../../../services/rest/createCallApmApi'; -type ServiceDetailsReturnType = APIReturnType<'GET /api/apm/services/{serviceName}/metadata/details'>; +type ServiceDetailsReturnType = + APIReturnType<'GET /api/apm/services/{serviceName}/metadata/details'>; interface Props { container: ServiceDetailsReturnType['container']; diff --git a/x-pack/plugins/apm/public/components/shared/service_icons/index.test.tsx b/x-pack/plugins/apm/public/components/shared/service_icons/index.test.tsx index d00a8df6fb0a..bd90cae0277a 100644 --- a/x-pack/plugins/apm/public/components/shared/service_icons/index.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/service_icons/index.test.tsx @@ -29,9 +29,9 @@ const addWarning = jest.fn(); const httpGet = jest.fn(); function Wrapper({ children }: { children?: ReactNode }) { - const mockPluginContext = (merge({}, mockApmPluginContextValue, { + const mockPluginContext = merge({}, mockApmPluginContextValue, { core: { http: { get: httpGet }, notifications: { toasts: { addWarning } } }, - }) as unknown) as ApmPluginContextValue; + }) as unknown as ApmPluginContextValue; return ( @@ -179,13 +179,11 @@ describe('ServiceIcons', () => { }); describe('details', () => { - const callApmApi = (apisMockData: Record) => ({ - endpoint, - }: { - endpoint: string; - }) => { - return apisMockData[endpoint]; - }; + const callApmApi = + (apisMockData: Record) => + ({ endpoint }: { endpoint: string }) => { + return apisMockData[endpoint]; + }; it('Shows loading spinner while fetching data', () => { const apisMockData = { 'GET /api/apm/services/{serviceName}/metadata/icons': { diff --git a/x-pack/plugins/apm/public/components/shared/service_icons/index.tsx b/x-pack/plugins/apm/public/components/shared/service_icons/index.tsx index 82de85341c47..780c3b0222f1 100644 --- a/x-pack/plugins/apm/public/components/shared/service_icons/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/service_icons/index.tsx @@ -62,10 +62,8 @@ interface PopoverItem { } export function ServiceIcons({ start, end, serviceName }: Props) { - const [ - selectedIconPopover, - setSelectedIconPopover, - ] = useState(); + const [selectedIconPopover, setSelectedIconPopover] = + useState(); const theme = useTheme(); diff --git a/x-pack/plugins/apm/public/components/shared/service_icons/service_details.tsx b/x-pack/plugins/apm/public/components/shared/service_icons/service_details.tsx index 1828465fff45..daf253f6bc0a 100644 --- a/x-pack/plugins/apm/public/components/shared/service_icons/service_details.tsx +++ b/x-pack/plugins/apm/public/components/shared/service_icons/service_details.tsx @@ -11,7 +11,8 @@ import { i18n } from '@kbn/i18n'; import React from 'react'; import { APIReturnType } from '../../../services/rest/createCallApmApi'; -type ServiceDetailsReturnType = APIReturnType<'GET /api/apm/services/{serviceName}/metadata/details'>; +type ServiceDetailsReturnType = + APIReturnType<'GET /api/apm/services/{serviceName}/metadata/details'>; interface Props { service: ServiceDetailsReturnType['service']; diff --git a/x-pack/plugins/apm/public/components/shared/transaction_action_menu/TransactionActionMenu.test.tsx b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/TransactionActionMenu.test.tsx index 0b0d5c8b1b8a..fa2d3700eaf8 100644 --- a/x-pack/plugins/apm/public/components/shared/transaction_action_menu/TransactionActionMenu.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/TransactionActionMenu.test.tsx @@ -26,13 +26,13 @@ import { TransactionActionMenu } from './TransactionActionMenu'; import * as Transactions from './__fixtures__/mockData'; function getMockAPMContext({ canSave }: { canSave: boolean }) { - return ({ + return { ...mockApmPluginContextValue, core: { ...mockApmPluginContextValue.core, application: { capabilities: { apm: { save: canSave }, ml: {} } }, }, - } as unknown) as ApmPluginContextValue; + } as unknown as ApmPluginContextValue; } function Wrapper({ children }: { children?: React.ReactNode }) { @@ -374,10 +374,9 @@ describe('TransactionActionMenu component', () => { expectTextsInDocument(component, ['Create link']); const getFilterKeyValue = (key: string) => { return { - [(component.getAllByText(key)[0] as HTMLOptionElement) - .text]: (component.getAllByTestId( - `${key}.value` - )[0] as HTMLInputElement).value, + [(component.getAllByText(key)[0] as HTMLOptionElement).text]: ( + component.getAllByTestId(`${key}.value`)[0] as HTMLInputElement + ).value, }; }; expect(getFilterKeyValue('service.name')).toEqual({ diff --git a/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/CustomLinkToolbar.test.tsx b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/CustomLinkToolbar.test.tsx index 89924343df9e..ecef563e7294 100644 --- a/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/CustomLinkToolbar.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/CustomLinkToolbar.test.tsx @@ -20,13 +20,13 @@ import { import { CustomLinkToolbar } from './CustomLinkToolbar'; function getMockAPMContext({ canSave }: { canSave: boolean }) { - return ({ + return { ...mockApmPluginContextValue, core: { ...mockApmPluginContextValue.core, application: { capabilities: { apm: { save: canSave }, ml: {} } }, }, - } as unknown) as ApmPluginContextValue; + } as unknown as ApmPluginContextValue; } function Wrapper({ children }: { children?: ReactNode }) { diff --git a/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/custom_link_list.test.tsx b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/custom_link_list.test.tsx index e063fb36b8e9..9c1e85222389 100644 --- a/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/custom_link_list.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/custom_link_list.test.tsx @@ -24,9 +24,9 @@ describe('CustomLinkList', () => { url: 'http://elastic.co?service.name={{service.name}}', }, ] as CustomLink[]; - const transaction = ({ + const transaction = { service: { name: 'foo.bar' }, - } as unknown) as Transaction; + } as unknown as Transaction; it('shows links', () => { const component = render( diff --git a/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/index.test.tsx b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/index.test.tsx index a624c220a0e4..a9a57d2247c6 100644 --- a/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/index.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/index.test.tsx @@ -25,7 +25,7 @@ function Wrapper({ children }: { children?: ReactNode }) { ); } -const transaction = ({ +const transaction = { service: { name: 'name', environment: 'env', @@ -34,7 +34,7 @@ const transaction = ({ name: 'tx name', type: 'tx type', }, -} as unknown) as Transaction; +} as unknown as Transaction; describe('Custom links', () => { it('shows empty message when no custom link is available', () => { diff --git a/x-pack/plugins/apm/public/components/shared/transaction_action_menu/sections.test.ts b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/sections.test.ts index c2cfeb046134..bcb52f4721dd 100644 --- a/x-pack/plugins/apm/public/components/shared/transaction_action_menu/sections.test.ts +++ b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/sections.test.ts @@ -11,11 +11,11 @@ import { Transaction } from '../../../../typings/es_schemas/ui/transaction'; import { getSections } from './sections'; describe('Transaction action menu', () => { - const basePath = ({ + const basePath = { prepend: (url: string) => { return `some-basepath${url}`; }, - } as unknown) as IBasePath; + } as unknown as IBasePath; const date = '2020-02-06T11:00:00.000Z'; const timestamp = { us: new Date(date).getTime() }; @@ -26,18 +26,18 @@ describe('Transaction action menu', () => { refreshInterval: 0, }; - const location = ({ + const location = { search: '?rangeFrom=now-24h&rangeTo=now&refreshPaused=true&refreshInterval=0', - } as unknown) as Location; + } as unknown as Location; it('shows required sections only', () => { - const transaction = ({ + const transaction = { timestamp, trace: { id: '123' }, transaction: { id: '123' }, '@timestamp': date, - } as unknown) as Transaction; + } as unknown as Transaction; expect( getSections({ transaction, @@ -55,8 +55,7 @@ describe('Transaction action menu', () => { { key: 'traceLogs', label: 'Trace logs', - href: - 'some-basepath/app/logs/link-to/logs?time=1580986800&filter=trace.id:%22123%22%20OR%20%22123%22', + href: 'some-basepath/app/logs/link-to/logs?time=1580986800&filter=trace.id:%22123%22%20OR%20%22123%22', condition: true, }, ], @@ -69,8 +68,7 @@ describe('Transaction action menu', () => { { key: 'sampleDocument', label: 'View sample document', - href: - 'some-basepath/app/discover#/?_g=(refreshInterval:(pause:!t,value:0),time:(from:now-24h,to:now))&_a=(index:apm_static_index_pattern_id,interval:auto,query:(language:kuery,query:\'processor.event:"transaction" AND transaction.id:"123" AND trace.id:"123"\'))', + href: 'some-basepath/app/discover#/?_g=(refreshInterval:(pause:!t,value:0),time:(from:now-24h,to:now))&_a=(index:apm_static_index_pattern_id,interval:auto,query:(language:kuery,query:\'processor.event:"transaction" AND transaction.id:"123" AND trace.id:"123"\'))', condition: true, }, ], @@ -80,13 +78,13 @@ describe('Transaction action menu', () => { }); it('shows pod and required sections only', () => { - const transaction = ({ + const transaction = { kubernetes: { pod: { uid: '123' } }, timestamp, trace: { id: '123' }, transaction: { id: '123' }, '@timestamp': date, - } as unknown) as Transaction; + } as unknown as Transaction; expect( getSections({ transaction, @@ -105,15 +103,13 @@ describe('Transaction action menu', () => { { key: 'podLogs', label: 'Pod logs', - href: - 'some-basepath/app/logs/link-to/pod-logs/123?time=1580986800', + href: 'some-basepath/app/logs/link-to/pod-logs/123?time=1580986800', condition: true, }, { key: 'podMetrics', label: 'Pod metrics', - href: - 'some-basepath/app/metrics/link-to/pod-detail/123?from=1580986500000&to=1580987100000', + href: 'some-basepath/app/metrics/link-to/pod-detail/123?from=1580986500000&to=1580987100000', condition: true, }, ], @@ -126,8 +122,7 @@ describe('Transaction action menu', () => { { key: 'traceLogs', label: 'Trace logs', - href: - 'some-basepath/app/logs/link-to/logs?time=1580986800&filter=trace.id:%22123%22%20OR%20%22123%22', + href: 'some-basepath/app/logs/link-to/logs?time=1580986800&filter=trace.id:%22123%22%20OR%20%22123%22', condition: true, }, ], @@ -140,8 +135,7 @@ describe('Transaction action menu', () => { { key: 'sampleDocument', label: 'View sample document', - href: - 'some-basepath/app/discover#/?_g=(refreshInterval:(pause:!t,value:0),time:(from:now-24h,to:now))&_a=(index:apm_static_index_pattern_id,interval:auto,query:(language:kuery,query:\'processor.event:"transaction" AND transaction.id:"123" AND trace.id:"123"\'))', + href: 'some-basepath/app/discover#/?_g=(refreshInterval:(pause:!t,value:0),time:(from:now-24h,to:now))&_a=(index:apm_static_index_pattern_id,interval:auto,query:(language:kuery,query:\'processor.event:"transaction" AND transaction.id:"123" AND trace.id:"123"\'))', condition: true, }, ], @@ -151,13 +145,13 @@ describe('Transaction action menu', () => { }); it('shows host and required sections only', () => { - const transaction = ({ + const transaction = { host: { hostname: 'foo' }, timestamp, trace: { id: '123' }, transaction: { id: '123' }, '@timestamp': date, - } as unknown) as Transaction; + } as unknown as Transaction; expect( getSections({ transaction, @@ -175,15 +169,13 @@ describe('Transaction action menu', () => { { key: 'hostLogs', label: 'Host logs', - href: - 'some-basepath/app/logs/link-to/host-logs/foo?time=1580986800', + href: 'some-basepath/app/logs/link-to/host-logs/foo?time=1580986800', condition: true, }, { key: 'hostMetrics', label: 'Host metrics', - href: - 'some-basepath/app/metrics/link-to/host-detail/foo?from=1580986500000&to=1580987100000', + href: 'some-basepath/app/metrics/link-to/host-detail/foo?from=1580986500000&to=1580987100000', condition: true, }, ], @@ -196,8 +188,7 @@ describe('Transaction action menu', () => { { key: 'traceLogs', label: 'Trace logs', - href: - 'some-basepath/app/logs/link-to/logs?time=1580986800&filter=trace.id:%22123%22%20OR%20%22123%22', + href: 'some-basepath/app/logs/link-to/logs?time=1580986800&filter=trace.id:%22123%22%20OR%20%22123%22', condition: true, }, ], @@ -210,8 +201,7 @@ describe('Transaction action menu', () => { { key: 'sampleDocument', label: 'View sample document', - href: - 'some-basepath/app/discover#/?_g=(refreshInterval:(pause:!t,value:0),time:(from:now-24h,to:now))&_a=(index:apm_static_index_pattern_id,interval:auto,query:(language:kuery,query:\'processor.event:"transaction" AND transaction.id:"123" AND trace.id:"123"\'))', + href: 'some-basepath/app/discover#/?_g=(refreshInterval:(pause:!t,value:0),time:(from:now-24h,to:now))&_a=(index:apm_static_index_pattern_id,interval:auto,query:(language:kuery,query:\'processor.event:"transaction" AND transaction.id:"123" AND trace.id:"123"\'))', condition: true, }, ], diff --git a/x-pack/plugins/apm/public/components/shared/transactions_table/get_columns.tsx b/x-pack/plugins/apm/public/components/shared/transactions_table/get_columns.tsx index 24ad61f80b02..b11a2994f1ca 100644 --- a/x-pack/plugins/apm/public/components/shared/transactions_table/get_columns.tsx +++ b/x-pack/plugins/apm/public/components/shared/transactions_table/get_columns.tsx @@ -27,12 +27,14 @@ import { ListMetric } from '../list_metric'; import { TruncateWithTooltip } from '../truncate_with_tooltip'; import { getLatencyColumnLabel } from './get_latency_column_label'; -type TransactionGroupMainStatistics = APIReturnType<'GET /api/apm/services/{serviceName}/transactions/groups/main_statistics'>; +type TransactionGroupMainStatistics = + APIReturnType<'GET /api/apm/services/{serviceName}/transactions/groups/main_statistics'>; type ServiceTransactionGroupItem = ValuesType< TransactionGroupMainStatistics['transactionGroups'] >; -type TransactionGroupDetailedStatistics = APIReturnType<'GET /api/apm/services/{serviceName}/transactions/groups/detailed_statistics'>; +type TransactionGroupDetailedStatistics = + APIReturnType<'GET /api/apm/services/{serviceName}/transactions/groups/detailed_statistics'>; export function getColumns({ serviceName, diff --git a/x-pack/plugins/apm/public/components/shared/transactions_table/index.tsx b/x-pack/plugins/apm/public/components/shared/transactions_table/index.tsx index 60612b581e1d..6f91684de0ee 100644 --- a/x-pack/plugins/apm/public/components/shared/transactions_table/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/transactions_table/index.tsx @@ -29,7 +29,8 @@ import { getColumns } from './get_columns'; import { ElasticDocsLink } from '../Links/ElasticDocsLink'; import { useBreakpoints } from '../../../hooks/use_breakpoints'; -type ApiResponse = APIReturnType<'GET /api/apm/services/{serviceName}/transactions/groups/main_statistics'>; +type ApiResponse = + APIReturnType<'GET /api/apm/services/{serviceName}/transactions/groups/main_statistics'>; interface InitialState { requestId: string; diff --git a/x-pack/plugins/apm/public/context/apm_service/use_service_agent_fetcher.ts b/x-pack/plugins/apm/public/context/apm_service/use_service_agent_fetcher.ts index 3723fcaba2a4..e30fd962e5a9 100644 --- a/x-pack/plugins/apm/public/context/apm_service/use_service_agent_fetcher.ts +++ b/x-pack/plugins/apm/public/context/apm_service/use_service_agent_fetcher.ts @@ -21,7 +21,11 @@ export function useServiceAgentFetcher({ start: string; end: string; }) { - const { data = INITIAL_STATE, error, status } = useFetcher( + const { + data = INITIAL_STATE, + error, + status, + } = useFetcher( (callApmApi) => { if (serviceName) { return callApmApi({ diff --git a/x-pack/plugins/apm/public/context/url_params_context/url_params_context.test.tsx b/x-pack/plugins/apm/public/context/url_params_context/url_params_context.test.tsx index 1d5c43f7e005..be4b8f046ac7 100644 --- a/x-pack/plugins/apm/public/context/url_params_context/url_params_context.test.tsx +++ b/x-pack/plugins/apm/public/context/url_params_context/url_params_context.test.tsx @@ -100,12 +100,12 @@ describe('UrlParamsContext', () => { it('should refresh the time range with new values', async () => { const calls = []; - const history = ({ + const history = { location: { pathname: '/test', }, listen: jest.fn(), - } as unknown) as History; + } as unknown as History; const wrapper = mount( @@ -151,12 +151,12 @@ describe('UrlParamsContext', () => { }); it('should refresh the time range with new values if time range is relative', async () => { - const history = ({ + const history = { location: { pathname: '/test', }, listen: jest.fn(), - } as unknown) as History; + } as unknown as History; jest .spyOn(Date, 'now') diff --git a/x-pack/plugins/apm/public/context/url_params_context/url_params_context.tsx b/x-pack/plugins/apm/public/context/url_params_context/url_params_context.tsx index 7a71f8b78d28..e7a5e072ff80 100644 --- a/x-pack/plugins/apm/public/context/url_params_context/url_params_context.tsx +++ b/x-pack/plugins/apm/public/context/url_params_context/url_params_context.tsx @@ -55,14 +55,8 @@ const UrlParamsProvider: React.ComponentClass<{}> = withRouter( ({ location, children }) => { const refUrlParams = useRef(resolveUrlParams(location, {})); - const { - start, - end, - rangeFrom, - rangeTo, - exactStart, - exactEnd, - } = refUrlParams.current; + const { start, end, rangeFrom, rangeTo, exactStart, exactEnd } = + refUrlParams.current; // Counter to force an update in useFetcher when the refresh button is clicked. const [rangeId, setRangeId] = useState(0); diff --git a/x-pack/plugins/apm/public/hooks/use_apm_router.ts b/x-pack/plugins/apm/public/hooks/use_apm_router.ts index c0ccc37cc897..9b2adfbd1c98 100644 --- a/x-pack/plugins/apm/public/hooks/use_apm_router.ts +++ b/x-pack/plugins/apm/public/hooks/use_apm_router.ts @@ -19,8 +19,8 @@ export function useApmRouter() { return core.http.basePath.prepend('/app/apm' + router.link(...args)); }; - return ({ + return { ...router, link, - } as unknown) as ApmRouter; + } as unknown as ApmRouter; } diff --git a/x-pack/plugins/apm/public/hooks/use_fetcher.test.tsx b/x-pack/plugins/apm/public/hooks/use_fetcher.test.tsx index 1007caa3155e..79eed2b27cd6 100644 --- a/x-pack/plugins/apm/public/hooks/use_fetcher.test.tsx +++ b/x-pack/plugins/apm/public/hooks/use_fetcher.test.tsx @@ -13,9 +13,9 @@ import { delay } from '../utils/testHelpers'; import { FetcherResult, useFetcher } from './use_fetcher'; // Wrap the hook with a provider so it can useKibana -const KibanaReactContext = createKibanaReactContext(({ +const KibanaReactContext = createKibanaReactContext({ notifications: { toasts: { add: () => {}, danger: () => {} } }, -} as unknown) as Partial); +} as unknown as Partial); interface WrapperProps { children?: ReactNode; diff --git a/x-pack/plugins/apm/public/hooks/use_search_strategy.ts b/x-pack/plugins/apm/public/hooks/use_search_strategy.ts index c01196e23c6c..32fc31ad80fe 100644 --- a/x-pack/plugins/apm/public/hooks/use_search_strategy.ts +++ b/x-pack/plugins/apm/public/hooks/use_search_strategy.ts @@ -59,10 +59,12 @@ const getInitialProgress = (): SearchStrategyProgress => ({ total: 100, }); -const getReducer = () => (prev: T, update: Partial): T => ({ - ...prev, - ...update, -}); +const getReducer = + () => + (prev: T, update: Partial): T => ({ + ...prev, + ...update, + }); interface SearchStrategyReturnBase { progress: SearchStrategyProgress; @@ -166,7 +168,7 @@ export function useSearchStrategy< } else if (isErrorResponse(response)) { searchSubscription$.current?.unsubscribe(); setFetchState({ - error: (response as unknown) as Error, + error: response as unknown as Error, isRunning: false, }); } diff --git a/x-pack/plugins/apm/public/hooks/use_service_metric_charts_fetcher.ts b/x-pack/plugins/apm/public/hooks/use_service_metric_charts_fetcher.ts index 28e8a4e0396a..82338d45a413 100644 --- a/x-pack/plugins/apm/public/hooks/use_service_metric_charts_fetcher.ts +++ b/x-pack/plugins/apm/public/hooks/use_service_metric_charts_fetcher.ts @@ -32,7 +32,11 @@ export function useServiceMetricChartsFetcher({ const { start, end } = useTimeRange({ rangeFrom, rangeTo }); const { agentName, serviceName } = useApmServiceContext(); - const { data = INITIAL_DATA, error, status } = useFetcher( + const { + data = INITIAL_DATA, + error, + status, + } = useFetcher( (callApmApi) => { if (serviceName && start && end && agentName) { return callApmApi({ diff --git a/x-pack/plugins/apm/public/hooks/use_transaction_trace_samples_fetcher.ts b/x-pack/plugins/apm/public/hooks/use_transaction_trace_samples_fetcher.ts index f7a6e6c3a80a..5279c7ce143f 100644 --- a/x-pack/plugins/apm/public/hooks/use_transaction_trace_samples_fetcher.ts +++ b/x-pack/plugins/apm/public/hooks/use_transaction_trace_samples_fetcher.ts @@ -42,7 +42,11 @@ export function useTransactionTraceSamplesFetcher({ urlParams: { transactionId, traceId, sampleRangeFrom, sampleRangeTo }, } = useUrlParams(); - const { data = INITIAL_DATA, status, error } = useFetcher( + const { + data = INITIAL_DATA, + status, + error, + } = useFetcher( async (callApmApi) => { if (serviceName && start && end && transactionType && transactionName) { const response = await callApmApi({ diff --git a/x-pack/plugins/apm/public/selectors/latency_chart_selectors.ts b/x-pack/plugins/apm/public/selectors/latency_chart_selectors.ts index a84a4abfe581..1fb4eb51dd77 100644 --- a/x-pack/plugins/apm/public/selectors/latency_chart_selectors.ts +++ b/x-pack/plugins/apm/public/selectors/latency_chart_selectors.ts @@ -13,7 +13,8 @@ import { asDuration } from '../../common/utils/formatters'; import { APMChartSpec, Coordinate } from '../../typings/timeseries'; import { APIReturnType } from '../services/rest/createCallApmApi'; -export type LatencyChartsResponse = APIReturnType<'GET /api/apm/services/{serviceName}/transactions/charts/latency'>; +export type LatencyChartsResponse = + APIReturnType<'GET /api/apm/services/{serviceName}/transactions/charts/latency'>; export interface LatencyChartData { currentPeriod?: APMChartSpec; diff --git a/x-pack/plugins/apm/public/services/callApi.test.ts b/x-pack/plugins/apm/public/services/callApi.test.ts index 5f0be1b6fadb..82be0bbf5dfc 100644 --- a/x-pack/plugins/apm/public/services/callApi.test.ts +++ b/x-pack/plugins/apm/public/services/callApi.test.ts @@ -19,14 +19,14 @@ describe('callApi', () => { let core: CoreMock; beforeEach(() => { - core = ({ + core = { http: { get: jest.fn().mockReturnValue({ my_key: 'hello_world', }), }, uiSettings: { get: () => false }, // disable `observability:enableInspectEsQueries` setting - } as unknown) as CoreMock; + } as unknown as CoreMock; }); afterEach(() => { diff --git a/x-pack/plugins/apm/public/services/rest/callApi.ts b/x-pack/plugins/apm/public/services/rest/callApi.ts index f623872303c5..53ddbed90413 100644 --- a/x-pack/plugins/apm/public/services/rest/callApi.ts +++ b/x-pack/plugins/apm/public/services/rest/callApi.ts @@ -53,10 +53,11 @@ export async function callApi( return cacheResponse; } - const { pathname, method = 'get', ...options } = fetchOptionsWithDebug( - fetchOptions, - inspectableEsQueriesEnabled - ); + const { + pathname, + method = 'get', + ...options + } = fetchOptionsWithDebug(fetchOptions, inspectableEsQueriesEnabled); const lowercaseMethod = method.toLowerCase() as | 'get' diff --git a/x-pack/plugins/apm/public/services/rest/callApmApiSpy.ts b/x-pack/plugins/apm/public/services/rest/callApmApiSpy.ts index ba9f740e06d0..d6ffd330f08b 100644 --- a/x-pack/plugins/apm/public/services/rest/callApmApiSpy.ts +++ b/x-pack/plugins/apm/public/services/rest/callApmApiSpy.ts @@ -16,9 +16,9 @@ export type CallApmApiSpy = jest.SpyInstance< export type CreateCallApmApiSpy = jest.SpyInstance; export const getCreateCallApmApiSpy = () => - (jest.spyOn( + jest.spyOn( createCallApmApi, 'createCallApmApi' - ) as unknown) as CreateCallApmApiSpy; + ) as unknown as CreateCallApmApiSpy; export const getCallApmApiSpy = () => - (jest.spyOn(createCallApmApi, 'callApmApi') as unknown) as CallApmApiSpy; + jest.spyOn(createCallApmApi, 'callApmApi') as unknown as CallApmApiSpy; diff --git a/x-pack/plugins/apm/public/services/rest/createCallApmApi.ts b/x-pack/plugins/apm/public/services/rest/createCallApmApi.ts index 40713f93d3ee..0dda1fc56dd2 100644 --- a/x-pack/plugins/apm/public/services/rest/createCallApmApi.ts +++ b/x-pack/plugins/apm/public/services/rest/createCallApmApi.ts @@ -54,9 +54,8 @@ export type APIReturnType = ReturnOf< _inspect?: InspectResponse; }; -export type APIClientRequestParamsOf< - TEndpoint extends APIEndpoint -> = ClientRequestParamsOf; +export type APIClientRequestParamsOf = + ClientRequestParamsOf; export type AbstractAPMRepository = ServerRouteRepository< APMRouteHandlerResources, @@ -81,7 +80,7 @@ export let callApmApi: APMClient = () => { export function createCallApmApi(core: CoreStart | CoreSetup) { callApmApi = ((options) => { const { endpoint, ...opts } = options; - const { params } = (options as unknown) as { + const { params } = options as unknown as { params?: Partial>; }; diff --git a/x-pack/plugins/apm/public/tutorial/config_agent/config_agent.stories.tsx b/x-pack/plugins/apm/public/tutorial/config_agent/config_agent.stories.tsx index 5ac5fa4d1071..166839390bc2 100644 --- a/x-pack/plugins/apm/public/tutorial/config_agent/config_agent.stories.tsx +++ b/x-pack/plugins/apm/public/tutorial/config_agent/config_agent.stories.tsx @@ -51,7 +51,7 @@ function Wrapper({ hasCloudPolicyWithApmIntegration, isFleetEnabled, }: Args) { - const http = ({ + const http = { get: () => ({ fleetAgents: [ ...(hasFleetPoliciesWithApmIntegration ? fleetAgents : []), @@ -65,7 +65,7 @@ function Wrapper({ secretToken: 'foo', }, }), - } as unknown) as HttpStart; + } as unknown as HttpStart; return ( { { { { { { fleetAgents, isFleetEnabled: true, }), - } as unknown) as HttpStart + } as unknown as HttpStart } basePath="http://localhost:5601" isCloudEnabled @@ -224,7 +224,7 @@ describe('TutorialConfigAgent', () => { { fleetAgents: [...fleetAgents, policyElasticAgentOnCloudAgent], isFleetEnabled: true, }), - } as unknown) as HttpStart + } as unknown as HttpStart } basePath="http://localhost:5601" isCloudEnabled @@ -263,11 +263,11 @@ describe('TutorialConfigAgent', () => { { throw new Error('Boom'); }, - } as unknown) as HttpStart + } as unknown as HttpStart } basePath="http://localhost:5601" isCloudEnabled @@ -296,13 +296,13 @@ describe('TutorialConfigAgent', () => { { { { fleetAgents: [], isFleetEnabled: false, }), - } as unknown) as HttpStart + } as unknown as HttpStart } basePath="http://localhost:5601" isCloudEnabled diff --git a/x-pack/plugins/apm/public/tutorial/tutorial_fleet_instructions/tutorial_fleet_instructions.stories.tsx b/x-pack/plugins/apm/public/tutorial/tutorial_fleet_instructions/tutorial_fleet_instructions.stories.tsx index 40b72f06654f..d826ca81416e 100644 --- a/x-pack/plugins/apm/public/tutorial/tutorial_fleet_instructions/tutorial_fleet_instructions.stories.tsx +++ b/x-pack/plugins/apm/public/tutorial/tutorial_fleet_instructions/tutorial_fleet_instructions.stories.tsx @@ -15,9 +15,9 @@ interface Args { } function Wrapper({ hasFleetPoliciesWithApmIntegration }: Args) { - const http = ({ + const http = { get: () => ({ hasData: hasFleetPoliciesWithApmIntegration }), - } as unknown) as HttpStart; + } as unknown as HttpStart; return ( , @@ -50,7 +50,7 @@ export function getEsClient({ // @ts-expect-error client.search = search; - return (client as unknown) as Omit & { + return client as unknown as Omit & { search: typeof search; }; } diff --git a/x-pack/plugins/apm/scripts/upload-telemetry-data/index.ts b/x-pack/plugins/apm/scripts/upload-telemetry-data/index.ts index 25554eeeaf81..0dab75cfba9c 100644 --- a/x-pack/plugins/apm/scripts/upload-telemetry-data/index.ts +++ b/x-pack/plugins/apm/scripts/upload-telemetry-data/index.ts @@ -76,7 +76,7 @@ async function uploadData() { const sampleDocuments = await generateSampleDocuments({ collectTelemetryParams: { - logger: (console as unknown) as Logger, + logger: console as unknown as Logger, indices: { ...config, apmCustomLinkIndex: '.apm-custom-links', diff --git a/x-pack/plugins/apm/server/lib/alerts/alerting_es_client.ts b/x-pack/plugins/apm/server/lib/alerts/alerting_es_client.ts index 8b4d3e2186c8..9445a0f0610f 100644 --- a/x-pack/plugins/apm/server/lib/alerts/alerting_es_client.ts +++ b/x-pack/plugins/apm/server/lib/alerts/alerting_es_client.ts @@ -27,5 +27,5 @@ export async function alertingEsClient({ ignore_unavailable: true, }); - return (response.body as unknown) as ESSearchResponse; + return response.body as unknown as ESSearchResponse; } diff --git a/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_duration.ts b/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_duration.ts index 8e3a44d78063..b18d3ac25a93 100644 --- a/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_duration.ts +++ b/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_duration.ts @@ -58,9 +58,10 @@ export async function getTransactionDurationChartPreview({ }, }; - const transactionDurationField = getTransactionDurationFieldForAggregatedTransactions( - searchAggregatedTransactions - ); + const transactionDurationField = + getTransactionDurationFieldForAggregatedTransactions( + searchAggregatedTransactions + ); const aggs = { timeseries: { diff --git a/x-pack/plugins/apm/server/lib/alerts/register_error_count_alert_type.test.ts b/x-pack/plugins/apm/server/lib/alerts/register_error_count_alert_type.test.ts index 5758dea1860b..2d98c09096f5 100644 --- a/x-pack/plugins/apm/server/lib/alerts/register_error_count_alert_type.test.ts +++ b/x-pack/plugins/apm/server/lib/alerts/register_error_count_alert_type.test.ts @@ -43,12 +43,8 @@ describe('Error count alert', () => { }); it('sends alerts with service name and environment for those that exceeded the threshold', async () => { - const { - services, - dependencies, - executor, - scheduleActions, - } = createRuleTypeMocks(); + const { services, dependencies, executor, scheduleActions } = + createRuleTypeMocks(); registerErrorCountAlertType(dependencies); diff --git a/x-pack/plugins/apm/server/lib/alerts/register_error_count_alert_type.ts b/x-pack/plugins/apm/server/lib/alerts/register_error_count_alert_type.ts index c78c24fba867..d1026b0b6ca8 100644 --- a/x-pack/plugins/apm/server/lib/alerts/register_error_count_alert_type.ts +++ b/x-pack/plugins/apm/server/lib/alerts/register_error_count_alert_type.ts @@ -42,8 +42,10 @@ import { apmActionVariables } from './action_variables'; import { alertingEsClient } from './alerting_es_client'; import { RegisterRuleDependencies } from './register_apm_alerts'; -const ALERT_EVALUATION_THRESHOLD: typeof ALERT_EVALUATION_THRESHOLD_TYPED = ALERT_EVALUATION_THRESHOLD_NON_TYPED; -const ALERT_EVALUATION_VALUE: typeof ALERT_EVALUATION_VALUE_TYPED = ALERT_EVALUATION_VALUE_NON_TYPED; +const ALERT_EVALUATION_THRESHOLD: typeof ALERT_EVALUATION_THRESHOLD_TYPED = + ALERT_EVALUATION_THRESHOLD_NON_TYPED; +const ALERT_EVALUATION_VALUE: typeof ALERT_EVALUATION_VALUE_TYPED = + ALERT_EVALUATION_VALUE_NON_TYPED; const ALERT_REASON: typeof ALERT_REASON_TYPED = ALERT_REASON_NON_TYPED; const paramsSchema = schema.object({ diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.test.ts b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.test.ts index 43abe89a4733..956347098d78 100644 --- a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.test.ts +++ b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.test.ts @@ -12,12 +12,8 @@ import { elasticsearchClientMock } from 'src/core/server/elasticsearch/client/mo describe('registerTransactionDurationAlertType', () => { it('sends alert when value is greater than threashold', async () => { - const { - services, - dependencies, - executor, - scheduleActions, - } = createRuleTypeMocks(); + const { services, dependencies, executor, scheduleActions } = + createRuleTypeMocks(); registerTransactionDurationAlertType(dependencies); diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts index a831f94cd6b6..b383b4777eca 100644 --- a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts +++ b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts @@ -49,8 +49,10 @@ import { apmActionVariables } from './action_variables'; import { alertingEsClient } from './alerting_es_client'; import { RegisterRuleDependencies } from './register_apm_alerts'; -const ALERT_EVALUATION_THRESHOLD: typeof ALERT_EVALUATION_THRESHOLD_TYPED = ALERT_EVALUATION_THRESHOLD_NON_TYPED; -const ALERT_EVALUATION_VALUE: typeof ALERT_EVALUATION_VALUE_TYPED = ALERT_EVALUATION_VALUE_NON_TYPED; +const ALERT_EVALUATION_THRESHOLD: typeof ALERT_EVALUATION_THRESHOLD_TYPED = + ALERT_EVALUATION_THRESHOLD_NON_TYPED; +const ALERT_EVALUATION_VALUE: typeof ALERT_EVALUATION_VALUE_TYPED = + ALERT_EVALUATION_VALUE_NON_TYPED; const ALERT_REASON: typeof ALERT_REASON_TYPED = ALERT_REASON_NON_TYPED; const paramsSchema = schema.object({ @@ -186,9 +188,8 @@ export function registerTransactionDurationAlertType({ if (transactionDuration && transactionDuration > thresholdMicroseconds) { const durationFormatter = getDurationFormatter(transactionDuration); - const transactionDurationFormatted = durationFormatter( - transactionDuration - ).formatted; + const transactionDurationFormatted = + durationFormatter(transactionDuration).formatted; services .alertWithLifecycle({ diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.test.ts b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.test.ts index ad1a8fcbf6e5..fa4125c54126 100644 --- a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.test.ts +++ b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.test.ts @@ -41,10 +41,10 @@ describe('Transaction duration anomaly alert', () => { const { services, dependencies, executor } = createRuleTypeMocks(); - const ml = ({ + const ml = { mlSystemProvider: () => ({ mlAnomalySearch: jest.fn() }), anomalyDetectorsProvider: jest.fn(), - } as unknown) as MlPluginSetup; + } as unknown as MlPluginSetup; registerTransactionDurationAnomalyAlertType({ ...dependencies, @@ -63,7 +63,7 @@ describe('Transaction duration anomaly alert', () => { it('anomaly is less than threshold', async () => { jest.spyOn(GetServiceAnomalies, 'getMLJobs').mockReturnValue( - Promise.resolve(([ + Promise.resolve([ { job_id: '1', custom_settings: { job_tags: { environment: 'development' } }, @@ -72,12 +72,12 @@ describe('Transaction duration anomaly alert', () => { job_id: '2', custom_settings: { job_tags: { environment: 'production' } }, }, - ] as unknown) as Job[]) + ] as unknown as Job[]) ); const { services, dependencies, executor } = createRuleTypeMocks(); - const ml = ({ + const ml = { mlSystemProvider: () => ({ mlAnomalySearch: () => ({ aggregations: { @@ -95,7 +95,7 @@ describe('Transaction duration anomaly alert', () => { }), }), anomalyDetectorsProvider: jest.fn(), - } as unknown) as MlPluginSetup; + } as unknown as MlPluginSetup; registerTransactionDurationAnomalyAlertType({ ...dependencies, @@ -116,7 +116,7 @@ describe('Transaction duration anomaly alert', () => { describe('sends alert', () => { it('for all services that exceeded the threshold', async () => { jest.spyOn(GetServiceAnomalies, 'getMLJobs').mockReturnValue( - Promise.resolve(([ + Promise.resolve([ { job_id: '1', custom_settings: { job_tags: { environment: 'development' } }, @@ -125,17 +125,13 @@ describe('Transaction duration anomaly alert', () => { job_id: '2', custom_settings: { job_tags: { environment: 'production' } }, }, - ] as unknown) as Job[]) + ] as unknown as Job[]) ); - const { - services, - dependencies, - executor, - scheduleActions, - } = createRuleTypeMocks(); + const { services, dependencies, executor, scheduleActions } = + createRuleTypeMocks(); - const ml = ({ + const ml = { mlSystemProvider: () => ({ mlAnomalySearch: () => ({ aggregations: { @@ -175,7 +171,7 @@ describe('Transaction duration anomaly alert', () => { }), }), anomalyDetectorsProvider: jest.fn(), - } as unknown) as MlPluginSetup; + } as unknown as MlPluginSetup; registerTransactionDurationAnomalyAlertType({ ...dependencies, diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.ts b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.ts index 7d49833c01ab..08203646d900 100644 --- a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.ts +++ b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.ts @@ -47,8 +47,10 @@ import { getEnvironmentLabel, } from '../../../common/environment_filter_values'; -const ALERT_EVALUATION_THRESHOLD: typeof ALERT_EVALUATION_THRESHOLD_TYPED = ALERT_EVALUATION_THRESHOLD_NON_TYPED; -const ALERT_EVALUATION_VALUE: typeof ALERT_EVALUATION_VALUE_TYPED = ALERT_EVALUATION_VALUE_NON_TYPED; +const ALERT_EVALUATION_THRESHOLD: typeof ALERT_EVALUATION_THRESHOLD_TYPED = + ALERT_EVALUATION_THRESHOLD_NON_TYPED; +const ALERT_EVALUATION_VALUE: typeof ALERT_EVALUATION_VALUE_TYPED = + ALERT_EVALUATION_VALUE_NON_TYPED; const ALERT_SEVERITY: typeof ALERT_SEVERITY_TYPED = ALERT_SEVERITY_NON_TYPED; const ALERT_REASON: typeof ALERT_REASON_TYPED = ALERT_REASON_NON_TYPED; @@ -206,10 +208,8 @@ export function registerTransactionDurationAnomalyAlertType({ }, }; - const response: ESSearchResponse< - unknown, - typeof anomalySearchParams - > = (await mlAnomalySearch(anomalySearchParams, [])) as any; + const response: ESSearchResponse = + (await mlAnomalySearch(anomalySearchParams, [])) as any; const anomalies = response.aggregations?.anomaly_groups.buckets diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_error_rate_alert_type.test.ts b/x-pack/plugins/apm/server/lib/alerts/register_transaction_error_rate_alert_type.test.ts index be5f4705482d..b0a99377c298 100644 --- a/x-pack/plugins/apm/server/lib/alerts/register_transaction_error_rate_alert_type.test.ts +++ b/x-pack/plugins/apm/server/lib/alerts/register_transaction_error_rate_alert_type.test.ts @@ -50,12 +50,8 @@ describe('Transaction error rate alert', () => { }); it('sends alerts for services that exceeded the threshold', async () => { - const { - services, - dependencies, - executor, - scheduleActions, - } = createRuleTypeMocks(); + const { services, dependencies, executor, scheduleActions } = + createRuleTypeMocks(); registerTransactionErrorRateAlertType({ ...dependencies, diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_error_rate_alert_type.ts b/x-pack/plugins/apm/server/lib/alerts/register_transaction_error_rate_alert_type.ts index 1671b15143be..6c59bcc4107b 100644 --- a/x-pack/plugins/apm/server/lib/alerts/register_transaction_error_rate_alert_type.ts +++ b/x-pack/plugins/apm/server/lib/alerts/register_transaction_error_rate_alert_type.ts @@ -49,8 +49,10 @@ import { SearchAggregatedTransactionSetting } from '../../../common/aggregated_t import { getDocumentTypeFilterForAggregatedTransactions } from '../helpers/aggregated_transactions'; import { asPercent } from '../../../../observability/common/utils/formatters'; -const ALERT_EVALUATION_THRESHOLD: typeof ALERT_EVALUATION_THRESHOLD_TYPED = ALERT_EVALUATION_THRESHOLD_NON_TYPED; -const ALERT_EVALUATION_VALUE: typeof ALERT_EVALUATION_VALUE_TYPED = ALERT_EVALUATION_VALUE_NON_TYPED; +const ALERT_EVALUATION_THRESHOLD: typeof ALERT_EVALUATION_THRESHOLD_TYPED = + ALERT_EVALUATION_THRESHOLD_NON_TYPED; +const ALERT_EVALUATION_VALUE: typeof ALERT_EVALUATION_VALUE_TYPED = + ALERT_EVALUATION_VALUE_NON_TYPED; const ALERT_REASON: typeof ALERT_REASON_TYPED = ALERT_REASON_NON_TYPED; const paramsSchema = schema.object({ @@ -213,12 +215,8 @@ export function registerTransactionErrorRateAlertType({ .filter((result) => result.errorRate >= alertParams.threshold); results.forEach((result) => { - const { - serviceName, - environment, - transactionType, - errorRate, - } = result; + const { serviceName, environment, transactionType, errorRate } = + result; services .alertWithLifecycle({ diff --git a/x-pack/plugins/apm/server/lib/alerts/test_utils/index.ts b/x-pack/plugins/apm/server/lib/alerts/test_utils/index.ts index c78e93815bf8..5d5865bdd228 100644 --- a/x-pack/plugins/apm/server/lib/alerts/test_utils/index.ts +++ b/x-pack/plugins/apm/server/lib/alerts/test_utils/index.ts @@ -23,11 +23,11 @@ export const createRuleTypeMocks = () => { /* eslint-enable @typescript-eslint/naming-convention */ } as APMConfig); - const loggerMock = ({ + const loggerMock = { debug: jest.fn(), warn: jest.fn(), error: jest.fn(), - } as unknown) as Logger; + } as unknown as Logger; const alerting = { registerType: ({ executor }) => { diff --git a/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts b/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts index fd341565c235..d624c8527df8 100644 --- a/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts +++ b/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts @@ -1094,10 +1094,9 @@ export const tasks: TelemetryTask[] = [ geo: { country_iso_code: { rum: { - '1d': - rumAgentCardinalityResponse.aggregations?.[ - CLIENT_GEO_COUNTRY_ISO_CODE - ].value, + '1d': rumAgentCardinalityResponse.aggregations?.[ + CLIENT_GEO_COUNTRY_ISO_CODE + ].value, }, }, }, @@ -1105,30 +1104,28 @@ export const tasks: TelemetryTask[] = [ transaction: { name: { all_agents: { - '1d': - allAgentsCardinalityResponse.aggregations?.[TRANSACTION_NAME] - .value, + '1d': allAgentsCardinalityResponse.aggregations?.[ + TRANSACTION_NAME + ].value, }, rum: { - '1d': - rumAgentCardinalityResponse.aggregations?.[TRANSACTION_NAME] - .value, + '1d': rumAgentCardinalityResponse.aggregations?.[ + TRANSACTION_NAME + ].value, }, }, }, user_agent: { original: { all_agents: { - '1d': - allAgentsCardinalityResponse.aggregations?.[ - USER_AGENT_ORIGINAL - ].value, + '1d': allAgentsCardinalityResponse.aggregations?.[ + USER_AGENT_ORIGINAL + ].value, }, rum: { - '1d': - rumAgentCardinalityResponse.aggregations?.[ - USER_AGENT_ORIGINAL - ].value, + '1d': rumAgentCardinalityResponse.aggregations?.[ + USER_AGENT_ORIGINAL + ].value, }, }, }, diff --git a/x-pack/plugins/apm/server/lib/apm_telemetry/schema.ts b/x-pack/plugins/apm/server/lib/apm_telemetry/schema.ts index 80be1ecbe13a..76c897dec569 100644 --- a/x-pack/plugins/apm/server/lib/apm_telemetry/schema.ts +++ b/x-pack/plugins/apm/server/lib/apm_telemetry/schema.ts @@ -17,10 +17,11 @@ import { ElasticAgentName } from '../../../typings/es_schemas/ui/fields/agent'; const long: { type: 'long' } = { type: 'long' }; -const aggregatedTransactionCountSchema: MakeSchemaFrom = { - expected_metric_document_count: long, - transaction_count: long, -}; +const aggregatedTransactionCountSchema: MakeSchemaFrom = + { + expected_metric_document_count: long, + transaction_count: long, + }; const timeframeMap1dSchema: MakeSchemaFrom = { '1d': long, diff --git a/x-pack/plugins/apm/server/lib/fleet/get_agents.ts b/x-pack/plugins/apm/server/lib/fleet/get_agents.ts index 5ee44bb3ad17..86a6294e96b0 100644 --- a/x-pack/plugins/apm/server/lib/fleet/get_agents.ts +++ b/x-pack/plugins/apm/server/lib/fleet/get_agents.ts @@ -23,9 +23,8 @@ export async function getFleetAgents({ fleetPluginStart: NonNullable; }) { // @ts-ignore - const savedObjectsClient: SavedObjectsClientContract = await getInternalSavedObjectsClient( - core.setup - ); + const savedObjectsClient: SavedObjectsClientContract = + await getInternalSavedObjectsClient(core.setup); return await fleetPluginStart.agentPolicyService.getByIds( savedObjectsClient, diff --git a/x-pack/plugins/apm/server/lib/fleet/get_apm_package_policies.ts b/x-pack/plugins/apm/server/lib/fleet/get_apm_package_policies.ts index 363ed77d56c4..5128339368f4 100644 --- a/x-pack/plugins/apm/server/lib/fleet/get_apm_package_policies.ts +++ b/x-pack/plugins/apm/server/lib/fleet/get_apm_package_policies.ts @@ -21,9 +21,8 @@ export async function getApmPackgePolicies({ fleetPluginStart: NonNullable; }) { // @ts-ignore - const savedObjectsClient: SavedObjectsClientContract = await getInternalSavedObjectsClient( - core.setup - ); + const savedObjectsClient: SavedObjectsClientContract = + await getInternalSavedObjectsClient(core.setup); return await fleetPluginStart.packagePolicyService.list(savedObjectsClient, { kuery: 'ingest-package-policies.package.name:apm', }); diff --git a/x-pack/plugins/apm/server/lib/fleet/get_apm_package_policy_definition.ts b/x-pack/plugins/apm/server/lib/fleet/get_apm_package_policy_definition.ts index afe3a95d7902..64b071b67d2b 100644 --- a/x-pack/plugins/apm/server/lib/fleet/get_apm_package_policy_definition.ts +++ b/x-pack/plugins/apm/server/lib/fleet/get_apm_package_policy_definition.ts @@ -72,20 +72,18 @@ function preprocessLegacyFields({ function getApmPackageInputVars(options: GetApmPackagePolicyDefinitionOptions) { const { apmServerSchema } = options; - const apmServerConfigs = Object.entries( - apmConfigMapping - ).map(([key, { name, type, getValue }]) => ({ key, name, type, getValue })); + const apmServerConfigs = Object.entries(apmConfigMapping).map( + ([key, { name, type, getValue }]) => ({ key, name, type, getValue }) + ); - const inputVars: Record< - string, - { type: string; value: any } - > = apmServerConfigs.reduce((acc, { key, name, type, getValue }) => { - const value = (getValue ? getValue(options) : apmServerSchema[key]) ?? ''; // defaults to an empty string to be edited in Fleet UI - return { - ...acc, - [name]: { type, value }, - }; - }, {}); + const inputVars: Record = + apmServerConfigs.reduce((acc, { key, name, type, getValue }) => { + const value = (getValue ? getValue(options) : apmServerSchema[key]) ?? ''; // defaults to an empty string to be edited in Fleet UI + return { + ...acc, + [name]: { type, value }, + }; + }, {}); return inputVars; } diff --git a/x-pack/plugins/apm/server/lib/fleet/sync_agent_configs_to_apm_package_policies.ts b/x-pack/plugins/apm/server/lib/fleet/sync_agent_configs_to_apm_package_policies.ts index 1365ddc28ddb..5f3a3f74598a 100644 --- a/x-pack/plugins/apm/server/lib/fleet/sync_agent_configs_to_apm_package_policies.ts +++ b/x-pack/plugins/apm/server/lib/fleet/sync_agent_configs_to_apm_package_policies.ts @@ -37,18 +37,15 @@ export async function syncAgentConfigsToApmPackagePolicies({ } const coreStart = await core.start(); const esClient = coreStart.elasticsearch.client.asInternalUser; - const [ - savedObjectsClient, - agentConfigurations, - packagePolicies, - ] = await Promise.all([ - getInternalSavedObjectsClient(core.setup), - listConfigurations({ setup }), - getApmPackgePolicies({ - core, - fleetPluginStart, - }), - ]); + const [savedObjectsClient, agentConfigurations, packagePolicies] = + await Promise.all([ + getInternalSavedObjectsClient(core.setup), + listConfigurations({ setup }), + getApmPackgePolicies({ + core, + fleetPluginStart, + }), + ]); return Promise.all( packagePolicies.items.map(async (item) => { @@ -58,7 +55,7 @@ export async function syncAgentConfigsToApmPackagePolicies({ agentConfigurations ); return fleetPluginStart.packagePolicyService.update( - (savedObjectsClient as unknown) as SavedObjectsClientContract, + savedObjectsClient as unknown as SavedObjectsClientContract, esClient, id, updatedPackagePolicy diff --git a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts index f35ba874cf2b..8f03aceef334 100644 --- a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts +++ b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts @@ -29,7 +29,8 @@ describe('createApmEventClient', () => { }); const { server: innerServer, createRouter } = await server.setup({ context: contextServiceMock.createSetupContract(), - executionContext: executionContextServiceMock.createInternalSetupContract(), + executionContext: + executionContextServiceMock.createInternalSetupContract(), }); const router = createRouter('/'); diff --git a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts index 2f2435c21dc1..3fed3c92c440 100644 --- a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts +++ b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts @@ -54,12 +54,11 @@ type ESSearchRequestOf = Omit< 'apm' > & { index: string[] | string }; -type TypedSearchResponse< - TParams extends APMEventESSearchRequest -> = InferSearchResponseOf< - TypeOfProcessorEvent>, - ESSearchRequestOf ->; +type TypedSearchResponse = + InferSearchResponseOf< + TypeOfProcessorEvent>, + ESSearchRequestOf + >; export type APMEventClient = ReturnType; diff --git a/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts b/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts index 00f3f15786ad..94e88a09ea35 100644 --- a/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts +++ b/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts @@ -41,7 +41,7 @@ function getMockResources() { }, }; - const mockResources = ({ + const mockResources = { config: new Proxy( {}, { @@ -81,7 +81,7 @@ function getMockResources() { }, }, }, - } as unknown) as APMRouteHandlerResources & { + } as unknown as APMRouteHandlerResources & { context: { core: { elasticsearch: { diff --git a/x-pack/plugins/apm/server/lib/index_pattern/create_static_index_pattern.test.ts b/x-pack/plugins/apm/server/lib/index_pattern/create_static_index_pattern.test.ts index 46596d8ac864..aae707c6e468 100644 --- a/x-pack/plugins/apm/server/lib/index_pattern/create_static_index_pattern.test.ts +++ b/x-pack/plugins/apm/server/lib/index_pattern/create_static_index_pattern.test.ts @@ -13,24 +13,24 @@ import { InternalSavedObjectsClient } from '../helpers/get_internal_saved_object import { APMConfig } from '../..'; function getMockSavedObjectsClient(existingIndexPatternTitle: string) { - return ({ + return { get: jest.fn(() => ({ attributes: { title: existingIndexPatternTitle, }, })), create: jest.fn(), - } as unknown) as InternalSavedObjectsClient; + } as unknown as InternalSavedObjectsClient; } -const setup = ({ +const setup = { indices: { 'apm_oss.transactionIndices': 'apm-*-transaction-*', 'apm_oss.spanIndices': 'apm-*-span-*', 'apm_oss.errorIndices': 'apm-*-error-*', 'apm_oss.metricsIndices': 'apm-*-metrics-*', }, -} as unknown) as Setup; +} as unknown as Setup; describe('createStaticIndexPattern', () => { it(`should not create index pattern if 'xpack.apm.autocreateApmIndexPattern=false'`, async () => { diff --git a/x-pack/plugins/apm/server/lib/index_pattern/create_static_index_pattern.ts b/x-pack/plugins/apm/server/lib/index_pattern/create_static_index_pattern.ts index 6fa96de0b941..4f35e7e63915 100644 --- a/x-pack/plugins/apm/server/lib/index_pattern/create_static_index_pattern.ts +++ b/x-pack/plugins/apm/server/lib/index_pattern/create_static_index_pattern.ts @@ -91,10 +91,11 @@ async function getForceOverwrite({ }) { if (!overwrite) { try { - const existingIndexPattern = await savedObjectsClient.get( - 'index-pattern', - APM_STATIC_INDEX_PATTERN_ID - ); + const existingIndexPattern = + await savedObjectsClient.get( + 'index-pattern', + APM_STATIC_INDEX_PATTERN_ID + ); // if the existing index pattern does not matches the new one, force an update return existingIndexPattern.attributes.title !== apmIndexPatternTitle; diff --git a/x-pack/plugins/apm/server/lib/rum_client/get_js_errors.ts b/x-pack/plugins/apm/server/lib/rum_client/get_js_errors.ts index 6967dd3d1660..10e43c478e24 100644 --- a/x-pack/plugins/apm/server/lib/rum_client/get_js_errors.ts +++ b/x-pack/plugins/apm/server/lib/rum_client/get_js_errors.ts @@ -108,9 +108,11 @@ export async function getJSErrors({ return { count: impactedPages.pageCount.value, errorGroupId: key, - errorMessage: (sample.hits.hits[0]._source as { - error: { exception: Array<{ message: string }> }; - }).error.exception?.[0].message, + errorMessage: ( + sample.hits.hits[0]._source as { + error: { exception: Array<{ message: string }> }; + } + ).error.exception?.[0].message, }; }), }; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/failed_transactions_correlations/failed_transactions_correlations_search_service.ts b/x-pack/plugins/apm/server/lib/search_strategies/failed_transactions_correlations/failed_transactions_correlations_search_service.ts index a089c5043f9a..02ba0a8514b6 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/failed_transactions_correlations/failed_transactions_correlations_search_service.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/failed_transactions_correlations/failed_transactions_correlations_search_service.ts @@ -37,198 +37,201 @@ import { failedTransactionsCorrelationsSearchServiceStateProvider } from './fail import { ERROR_CORRELATION_THRESHOLD } from '../constants'; -export type FailedTransactionsCorrelationsSearchServiceProvider = SearchServiceProvider< - FailedTransactionsCorrelationsRequestParams, - FailedTransactionsCorrelationsRawResponse ->; +export type FailedTransactionsCorrelationsSearchServiceProvider = + SearchServiceProvider< + FailedTransactionsCorrelationsRequestParams, + FailedTransactionsCorrelationsRawResponse + >; export type FailedTransactionsCorrelationsSearchStrategy = ISearchStrategy< IKibanaSearchRequest, IKibanaSearchResponse >; -export const failedTransactionsCorrelationsSearchServiceProvider: FailedTransactionsCorrelationsSearchServiceProvider = ( - esClient: ElasticsearchClient, - getApmIndices: () => Promise, - searchServiceParams: FailedTransactionsCorrelationsRequestParams, - includeFrozen: boolean -) => { - const { addLogMessage, getLogMessages } = searchServiceLogProvider(); - - const state = failedTransactionsCorrelationsSearchServiceStateProvider(); - - async function fetchErrorCorrelations() { - try { - const indices = await getApmIndices(); - const params: FailedTransactionsCorrelationsRequestParams & - SearchStrategyServerParams = { - ...searchServiceParams, - index: indices['apm_oss.transactionIndices'], - includeFrozen, - }; +export const failedTransactionsCorrelationsSearchServiceProvider: FailedTransactionsCorrelationsSearchServiceProvider = + ( + esClient: ElasticsearchClient, + getApmIndices: () => Promise, + searchServiceParams: FailedTransactionsCorrelationsRequestParams, + includeFrozen: boolean + ) => { + const { addLogMessage, getLogMessages } = searchServiceLogProvider(); + + const state = failedTransactionsCorrelationsSearchServiceStateProvider(); + + async function fetchErrorCorrelations() { + try { + const indices = await getApmIndices(); + const params: FailedTransactionsCorrelationsRequestParams & + SearchStrategyServerParams = { + ...searchServiceParams, + index: indices['apm_oss.transactionIndices'], + includeFrozen, + }; + + // 95th percentile to be displayed as a marker in the log log chart + const { totalDocs, percentiles: percentilesResponseThresholds } = + await fetchTransactionDurationPercentiles( + esClient, + params, + params.percentileThreshold + ? [params.percentileThreshold] + : undefined + ); + const percentileThresholdValue = + percentilesResponseThresholds[`${params.percentileThreshold}.0`]; + state.setPercentileThresholdValue(percentileThresholdValue); - // 95th percentile to be displayed as a marker in the log log chart - const { - totalDocs, - percentiles: percentilesResponseThresholds, - } = await fetchTransactionDurationPercentiles( - esClient, - params, - params.percentileThreshold ? [params.percentileThreshold] : undefined - ); - const percentileThresholdValue = - percentilesResponseThresholds[`${params.percentileThreshold}.0`]; - state.setPercentileThresholdValue(percentileThresholdValue); + addLogMessage( + `Fetched ${params.percentileThreshold}th percentile value of ${percentileThresholdValue} based on ${totalDocs} documents.` + ); - addLogMessage( - `Fetched ${params.percentileThreshold}th percentile value of ${percentileThresholdValue} based on ${totalDocs} documents.` - ); + // finish early if we weren't able to identify the percentileThresholdValue. + if (percentileThresholdValue === undefined) { + addLogMessage( + `Abort service since percentileThresholdValue could not be determined.` + ); + state.setProgress({ + loadedFieldCandidates: 1, + loadedErrorCorrelations: 1, + loadedOverallHistogram: 1, + loadedFailedTransactionsCorrelations: 1, + }); + state.setIsRunning(false); + return; + } - // finish early if we weren't able to identify the percentileThresholdValue. - if (percentileThresholdValue === undefined) { - addLogMessage( - `Abort service since percentileThresholdValue could not be determined.` + const histogramRangeSteps = + await fetchTransactionDurationHistogramRangeSteps(esClient, params); + + const overallLogHistogramChartData = + await fetchTransactionDurationRanges( + esClient, + params, + histogramRangeSteps + ); + const errorLogHistogramChartData = await fetchTransactionDurationRanges( + esClient, + params, + histogramRangeSteps, + [{ fieldName: EVENT_OUTCOME, fieldValue: EventOutcome.failure }] ); - state.setProgress({ - loadedFieldCandidates: 1, - loadedErrorCorrelations: 1, - loadedOverallHistogram: 1, - loadedFailedTransactionsCorrelations: 1, - }); - state.setIsRunning(false); - return; - } - const histogramRangeSteps = await fetchTransactionDurationHistogramRangeSteps( - esClient, - params - ); + state.setProgress({ loadedOverallHistogram: 1 }); + state.setErrorHistogram(errorLogHistogramChartData); + state.setOverallHistogram(overallLogHistogramChartData); - const overallLogHistogramChartData = await fetchTransactionDurationRanges( - esClient, - params, - histogramRangeSteps - ); - const errorLogHistogramChartData = await fetchTransactionDurationRanges( - esClient, - params, - histogramRangeSteps, - [{ fieldName: EVENT_OUTCOME, fieldValue: EventOutcome.failure }] - ); + const { fieldCandidates: candidates } = + await fetchTransactionDurationFieldCandidates(esClient, params); - state.setProgress({ loadedOverallHistogram: 1 }); - state.setErrorHistogram(errorLogHistogramChartData); - state.setOverallHistogram(overallLogHistogramChartData); + const fieldCandidates = candidates.filter( + (t) => !(t === EVENT_OUTCOME) + ); - const { - fieldCandidates: candidates, - } = await fetchTransactionDurationFieldCandidates(esClient, params); - - const fieldCandidates = candidates.filter((t) => !(t === EVENT_OUTCOME)); - - addLogMessage(`Identified ${fieldCandidates.length} fieldCandidates.`); - - state.setProgress({ loadedFieldCandidates: 1 }); - - let fieldCandidatesFetchedCount = 0; - if (params !== undefined && fieldCandidates.length > 0) { - const batches = chunk(fieldCandidates, 10); - for (let i = 0; i < batches.length; i++) { - try { - const results = await Promise.allSettled( - batches[i].map((fieldName) => - fetchFailedTransactionsCorrelationPValues( - esClient, - params, - histogramRangeSteps, - fieldName - ) - ) - ); - - results.forEach((result, idx) => { - if (result.status === 'fulfilled') { - state.addFailedTransactionsCorrelations( - result.value.filter( - (record) => - record && - typeof record.pValue === 'number' && - record.pValue < ERROR_CORRELATION_THRESHOLD + addLogMessage(`Identified ${fieldCandidates.length} fieldCandidates.`); + + state.setProgress({ loadedFieldCandidates: 1 }); + + let fieldCandidatesFetchedCount = 0; + if (params !== undefined && fieldCandidates.length > 0) { + const batches = chunk(fieldCandidates, 10); + for (let i = 0; i < batches.length; i++) { + try { + const results = await Promise.allSettled( + batches[i].map((fieldName) => + fetchFailedTransactionsCorrelationPValues( + esClient, + params, + histogramRangeSteps, + fieldName ) - ); - } else { - // If one of the fields in the batch had an error - addLogMessage( - `Error getting error correlation for field ${batches[i][idx]}: ${result.reason}.` - ); + ) + ); + + results.forEach((result, idx) => { + if (result.status === 'fulfilled') { + state.addFailedTransactionsCorrelations( + result.value.filter( + (record) => + record && + typeof record.pValue === 'number' && + record.pValue < ERROR_CORRELATION_THRESHOLD + ) + ); + } else { + // If one of the fields in the batch had an error + addLogMessage( + `Error getting error correlation for field ${batches[i][idx]}: ${result.reason}.` + ); + } + }); + } catch (e) { + state.setError(e); + + if (params?.index.includes(':')) { + state.setCcsWarning(true); } - }); - } catch (e) { - state.setError(e); - - if (params?.index.includes(':')) { - state.setCcsWarning(true); + } finally { + fieldCandidatesFetchedCount += batches[i].length; + state.setProgress({ + loadedFailedTransactionsCorrelations: + fieldCandidatesFetchedCount / fieldCandidates.length, + }); } - } finally { - fieldCandidatesFetchedCount += batches[i].length; - state.setProgress({ - loadedFailedTransactionsCorrelations: - fieldCandidatesFetchedCount / fieldCandidates.length, - }); } - } - addLogMessage( - `Identified correlations for ${fieldCandidatesFetchedCount} fields out of ${fieldCandidates.length} candidates.` - ); + addLogMessage( + `Identified correlations for ${fieldCandidatesFetchedCount} fields out of ${fieldCandidates.length} candidates.` + ); + } + } catch (e) { + state.setError(e); } - } catch (e) { - state.setError(e); + + addLogMessage( + `Identified ${ + state.getState().failedTransactionsCorrelations.length + } significant correlations relating to failed transactions.` + ); + + state.setIsRunning(false); } - addLogMessage( - `Identified ${ - state.getState().failedTransactionsCorrelations.length - } significant correlations relating to failed transactions.` - ); - - state.setIsRunning(false); - } - - fetchErrorCorrelations(); - - return () => { - const { - ccsWarning, - error, - isRunning, - overallHistogram, - errorHistogram, - percentileThresholdValue, - progress, - } = state.getState(); - - return { - cancel: () => { - addLogMessage(`Service cancelled.`); - state.setIsCancelled(true); - }, - error, - meta: { - loaded: Math.round(state.getOverallProgress() * 100), - total: 100, - isRunning, - isPartial: isRunning, - }, - rawResponse: { + fetchErrorCorrelations(); + + return () => { + const { ccsWarning, - log: getLogMessages(), - took: Date.now() - progress.started, - failedTransactionsCorrelations: state.getFailedTransactionsCorrelationsSortedByScore(), + error, + isRunning, overallHistogram, errorHistogram, percentileThresholdValue, - }, + progress, + } = state.getState(); + + return { + cancel: () => { + addLogMessage(`Service cancelled.`); + state.setIsCancelled(true); + }, + error, + meta: { + loaded: Math.round(state.getOverallProgress() * 100), + total: 100, + isRunning, + isPartial: isRunning, + }, + rawResponse: { + ccsWarning, + log: getLogMessages(), + took: Date.now() - progress.started, + failedTransactionsCorrelations: + state.getFailedTransactionsCorrelationsSortedByScore(), + overallHistogram, + errorHistogram, + percentileThresholdValue, + }, + }; }; }; -}; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/latency_correlations/latency_correlations_search_service.ts b/x-pack/plugins/apm/server/lib/search_strategies/latency_correlations/latency_correlations_search_service.ts index 9344b354808b..7e420c821a74 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/latency_correlations/latency_correlations_search_service.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/latency_correlations/latency_correlations_search_service.ts @@ -47,233 +47,230 @@ export type LatencyCorrelationsSearchStrategy = ISearchStrategy< IKibanaSearchResponse >; -export const latencyCorrelationsSearchServiceProvider: LatencyCorrelationsSearchServiceProvider = ( - esClient: ElasticsearchClient, - getApmIndices: () => Promise, - searchServiceParams: LatencyCorrelationsRequestParams, - includeFrozen: boolean -) => { - const { addLogMessage, getLogMessages } = searchServiceLogProvider(); - - const state = latencyCorrelationsSearchServiceStateProvider(); - - async function fetchCorrelations() { - let params: - | (LatencyCorrelationsRequestParams & SearchStrategyServerParams) - | undefined; - - try { - const indices = await getApmIndices(); - params = { - ...searchServiceParams, - index: indices['apm_oss.transactionIndices'], - includeFrozen, - }; +export const latencyCorrelationsSearchServiceProvider: LatencyCorrelationsSearchServiceProvider = + ( + esClient: ElasticsearchClient, + getApmIndices: () => Promise, + searchServiceParams: LatencyCorrelationsRequestParams, + includeFrozen: boolean + ) => { + const { addLogMessage, getLogMessages } = searchServiceLogProvider(); + + const state = latencyCorrelationsSearchServiceStateProvider(); + + async function fetchCorrelations() { + let params: + | (LatencyCorrelationsRequestParams & SearchStrategyServerParams) + | undefined; + + try { + const indices = await getApmIndices(); + params = { + ...searchServiceParams, + index: indices['apm_oss.transactionIndices'], + includeFrozen, + }; + + // 95th percentile to be displayed as a marker in the log log chart + const { totalDocs, percentiles: percentilesResponseThresholds } = + await fetchTransactionDurationPercentiles( + esClient, + params, + params.percentileThreshold + ? [params.percentileThreshold] + : undefined + ); + const percentileThresholdValue = + percentilesResponseThresholds[`${params.percentileThreshold}.0`]; + state.setPercentileThresholdValue(percentileThresholdValue); - // 95th percentile to be displayed as a marker in the log log chart - const { - totalDocs, - percentiles: percentilesResponseThresholds, - } = await fetchTransactionDurationPercentiles( - esClient, - params, - params.percentileThreshold ? [params.percentileThreshold] : undefined - ); - const percentileThresholdValue = - percentilesResponseThresholds[`${params.percentileThreshold}.0`]; - state.setPercentileThresholdValue(percentileThresholdValue); - - addLogMessage( - `Fetched ${params.percentileThreshold}th percentile value of ${percentileThresholdValue} based on ${totalDocs} documents.` - ); - - // finish early if we weren't able to identify the percentileThresholdValue. - if (percentileThresholdValue === undefined) { addLogMessage( - `Abort service since percentileThresholdValue could not be determined.` + `Fetched ${params.percentileThreshold}th percentile value of ${percentileThresholdValue} based on ${totalDocs} documents.` ); - state.setProgress({ - loadedHistogramStepsize: 1, - loadedOverallHistogram: 1, - loadedFieldCandidates: 1, - loadedFieldValuePairs: 1, - loadedHistograms: 1, - }); - state.setIsRunning(false); - return; - } - const histogramRangeSteps = await fetchTransactionDurationHistogramRangeSteps( - esClient, - params - ); - state.setProgress({ loadedHistogramStepsize: 1 }); + // finish early if we weren't able to identify the percentileThresholdValue. + if (percentileThresholdValue === undefined) { + addLogMessage( + `Abort service since percentileThresholdValue could not be determined.` + ); + state.setProgress({ + loadedHistogramStepsize: 1, + loadedOverallHistogram: 1, + loadedFieldCandidates: 1, + loadedFieldValuePairs: 1, + loadedHistograms: 1, + }); + state.setIsRunning(false); + return; + } - addLogMessage(`Loaded histogram range steps.`); + const histogramRangeSteps = + await fetchTransactionDurationHistogramRangeSteps(esClient, params); + state.setProgress({ loadedHistogramStepsize: 1 }); - if (state.getIsCancelled()) { - state.setIsRunning(false); - return; - } + addLogMessage(`Loaded histogram range steps.`); - const overallLogHistogramChartData = await fetchTransactionDurationRanges( - esClient, - params, - histogramRangeSteps - ); - state.setProgress({ loadedOverallHistogram: 1 }); - state.setOverallHistogram(overallLogHistogramChartData); + if (state.getIsCancelled()) { + state.setIsRunning(false); + return; + } - addLogMessage(`Loaded overall histogram chart data.`); + const overallLogHistogramChartData = + await fetchTransactionDurationRanges( + esClient, + params, + histogramRangeSteps + ); + state.setProgress({ loadedOverallHistogram: 1 }); + state.setOverallHistogram(overallLogHistogramChartData); - if (state.getIsCancelled()) { - state.setIsRunning(false); - return; - } + addLogMessage(`Loaded overall histogram chart data.`); - // finish early if correlation analysis is not required. - if (params.analyzeCorrelations === false) { - addLogMessage( - `Finish service since correlation analysis wasn't requested.` - ); - state.setProgress({ - loadedHistogramStepsize: 1, - loadedOverallHistogram: 1, - loadedFieldCandidates: 1, - loadedFieldValuePairs: 1, - loadedHistograms: 1, - }); - state.setIsRunning(false); - return; - } + if (state.getIsCancelled()) { + state.setIsRunning(false); + return; + } - // Create an array of ranges [2, 4, 6, ..., 98] - const percentileAggregationPercents = range(2, 100, 2); - const { - percentiles: percentilesRecords, - } = await fetchTransactionDurationPercentiles( - esClient, - params, - percentileAggregationPercents - ); - const percentiles = Object.values(percentilesRecords); - - addLogMessage(`Loaded percentiles.`); - - if (state.getIsCancelled()) { - state.setIsRunning(false); - return; - } + // finish early if correlation analysis is not required. + if (params.analyzeCorrelations === false) { + addLogMessage( + `Finish service since correlation analysis wasn't requested.` + ); + state.setProgress({ + loadedHistogramStepsize: 1, + loadedOverallHistogram: 1, + loadedFieldCandidates: 1, + loadedFieldValuePairs: 1, + loadedHistograms: 1, + }); + state.setIsRunning(false); + return; + } - const { fieldCandidates } = await fetchTransactionDurationFieldCandidates( - esClient, - params - ); + // Create an array of ranges [2, 4, 6, ..., 98] + const percentileAggregationPercents = range(2, 100, 2); + const { percentiles: percentilesRecords } = + await fetchTransactionDurationPercentiles( + esClient, + params, + percentileAggregationPercents + ); + const percentiles = Object.values(percentilesRecords); + + addLogMessage(`Loaded percentiles.`); + + if (state.getIsCancelled()) { + state.setIsRunning(false); + return; + } + + const { fieldCandidates } = + await fetchTransactionDurationFieldCandidates(esClient, params); - addLogMessage(`Identified ${fieldCandidates.length} fieldCandidates.`); + addLogMessage(`Identified ${fieldCandidates.length} fieldCandidates.`); - state.setProgress({ loadedFieldCandidates: 1 }); + state.setProgress({ loadedFieldCandidates: 1 }); - const fieldValuePairs = await fetchTransactionDurationFieldValuePairs( - esClient, - params, - fieldCandidates, - state, - addLogMessage - ); + const fieldValuePairs = await fetchTransactionDurationFieldValuePairs( + esClient, + params, + fieldCandidates, + state, + addLogMessage + ); - addLogMessage(`Identified ${fieldValuePairs.length} fieldValuePairs.`); + addLogMessage(`Identified ${fieldValuePairs.length} fieldValuePairs.`); - if (state.getIsCancelled()) { - state.setIsRunning(false); - return; - } + if (state.getIsCancelled()) { + state.setIsRunning(false); + return; + } - const { expectations, ranges } = computeExpectationsAndRanges( - percentiles - ); + const { expectations, ranges } = + computeExpectationsAndRanges(percentiles); - const { - fractions, - totalDocCount, - } = await fetchTransactionDurationFractions(esClient, params, ranges); - - addLogMessage(`Loaded fractions and totalDocCount of ${totalDocCount}.`); - - let loadedHistograms = 0; - for await (const item of fetchTransactionDurationHistograms( - esClient, - addLogMessage, - params, - state, - expectations, - ranges, - fractions, - histogramRangeSteps, - totalDocCount, - fieldValuePairs - )) { - if (item !== undefined) { - state.addLatencyCorrelation(item); + const { fractions, totalDocCount } = + await fetchTransactionDurationFractions(esClient, params, ranges); + + addLogMessage( + `Loaded fractions and totalDocCount of ${totalDocCount}.` + ); + + let loadedHistograms = 0; + for await (const item of fetchTransactionDurationHistograms( + esClient, + addLogMessage, + params, + state, + expectations, + ranges, + fractions, + histogramRangeSteps, + totalDocCount, + fieldValuePairs + )) { + if (item !== undefined) { + state.addLatencyCorrelation(item); + } + loadedHistograms++; + state.setProgress({ + loadedHistograms: loadedHistograms / fieldValuePairs.length, + }); } - loadedHistograms++; - state.setProgress({ - loadedHistograms: loadedHistograms / fieldValuePairs.length, - }); + + addLogMessage( + `Identified ${ + state.getState().latencyCorrelations.length + } significant correlations out of ${ + fieldValuePairs.length + } field/value pairs.` + ); + } catch (e) { + state.setError(e); } - addLogMessage( - `Identified ${ - state.getState().latencyCorrelations.length - } significant correlations out of ${ - fieldValuePairs.length - } field/value pairs.` - ); - } catch (e) { - state.setError(e); + if (state.getState().error !== undefined && params?.index.includes(':')) { + state.setCcsWarning(true); + } + + state.setIsRunning(false); } - if (state.getState().error !== undefined && params?.index.includes(':')) { - state.setCcsWarning(true); + function cancel() { + addLogMessage(`Service cancelled.`); + state.setIsCancelled(true); } - state.setIsRunning(false); - } - - function cancel() { - addLogMessage(`Service cancelled.`); - state.setIsCancelled(true); - } - - fetchCorrelations(); - - return () => { - const { - ccsWarning, - error, - isRunning, - overallHistogram, - percentileThresholdValue, - progress, - } = state.getState(); - - return { - cancel, - error, - meta: { - loaded: Math.round(state.getOverallProgress() * 100), - total: 100, - isRunning, - isPartial: isRunning, - }, - rawResponse: { + fetchCorrelations(); + + return () => { + const { ccsWarning, - log: getLogMessages(), - took: Date.now() - progress.started, - latencyCorrelations: state.getLatencyCorrelationsSortedByCorrelation(), - percentileThresholdValue, + error, + isRunning, overallHistogram, - }, + percentileThresholdValue, + progress, + } = state.getState(); + + return { + cancel, + error, + meta: { + loaded: Math.round(state.getOverallProgress() * 100), + total: 100, + isRunning, + isPartial: isRunning, + }, + rawResponse: { + ccsWarning, + log: getLogMessages(), + took: Date.now() - progress.started, + latencyCorrelations: + state.getLatencyCorrelationsSortedByCorrelation(), + percentileThresholdValue, + overallHistogram, + }, + }; }; }; -}; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/get_prioritized_field_value_pairs.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/get_prioritized_field_value_pairs.test.ts index cb1500e70bab..227173c31778 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/get_prioritized_field_value_pairs.test.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/get_prioritized_field_value_pairs.test.ts @@ -14,9 +14,8 @@ describe('correlations', () => { { fieldName: 'the-field-1', fieldValue: 'the-value-1' }, { fieldName: 'the-field-2', fieldValue: 'the-value-2' }, ]; - const prioritziedFieldValuePairs = getPrioritizedFieldValuePairs( - fieldValuePairs - ); + const prioritziedFieldValuePairs = + getPrioritizedFieldValuePairs(fieldValuePairs); expect(prioritziedFieldValuePairs.map((d) => d.fieldName)).toEqual([ 'the-field-1', 'the-field-2', @@ -28,9 +27,8 @@ describe('correlations', () => { { fieldName: 'service.version', fieldValue: 'the-value-1' }, { fieldName: 'the-field-2', fieldValue: 'the-value-2' }, ]; - const prioritziedFieldValuePairs = getPrioritizedFieldValuePairs( - fieldValuePairs - ); + const prioritziedFieldValuePairs = + getPrioritizedFieldValuePairs(fieldValuePairs); expect(prioritziedFieldValuePairs.map((d) => d.fieldName)).toEqual([ 'service.version', 'the-field-2', @@ -42,9 +40,8 @@ describe('correlations', () => { { fieldName: 'the-field-1', fieldValue: 'the-value-1' }, { fieldName: 'service.version', fieldValue: 'the-value-2' }, ]; - const prioritziedFieldValuePairs = getPrioritizedFieldValuePairs( - fieldValuePairs - ); + const prioritziedFieldValuePairs = + getPrioritizedFieldValuePairs(fieldValuePairs); expect(prioritziedFieldValuePairs.map((d) => d.fieldName)).toEqual([ 'service.version', 'the-field-1', @@ -57,9 +54,8 @@ describe('correlations', () => { { fieldName: 'service.version', fieldValue: 'the-value-2' }, { fieldName: 'cloud.the-field-3', fieldValue: 'the-value-3' }, ]; - const prioritziedFieldValuePairs = getPrioritizedFieldValuePairs( - fieldValuePairs - ); + const prioritziedFieldValuePairs = + getPrioritizedFieldValuePairs(fieldValuePairs); expect(prioritziedFieldValuePairs.map((d) => d.fieldName)).toEqual([ 'service.version', 'cloud.the-field-3', diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.test.ts index d3d14260df65..fc2dacce61a7 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.test.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.test.ts @@ -48,9 +48,11 @@ describe('query_correlation', () => { expect(query?.body?.aggs?.latency_ranges?.range?.ranges).toEqual(ranges); expect( - (query?.body?.aggs?.transaction_duration_correlation as { - bucket_correlation: BucketCorrelation; - })?.bucket_correlation.function.count_correlation.indicator + ( + query?.body?.aggs?.transaction_duration_correlation as { + bucket_correlation: BucketCorrelation; + } + )?.bucket_correlation.function.count_correlation.indicator ).toEqual({ fractions, expectations, @@ -69,27 +71,31 @@ describe('query_correlation', () => { const transactionDurationCorrelationValue = 0.45; const KsTestLess = 0.01; - const esClientSearchMock = jest.fn((req: estypes.SearchRequest): { - body: estypes.SearchResponse; - } => { - return { - body: ({ - aggregations: { - latency_ranges: { - buckets: latencyRangesBuckets, + const esClientSearchMock = jest.fn( + ( + req: estypes.SearchRequest + ): { + body: estypes.SearchResponse; + } => { + return { + body: { + aggregations: { + latency_ranges: { + buckets: latencyRangesBuckets, + }, + transaction_duration_correlation: { + value: transactionDurationCorrelationValue, + }, + ks_test: { less: KsTestLess }, }, - transaction_duration_correlation: { - value: transactionDurationCorrelationValue, - }, - ks_test: { less: KsTestLess }, - }, - } as unknown) as estypes.SearchResponse, - }; - }); + } as unknown as estypes.SearchResponse, + }; + } + ); - const esClientMock = ({ + const esClientMock = { search: esClientSearchMock, - } as unknown) as ElasticsearchClient; + } as unknown as ElasticsearchClient; const resp = await fetchTransactionDurationCorrelation( esClientMock, diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.ts index 82913a91db16..24db25f8afd8 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.ts @@ -116,11 +116,14 @@ export const fetchTransactionDurationCorrelation = async ( } const result = { - ranges: (resp.body.aggregations - .latency_ranges as estypes.AggregationsMultiBucketAggregate).buckets, - correlation: (resp.body.aggregations - .transaction_duration_correlation as estypes.AggregationsValueAggregate) - .value, + ranges: ( + resp.body.aggregations + .latency_ranges as estypes.AggregationsMultiBucketAggregate + ).buckets, + correlation: ( + resp.body.aggregations + .transaction_duration_correlation as estypes.AggregationsValueAggregate + ).value, // @ts-ignore ksTest: resp.body.aggregations.ks_test.less, }; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_candidates.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_candidates.test.ts index 150348e2a7aa..6e0521ac1a00 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_candidates.test.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_candidates.test.ts @@ -106,30 +106,34 @@ describe('query_field_candidates', () => { }, }, })); - const esClientSearchMock = jest.fn((req: estypes.SearchRequest): { - body: estypes.SearchResponse; - } => { - return { - body: ({ - hits: { - hits: [ - { - fields: { - myIpFieldName: '1.1.1.1', - myKeywordFieldName: 'myKeywordFieldValue', - myNumericFieldName: 1234, + const esClientSearchMock = jest.fn( + ( + req: estypes.SearchRequest + ): { + body: estypes.SearchResponse; + } => { + return { + body: { + hits: { + hits: [ + { + fields: { + myIpFieldName: '1.1.1.1', + myKeywordFieldName: 'myKeywordFieldValue', + myNumericFieldName: 1234, + }, }, - }, - ], - }, - } as unknown) as estypes.SearchResponse, - }; - }); + ], + }, + } as unknown as estypes.SearchResponse, + }; + } + ); - const esClientMock = ({ + const esClientMock = { fieldCaps: esClientFieldCapsMock, search: esClientSearchMock, - } as unknown) as ElasticsearchClient; + } as unknown as ElasticsearchClient; const resp = await fetchTransactionDurationFieldCandidates( esClientMock, diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.test.ts index 1fff8cde5bbb..9ffbf6b2ce18 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.test.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.test.ts @@ -44,23 +44,27 @@ describe('query_field_value_pairs', () => { 'myFieldCandidate3', ]; - const esClientSearchMock = jest.fn((req: estypes.SearchRequest): { - body: estypes.SearchResponse; - } => { - return { - body: ({ - aggregations: { - attribute_terms: { - buckets: [{ key: 'myValue1' }, { key: 'myValue2' }], + const esClientSearchMock = jest.fn( + ( + req: estypes.SearchRequest + ): { + body: estypes.SearchResponse; + } => { + return { + body: { + aggregations: { + attribute_terms: { + buckets: [{ key: 'myValue1' }, { key: 'myValue2' }], + }, }, - }, - } as unknown) as estypes.SearchResponse, - }; - }); + } as unknown as estypes.SearchResponse, + }; + } + ); - const esClientMock = ({ + const esClientMock = { search: esClientSearchMock, - } as unknown) as ElasticsearchClient; + } as unknown as ElasticsearchClient; const { addLogMessage, getLogMessages } = searchServiceLogProvider(); const state = latencyCorrelationsSearchServiceStateProvider(); diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.ts index aa7d9f341a34..296abfd2d865 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.ts @@ -56,10 +56,12 @@ const fetchTransactionDurationFieldTerms = async ( ); return []; } - const buckets = (resp.body.aggregations - .attribute_terms as estypes.AggregationsMultiBucketAggregate<{ - key: string; - }>)?.buckets; + const buckets = ( + resp.body.aggregations + .attribute_terms as estypes.AggregationsMultiBucketAggregate<{ + key: string; + }> + )?.buckets; if (buckets?.length >= 1) { return buckets.map((d) => ({ fieldName, diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.test.ts index fdf383453e17..daf6b368c78b 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.test.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.test.ts @@ -39,23 +39,27 @@ describe('query_fractions', () => { describe('fetchTransactionDurationFractions', () => { it('computes the actual percentile bucket counts and actual fractions', async () => { - const esClientSearchMock = jest.fn((req: estypes.SearchRequest): { - body: estypes.SearchResponse; - } => { - return { - body: ({ - aggregations: { - latency_ranges: { - buckets: [{ doc_count: 1 }, { doc_count: 2 }], + const esClientSearchMock = jest.fn( + ( + req: estypes.SearchRequest + ): { + body: estypes.SearchResponse; + } => { + return { + body: { + aggregations: { + latency_ranges: { + buckets: [{ doc_count: 1 }, { doc_count: 2 }], + }, }, - }, - } as unknown) as estypes.SearchResponse, - }; - }); + } as unknown as estypes.SearchResponse, + }; + } + ); - const esClientMock = ({ + const esClientMock = { search: esClientSearchMock, - } as unknown) as ElasticsearchClient; + } as unknown as ElasticsearchClient; const resp = await fetchTransactionDurationFractions( esClientMock, diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.ts index 25e5f62564b0..ccea480052c9 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.ts @@ -50,10 +50,12 @@ export const fetchTransactionDurationFractions = async ( ); } - const buckets = (resp.body.aggregations - .latency_ranges as estypes.AggregationsMultiBucketAggregate<{ - doc_count: number; - }>)?.buckets; + const buckets = ( + resp.body.aggregations + .latency_ranges as estypes.AggregationsMultiBucketAggregate<{ + doc_count: number; + }> + )?.buckets; const totalDocCount = buckets.reduce((acc, bucket) => { return acc + bucket.doc_count; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.test.ts index e6faeb16247f..7ecb1d2d8a33 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.test.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.test.ts @@ -78,23 +78,27 @@ describe('query_histogram', () => { }, ]; - const esClientSearchMock = jest.fn((req: estypes.SearchRequest): { - body: estypes.SearchResponse; - } => { - return { - body: ({ - aggregations: { - transaction_duration_histogram: { - buckets: histogramBucket, + const esClientSearchMock = jest.fn( + ( + req: estypes.SearchRequest + ): { + body: estypes.SearchResponse; + } => { + return { + body: { + aggregations: { + transaction_duration_histogram: { + buckets: histogramBucket, + }, }, - }, - } as unknown) as estypes.SearchResponse, - }; - }); + } as unknown as estypes.SearchResponse, + }; + } + ); - const esClientMock = ({ + const esClientMock = { search: esClientSearchMock, - } as unknown) as ElasticsearchClient; + } as unknown as ElasticsearchClient; const resp = await fetchTransactionDurationHistogram( esClientMock, diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.ts index 2514caf3ff87..5fb7ef76fc72 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.ts @@ -54,8 +54,9 @@ export const fetchTransactionDurationHistogram = async ( } return ( - (resp.body.aggregations - .transaction_duration_histogram as estypes.AggregationsMultiBucketAggregate) - .buckets ?? [] + ( + resp.body.aggregations + .transaction_duration_histogram as estypes.AggregationsMultiBucketAggregate + ).buckets ?? [] ); }; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_interval.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_interval.test.ts index 7b0d00d0d9b5..e6cf926d20bd 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_interval.test.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_interval.test.ts @@ -74,26 +74,30 @@ describe('query_histogram_interval', () => { describe('fetchTransactionDurationHistogramInterval', () => { it('fetches the interval duration for histograms', async () => { - const esClientSearchMock = jest.fn((req: estypes.SearchRequest): { - body: estypes.SearchResponse; - } => { - return { - body: ({ - aggregations: { - transaction_duration_max: { - value: 10000, - }, - transaction_duration_min: { - value: 10, + const esClientSearchMock = jest.fn( + ( + req: estypes.SearchRequest + ): { + body: estypes.SearchResponse; + } => { + return { + body: { + aggregations: { + transaction_duration_max: { + value: 10000, + }, + transaction_duration_min: { + value: 10, + }, }, - }, - } as unknown) as estypes.SearchResponse, - }; - }); + } as unknown as estypes.SearchResponse, + }; + } + ); - const esClientMock = ({ + const esClientMock = { search: esClientSearchMock, - } as unknown) as ElasticsearchClient; + } as unknown as ElasticsearchClient; const resp = await fetchTransactionDurationHistogramInterval( esClientMock, diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_interval.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_interval.ts index 7a8752e45c6f..906105003b71 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_interval.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_interval.ts @@ -44,10 +44,14 @@ export const fetchTransactionDurationHistogramInterval = async ( } const transactionDurationDelta = - (resp.body.aggregations - .transaction_duration_max as estypes.AggregationsValueAggregate).value - - (resp.body.aggregations - .transaction_duration_min as estypes.AggregationsValueAggregate).value; + ( + resp.body.aggregations + .transaction_duration_max as estypes.AggregationsValueAggregate + ).value - + ( + resp.body.aggregations + .transaction_duration_min as estypes.AggregationsValueAggregate + ).value; return transactionDurationDelta / (HISTOGRAM_INTERVALS - 1); }; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.test.ts index 88d4f1a57ade..25ce39cbcf17 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.test.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.test.ts @@ -74,27 +74,31 @@ describe('query_histogram_range_steps', () => { describe('fetchTransactionDurationHistogramRangeSteps', () => { it('fetches the range steps for the log histogram', async () => { - const esClientSearchMock = jest.fn((req: estypes.SearchRequest): { - body: estypes.SearchResponse; - } => { - return { - body: ({ - hits: { total: { value: 10 } }, - aggregations: { - transaction_duration_max: { - value: 10000, - }, - transaction_duration_min: { - value: 10, + const esClientSearchMock = jest.fn( + ( + req: estypes.SearchRequest + ): { + body: estypes.SearchResponse; + } => { + return { + body: { + hits: { total: { value: 10 } }, + aggregations: { + transaction_duration_max: { + value: 10000, + }, + transaction_duration_min: { + value: 10, + }, }, - }, - } as unknown) as estypes.SearchResponse, - }; - }); + } as unknown as estypes.SearchResponse, + }; + } + ); - const esClientMock = ({ + const esClientMock = { search: esClientSearchMock, - } as unknown) as ElasticsearchClient; + } as unknown as ElasticsearchClient; const resp = await fetchTransactionDurationHistogramRangeSteps( esClientMock, diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.ts index 31ab7392155b..973787833577 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.ts @@ -57,12 +57,15 @@ export const fetchTransactionDurationHistogramRangeSteps = async ( ); } - const min = (resp.body.aggregations - .transaction_duration_min as estypes.AggregationsValueAggregate).value; + const min = ( + resp.body.aggregations + .transaction_duration_min as estypes.AggregationsValueAggregate + ).value; const max = - (resp.body.aggregations - .transaction_duration_max as estypes.AggregationsValueAggregate).value * - 2; + ( + resp.body.aggregations + .transaction_duration_max as estypes.AggregationsValueAggregate + ).value * 2; return getHistogramRangeSteps(min, max, steps); }; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.test.ts index c80b2533d7e3..375e32b1472c 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.test.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.test.ts @@ -38,17 +38,21 @@ const fieldValuePairs = [ describe('query_histograms_generator', () => { describe('fetchTransactionDurationHistograms', () => { it(`doesn't break on failing ES queries and adds messages to the log`, async () => { - const esClientSearchMock = jest.fn((req: estypes.SearchRequest): { - body: estypes.SearchResponse; - } => { - return { - body: ({} as unknown) as estypes.SearchResponse, - }; - }); - - const esClientMock = ({ + const esClientSearchMock = jest.fn( + ( + req: estypes.SearchRequest + ): { + body: estypes.SearchResponse; + } => { + return { + body: {} as unknown as estypes.SearchResponse, + }; + } + ); + + const esClientMock = { search: esClientSearchMock, - } as unknown) as ElasticsearchClient; + } as unknown as ElasticsearchClient; const state = latencyCorrelationsSearchServiceStateProvider(); const { addLogMessage, getLogMessages } = searchServiceLogProvider(); @@ -85,24 +89,28 @@ describe('query_histograms_generator', () => { }); it('returns items with correlation and ks-test value', async () => { - const esClientSearchMock = jest.fn((req: estypes.SearchRequest): { - body: estypes.SearchResponse; - } => { - return { - body: ({ - aggregations: { - latency_ranges: { buckets: [] }, - transaction_duration_correlation: { value: 0.6 }, - ks_test: { less: 0.001 }, - logspace_ranges: { buckets: [] }, - }, - } as unknown) as estypes.SearchResponse, - }; - }); - - const esClientMock = ({ + const esClientSearchMock = jest.fn( + ( + req: estypes.SearchRequest + ): { + body: estypes.SearchResponse; + } => { + return { + body: { + aggregations: { + latency_ranges: { buckets: [] }, + transaction_duration_correlation: { value: 0.6 }, + ks_test: { less: 0.001 }, + logspace_ranges: { buckets: [] }, + }, + } as unknown as estypes.SearchResponse, + }; + } + ); + + const esClientMock = { search: esClientSearchMock, - } as unknown) as ElasticsearchClient; + } as unknown as ElasticsearchClient; const state = latencyCorrelationsSearchServiceStateProvider(); const { addLogMessage, getLogMessages } = searchServiceLogProvider(); diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.ts index a7f78d62d973..d526c63c7de3 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.ts @@ -43,10 +43,7 @@ export async function* fetchTransactionDurationHistograms( // If one of the fields have an error // We don't want to stop the whole process try { - const { - correlation, - ksTest, - } = await fetchTransactionDurationCorrelation( + const { correlation, ksTest } = await fetchTransactionDurationCorrelation( esClient, params, expectations, diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.test.ts index 1a5d518b7e47..ce86ffd9654e 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.test.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.test.ts @@ -84,24 +84,28 @@ describe('query_percentiles', () => { '99.0': 985.0, }; - const esClientSearchMock = jest.fn((req: estypes.SearchRequest): { - body: estypes.SearchResponse; - } => { - return { - body: ({ - hits: { total: { value: totalDocs } }, - aggregations: { - transaction_duration_percentiles: { - values: percentilesValues, + const esClientSearchMock = jest.fn( + ( + req: estypes.SearchRequest + ): { + body: estypes.SearchResponse; + } => { + return { + body: { + hits: { total: { value: totalDocs } }, + aggregations: { + transaction_duration_percentiles: { + values: percentilesValues, + }, }, - }, - } as unknown) as estypes.SearchResponse, - }; - }); + } as unknown as estypes.SearchResponse, + }; + } + ); - const esClientMock = ({ + const esClientMock = { search: esClientSearchMock, - } as unknown) as ElasticsearchClient; + } as unknown as ElasticsearchClient; const resp = await fetchTransactionDurationPercentiles( esClientMock, diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.ts index afc2487acfbf..70b5b70ce891 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.ts @@ -72,8 +72,9 @@ export const fetchTransactionDurationPercentiles = async ( return { totalDocs: (resp.body.hits.total as estypes.SearchTotalHits).value, percentiles: - (resp.body.aggregations - .transaction_duration_percentiles as estypes.AggregationsTDigestPercentilesAggregate) - .values ?? {}, + ( + resp.body.aggregations + .transaction_duration_percentiles as estypes.AggregationsTDigestPercentilesAggregate + ).values ?? {}, }; }; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.test.ts index 64b746b72534..e210eb7d41e7 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.test.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.test.ts @@ -109,23 +109,27 @@ describe('query_ranges', () => { }, ]; - const esClientSearchMock = jest.fn((req: estypes.SearchRequest): { - body: estypes.SearchResponse; - } => { - return { - body: ({ - aggregations: { - logspace_ranges: { - buckets: logspaceRangesBuckets, + const esClientSearchMock = jest.fn( + ( + req: estypes.SearchRequest + ): { + body: estypes.SearchResponse; + } => { + return { + body: { + aggregations: { + logspace_ranges: { + buckets: logspaceRangesBuckets, + }, }, - }, - } as unknown) as estypes.SearchResponse, - }; - }); + } as unknown as estypes.SearchResponse, + }; + } + ); - const esClientMock = ({ + const esClientMock = { search: esClientSearchMock, - } as unknown) as ElasticsearchClient; + } as unknown as ElasticsearchClient; const resp = await fetchTransactionDurationRanges( esClientMock, diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.ts index 487b23e76a10..a530c997876c 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.ts @@ -71,11 +71,13 @@ export const fetchTransactionDurationRanges = async ( ); } - return (resp.body.aggregations - .logspace_ranges as estypes.AggregationsMultiBucketAggregate<{ - from: number; - doc_count: number; - }>).buckets + return ( + resp.body.aggregations + .logspace_ranges as estypes.AggregationsMultiBucketAggregate<{ + from: number; + doc_count: number; + }> + ).buckets .map((d) => ({ key: d.from, doc_count: d.doc_count, diff --git a/x-pack/plugins/apm/server/lib/search_strategies/search_strategy_provider.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/search_strategy_provider.test.ts index f1f4bf637b51..b56ab83f547f 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/search_strategy_provider.test.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/search_strategy_provider.test.ts @@ -134,14 +134,14 @@ describe('APM Correlations search strategy', () => { mockClientFieldCaps = jest.fn(clientFieldCapsMock); mockClientSearch = jest.fn(clientSearchMock); mockGetApmIndicesMock = jest.fn(getApmIndicesMock); - mockDeps = ({ + mockDeps = { esClient: { asCurrentUser: { fieldCaps: mockClientFieldCaps, search: mockClientSearch, }, }, - } as unknown) as SearchStrategyDependencies; + } as unknown as SearchStrategyDependencies; params = { start: '2020', end: '2021', diff --git a/x-pack/plugins/apm/server/lib/search_strategies/search_strategy_provider.ts b/x-pack/plugins/apm/server/lib/search_strategies/search_strategy_provider.ts index c0376852b250..cec10294460b 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/search_strategy_provider.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/search_strategy_provider.ts @@ -41,9 +41,8 @@ interface SearchServiceState { rawResponse: TRawResponse; } -type GetSearchServiceState< - TRawResponse extends RawResponseBase -> = () => SearchServiceState; +type GetSearchServiceState = + () => SearchServiceState; export type SearchServiceProvider< TSearchStrategyClientParams extends SearchStrategyClientParams, diff --git a/x-pack/plugins/apm/server/lib/search_strategies/utils/compute_expectations_and_ranges.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/utils/compute_expectations_and_ranges.test.ts index 8fb4ecc57e7a..523b40988d52 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/utils/compute_expectations_and_ranges.test.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/utils/compute_expectations_and_ranges.test.ts @@ -28,17 +28,11 @@ describe('aggregation utils', () => { it('returns expectations and ranges with adjusted fractions', async () => { const { expectations, ranges } = computeExpectationsAndRanges([ - 1, - 3, - 3, - 5, + 1, 3, 3, 5, ]); expect(expectations.length).toBe(ranges.length); expect(expectations).toEqual([ - 1, - 2.333333333333333, - 3.666666666666667, - 5, + 1, 2.333333333333333, 3.666666666666667, 5, ]); expect(ranges).toEqual([ { to: 1 }, @@ -50,29 +44,12 @@ describe('aggregation utils', () => { it('returns expectation and ranges adjusted when percentiles have equal values', async () => { const { expectations, ranges } = computeExpectationsAndRanges([ - 5000, - 5000, - 3090428, - 3090428, - 3090428, - 3618812, - 3618812, - 3618812, - 3618812, - 3696636, - 3696636, - 3696636, - 3696636, - 3696636, - 3696636, + 5000, 5000, 3090428, 3090428, 3090428, 3618812, 3618812, 3618812, + 3618812, 3696636, 3696636, 3696636, 3696636, 3696636, 3696636, ]); expect(expectations.length).toBe(ranges.length); expect(expectations).toEqual([ - 5000, - 1856256.7999999998, - 3392361.714285714, - 3665506.4, - 3696636, + 5000, 1856256.7999999998, 3392361.714285714, 3665506.4, 3696636, ]); expect(ranges).toEqual([ { diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts b/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts index 98cfc7715d6f..f6af04458260 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts +++ b/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts @@ -107,10 +107,8 @@ export async function getServiceAnomalies({ getMLJobIds(ml.anomalyDetectors, environment), ]); - const typedAnomalyResponse: ESSearchResponse< - unknown, - typeof params - > = anomalyResponse as any; + const typedAnomalyResponse: ESSearchResponse = + anomalyResponse as any; const relevantBuckets = uniqBy( sortBy( // make sure we only return data for jobs that are available in this space diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_map_from_trace_ids.ts b/x-pack/plugins/apm/server/lib/service_map/get_service_map_from_trace_ids.ts index ed99f1909ab0..7915f1892230 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_service_map_from_trace_ids.ts +++ b/x-pack/plugins/apm/server/lib/service_map/get_service_map_from_trace_ids.ts @@ -46,10 +46,8 @@ export async function getServiceMapFromTraceIds({ setup: Setup & SetupTimeRange; traceIds: string[]; }) { - const serviceMapFromTraceIdsScriptResponse = await fetchServicePathsFromTraceIds( - setup, - traceIds - ); + const serviceMapFromTraceIdsScriptResponse = + await fetchServicePathsFromTraceIds(setup, traceIds); const serviceMapScriptedAggValue = serviceMapFromTraceIdsScriptResponse.aggregations?.service_map.value; diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.test.ts b/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.test.ts index 542d240b1cd1..e9d163432ef9 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.test.ts +++ b/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.test.ts @@ -13,7 +13,7 @@ import { ENVIRONMENT_ALL } from '../../../common/environment_filter_values'; describe('getServiceMapServiceNodeInfo', () => { describe('with no results', () => { it('returns null data', async () => { - const setup = ({ + const setup = { apmEventClient: { search: () => Promise.resolve({ @@ -22,7 +22,7 @@ describe('getServiceMapServiceNodeInfo', () => { }, indices: {}, uiFilters: {}, - } as unknown) as Setup & SetupTimeRange; + } as unknown as Setup & SetupTimeRange; const serviceName = 'test service name'; const result = await getServiceMapServiceNodeInfo({ environment: 'test environment', @@ -51,7 +51,7 @@ describe('getServiceMapServiceNodeInfo', () => { noHits: false, }); - const setup = ({ + const setup = { apmEventClient: { search: () => Promise.resolve({ @@ -72,7 +72,7 @@ describe('getServiceMapServiceNodeInfo', () => { 'xpack.apm.metricsInterval': 30, }, uiFilters: { environment: 'test environment' }, - } as unknown) as Setup & SetupTimeRange; + } as unknown as Setup & SetupTimeRange; const serviceName = 'test service name'; const result = await getServiceMapServiceNodeInfo({ setup, diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.ts b/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.ts index f74c68be1c8c..21cea9bfc87f 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.ts +++ b/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.ts @@ -75,17 +75,13 @@ export function getServiceMapServiceNodeInfo({ setup, }; - const [ - errorStats, - transactionStats, - cpuStats, - memoryStats, - ] = await Promise.all([ - getErrorStats(taskParams), - getTransactionStats(taskParams), - getCpuStats(taskParams), - getMemoryStats(taskParams), - ]); + const [errorStats, transactionStats, cpuStats, memoryStats] = + await Promise.all([ + getErrorStats(taskParams), + getTransactionStats(taskParams), + getCpuStats(taskParams), + getMemoryStats(taskParams), + ]); return { ...errorStats, transactionStats, diff --git a/x-pack/plugins/apm/server/lib/service_map/transform_service_map_responses.ts b/x-pack/plugins/apm/server/lib/service_map/transform_service_map_responses.ts index f29c7c9da97a..0cdbdc26c69d 100644 --- a/x-pack/plugins/apm/server/lib/service_map/transform_service_map_responses.ts +++ b/x-pack/plugins/apm/server/lib/service_map/transform_service_map_responses.ts @@ -194,11 +194,13 @@ export function transformServiceMapResponses(response: ServiceMapResponse) { // Instead of adding connections in two directions, // we add a `bidirectional` flag to use in styling - const dedupedConnections = (sortBy( - Object.values(connectionsById), - // make sure that order is stable - 'id' - ) as ConnectionWithId[]).reduce< + const dedupedConnections = ( + sortBy( + Object.values(connectionsById), + // make sure that order is stable + 'id' + ) as ConnectionWithId[] + ).reduce< Array< ConnectionWithId & { bidirectional?: boolean; isInverseEdge?: boolean } > diff --git a/x-pack/plugins/apm/server/lib/services/annotations/get_stored_annotations.ts b/x-pack/plugins/apm/server/lib/services/annotations/get_stored_annotations.ts index e811031fdddd..6a1012a816c7 100644 --- a/x-pack/plugins/apm/server/lib/services/annotations/get_stored_annotations.ts +++ b/x-pack/plugins/apm/server/lib/services/annotations/get_stored_annotations.ts @@ -55,15 +55,13 @@ export function getStoredAnnotations({ }; try { - const response: ESSearchResponse< - ESAnnotation, - { body: typeof body } - > = await (unwrapEsResponse( - client.search({ - index: annotationsClient.index, - body, - }) - ) as any); + const response: ESSearchResponse = + await (unwrapEsResponse( + client.search({ + index: annotationsClient.index, + body, + }) + ) as any); return response.hits.hits.map((hit) => { return { diff --git a/x-pack/plugins/apm/server/lib/services/annotations/index.test.ts b/x-pack/plugins/apm/server/lib/services/annotations/index.test.ts index 6d65c971baa3..8d64e84844d5 100644 --- a/x-pack/plugins/apm/server/lib/services/annotations/index.test.ts +++ b/x-pack/plugins/apm/server/lib/services/annotations/index.test.ts @@ -95,7 +95,7 @@ describe('getServiceAnnotations', () => { }), { mockResponse: () => - (responses.shift() as unknown) as ESSearchResponse< + responses.shift() as unknown as ESSearchResponse< unknown, ESSearchRequest, { diff --git a/x-pack/plugins/apm/server/lib/services/get_service_error_groups/index.ts b/x-pack/plugins/apm/server/lib/services/get_service_error_groups/index.ts index fc4dc44b259f..087d0408ebf3 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_error_groups/index.ts +++ b/x-pack/plugins/apm/server/lib/services/get_service_error_groups/index.ts @@ -87,11 +87,11 @@ export async function getServiceErrorGroups({ sample: { top_hits: { size: 1, - _source: ([ + _source: [ ERROR_LOG_MESSAGE, ERROR_EXC_MESSAGE, '@timestamp', - ] as any) as string, + ] as any as string, sort: { '@timestamp': 'desc', }, diff --git a/x-pack/plugins/apm/server/lib/services/get_services/get_services_items.ts b/x-pack/plugins/apm/server/lib/services/get_services/get_services_items.ts index 0f8405b241b5..41f43d4b1499 100644 --- a/x-pack/plugins/apm/server/lib/services/get_services/get_services_items.ts +++ b/x-pack/plugins/apm/server/lib/services/get_services/get_services_items.ts @@ -39,18 +39,15 @@ export async function getServicesItems({ maxNumServices: MAX_NUMBER_OF_SERVICES, }; - const [ - transactionStats, - servicesFromMetricDocuments, - healthStatuses, - ] = await Promise.all([ - getServiceTransactionStats(params), - getServicesFromMetricDocuments(params), - getHealthStatuses(params).catch((err) => { - logger.error(err); - return []; - }), - ]); + const [transactionStats, servicesFromMetricDocuments, healthStatuses] = + await Promise.all([ + getServiceTransactionStats(params), + getServicesFromMetricDocuments(params), + getHealthStatuses(params).catch((err) => { + logger.error(err); + return []; + }), + ]); return mergeServiceStats({ transactionStats, diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/convert_settings_to_string.ts b/x-pack/plugins/apm/server/lib/settings/agent_configuration/convert_settings_to_string.ts index 3ec10f6bf0c6..e5f6b3678930 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/convert_settings_to_string.ts +++ b/x-pack/plugins/apm/server/lib/settings/agent_configuration/convert_settings_to_string.ts @@ -16,11 +16,13 @@ export function convertConfigSettingsToString( const config = hit._source; if (config.settings?.transaction_sample_rate) { - config.settings.transaction_sample_rate = config.settings.transaction_sample_rate.toString(); + config.settings.transaction_sample_rate = + config.settings.transaction_sample_rate.toString(); } if (config.settings?.transaction_max_spans) { - config.settings.transaction_max_spans = config.settings.transaction_max_spans.toString(); + config.settings.transaction_max_spans = + config.settings.transaction_max_spans.toString(); } return hit; diff --git a/x-pack/plugins/apm/server/lib/settings/apm_indices/save_apm_indices.test.ts b/x-pack/plugins/apm/server/lib/settings/apm_indices/save_apm_indices.test.ts index 653794fffd17..bce6857aa4ff 100644 --- a/x-pack/plugins/apm/server/lib/settings/apm_indices/save_apm_indices.test.ts +++ b/x-pack/plugins/apm/server/lib/settings/apm_indices/save_apm_indices.test.ts @@ -10,9 +10,9 @@ import { SavedObjectsClientContract } from '../../../../../../../src/core/server describe('saveApmIndices', () => { it('should trim and strip empty settings', async () => { - const savedObjectsClient = ({ + const savedObjectsClient = { create: jest.fn(), - } as unknown) as SavedObjectsClientContract; + } as unknown as SavedObjectsClientContract; const apmIndices = { settingA: 'aa', diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/create_or_update_custom_link.test.ts b/x-pack/plugins/apm/server/lib/settings/custom_link/create_or_update_custom_link.test.ts index 051b9e2809e4..1cec38ad4af6 100644 --- a/x-pack/plugins/apm/server/lib/settings/custom_link/create_or_update_custom_link.test.ts +++ b/x-pack/plugins/apm/server/lib/settings/custom_link/create_or_update_custom_link.test.ts @@ -12,23 +12,23 @@ import { createOrUpdateCustomLink } from './create_or_update_custom_link'; describe('Create or Update Custom link', () => { const internalClientIndexMock = jest.fn(); - const mockedSetup = ({ + const mockedSetup = { internalClient: { index: internalClientIndexMock, }, indices: { apmCustomLinkIndex: 'apmCustomLinkIndex', }, - } as unknown) as Setup; + } as unknown as Setup; - const customLink = ({ + const customLink = { label: 'foo', url: 'http://elastic.com/{{trace.id}}', filters: [ { key: 'service.name', value: 'opbeans-java' }, { key: 'transaction.type', value: 'Request' }, ], - } as unknown) as CustomLink; + } as unknown as CustomLink; afterEach(() => { internalClientIndexMock.mockClear(); }); diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/get_transaction.test.ts b/x-pack/plugins/apm/server/lib/settings/custom_link/get_transaction.test.ts index dc12ac285254..03d0120b0043 100644 --- a/x-pack/plugins/apm/server/lib/settings/custom_link/get_transaction.test.ts +++ b/x-pack/plugins/apm/server/lib/settings/custom_link/get_transaction.test.ts @@ -23,7 +23,7 @@ describe('custom link get transaction', () => { it('fetches without filter', async () => { mock = await inspectSearchParams((setup) => getTransaction({ - setup: (setup as unknown) as Setup, + setup: setup as unknown as Setup, }) ); @@ -32,7 +32,7 @@ describe('custom link get transaction', () => { it('fetches with all filter', async () => { mock = await inspectSearchParams((setup) => getTransaction({ - setup: (setup as unknown) as Setup, + setup: setup as unknown as Setup, filters: { [SERVICE_NAME]: 'foo', [SERVICE_ENVIRONMENT]: 'bar', diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.test.ts b/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.test.ts index 2029652d6fbf..844f886c21a4 100644 --- a/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.test.ts +++ b/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.test.ts @@ -22,7 +22,7 @@ describe('List Custom Links', () => { it('fetches all custom links', async () => { mock = await inspectSearchParams((setup) => listCustomLinks({ - setup: (setup as unknown) as Setup, + setup: setup as unknown as Setup, }) ); @@ -37,7 +37,7 @@ describe('List Custom Links', () => { mock = await inspectSearchParams((setup) => listCustomLinks({ filters, - setup: (setup as unknown) as Setup, + setup: setup as unknown as Setup, }) ); diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts b/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts index 75c14b4ffc50..b7b9355bf9d9 100644 --- a/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts +++ b/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts @@ -63,12 +63,8 @@ function getRequest( ) { const { start, end } = setup; - const { - searchAggregatedTransactions, - environment, - kuery, - transactionName, - } = topTraceOptions; + const { searchAggregatedTransactions, environment, kuery, transactionName } = + topTraceOptions; const transactionNameFilter = transactionName ? [{ term: { [TRANSACTION_NAME]: transactionName } }] diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/mock_responses/transaction_groups_response.ts b/x-pack/plugins/apm/server/lib/transaction_groups/mock_responses/transaction_groups_response.ts index 25e343c90f83..1ec8d7cd76ca 100644 --- a/x-pack/plugins/apm/server/lib/transaction_groups/mock_responses/transaction_groups_response.ts +++ b/x-pack/plugins/apm/server/lib/transaction_groups/mock_responses/transaction_groups_response.ts @@ -7,7 +7,7 @@ import { ESResponse } from '../fetcher'; -export const transactionGroupsResponse = ({ +export const transactionGroupsResponse = { took: 139, timed_out: false, _shards: { total: 44, successful: 44, skipped: 0, failed: 0 }, @@ -1154,8 +1154,7 @@ export const transactionGroupsResponse = ({ url: { port: '3000', pathname: '/api/products/2/customers', - full: - 'http://opbeans-node:3000/api/products/2/customers', + full: 'http://opbeans-node:3000/api/products/2/customers', raw: '/api/products/2/customers', protocol: 'http:', hostname: 'opbeans-node', @@ -2721,4 +2720,4 @@ export const transactionGroupsResponse = ({ ], }, }, -} as unknown) as ESResponse; +} as unknown as ESResponse; diff --git a/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/fetcher.ts b/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/fetcher.ts index 95cca0081e5b..a61e0614f5b1 100644 --- a/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/fetcher.ts +++ b/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/fetcher.ts @@ -82,7 +82,7 @@ export function anomalySeriesFetcher({ }, }; - return (ml.mlSystem.mlAnomalySearch(params, []) as unknown) as Promise< + return ml.mlSystem.mlAnomalySearch(params, []) as unknown as Promise< ESSearchResponse >; }); diff --git a/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/index.ts b/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/index.ts index 73294a0bd123..0b0892febf66 100644 --- a/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/index.ts +++ b/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/index.ts @@ -77,50 +77,51 @@ export async function getAnomalySeries({ getMLJobIds(ml.anomalyDetectors, environment), ]); - const scoreSeriesCollection = anomaliesResponse?.aggregations?.job_id.buckets - .filter((bucket) => jobIds.includes(bucket.key as string)) - .map((bucket) => { - const dateBuckets = bucket.ml_avg_response_times.buckets; - - return { - jobId: bucket.key as string, - anomalyScore: compact( - dateBuckets.map((dateBucket) => { - const metrics = maybe(dateBucket.anomaly_score.top[0])?.metrics; - const score = metrics?.record_score; - - if ( - !metrics || - !isFiniteNumber(score) || - score < ANOMALY_THRESHOLD.CRITICAL - ) { - return null; - } - - const anomalyStart = Date.parse(metrics.timestamp as string); - const anomalyEnd = - anomalyStart + (metrics.bucket_span as number) * 1000; - - return { - x0: anomalyStart, - x: anomalyEnd, - y: score, - }; - }) - ), - anomalyBoundaries: dateBuckets - .filter( - (dateBucket) => - dateBucket.lower.value !== null && - dateBucket.upper.value !== null - ) - .map((dateBucket) => ({ - x: dateBucket.key, - y0: dateBucket.lower.value as number, - y: dateBucket.upper.value as number, - })), - }; - }); + const scoreSeriesCollection = + anomaliesResponse?.aggregations?.job_id.buckets + .filter((bucket) => jobIds.includes(bucket.key as string)) + .map((bucket) => { + const dateBuckets = bucket.ml_avg_response_times.buckets; + + return { + jobId: bucket.key as string, + anomalyScore: compact( + dateBuckets.map((dateBucket) => { + const metrics = maybe(dateBucket.anomaly_score.top[0])?.metrics; + const score = metrics?.record_score; + + if ( + !metrics || + !isFiniteNumber(score) || + score < ANOMALY_THRESHOLD.CRITICAL + ) { + return null; + } + + const anomalyStart = Date.parse(metrics.timestamp as string); + const anomalyEnd = + anomalyStart + (metrics.bucket_span as number) * 1000; + + return { + x0: anomalyStart, + x: anomalyEnd, + y: score, + }; + }) + ), + anomalyBoundaries: dateBuckets + .filter( + (dateBucket) => + dateBucket.lower.value !== null && + dateBucket.upper.value !== null + ) + .map((dateBucket) => ({ + x: dateBucket.key, + y0: dateBucket.lower.value as number, + y: dateBucket.upper.value as number, + })), + }; + }); if ((scoreSeriesCollection?.length ?? 0) > 1) { logger.warn( diff --git a/x-pack/plugins/apm/server/lib/transactions/get_latency_charts/index.ts b/x-pack/plugins/apm/server/lib/transactions/get_latency_charts/index.ts index c2fd718fbc95..e532240f49e2 100644 --- a/x-pack/plugins/apm/server/lib/transactions/get_latency_charts/index.ts +++ b/x-pack/plugins/apm/server/lib/transactions/get_latency_charts/index.ts @@ -79,9 +79,10 @@ function searchLatency({ filter.push({ term: { [TRANSACTION_TYPE]: transactionType } }); } - const transactionDurationField = getTransactionDurationFieldForAggregatedTransactions( - searchAggregatedTransactions - ); + const transactionDurationField = + getTransactionDurationFieldForAggregatedTransactions( + searchAggregatedTransactions + ); const params = { apm: { @@ -219,7 +220,8 @@ export async function getLatencyPeriods({ ...options, start: comparisonStart, end: comparisonEnd, - latencyAggregationType: latencyAggregationType as LatencyAggregationType, + latencyAggregationType: + latencyAggregationType as LatencyAggregationType, }) : { latencyTimeseries: [], overallAvgDuration: null }; diff --git a/x-pack/plugins/apm/server/plugin.ts b/x-pack/plugins/apm/server/plugin.ts index 1c6d1cdef37c..56185d846562 100644 --- a/x-pack/plugins/apm/server/plugin.ts +++ b/x-pack/plugins/apm/server/plugin.ts @@ -59,7 +59,8 @@ export class APMPlugin void, APMPluginSetupDependencies, APMPluginStartDependencies - > { + > +{ private currentConfig?: APMConfig; private logger?: Logger; constructor(private readonly initContext: PluginInitializerContext) { @@ -168,9 +169,10 @@ export class APMPlugin ); }); - const telemetryUsageCounter = resourcePlugins.usageCollection?.setup.createUsageCounter( - APM_SERVER_FEATURE_ID - ); + const telemetryUsageCounter = + resourcePlugins.usageCollection?.setup.createUsageCounter( + APM_SERVER_FEATURE_ID + ); registerRoutes({ core: { diff --git a/x-pack/plugins/apm/server/projections/util/merge_projection/index.ts b/x-pack/plugins/apm/server/projections/util/merge_projection/index.ts index fb2d981dd4a1..992f47c9c106 100644 --- a/x-pack/plugins/apm/server/projections/util/merge_projection/index.ts +++ b/x-pack/plugins/apm/server/projections/util/merge_projection/index.ts @@ -16,12 +16,11 @@ type SourceProjection = DeepPartial; type DeepMerge = U extends PlainObject ? T extends PlainObject - ? Omit & - { - [key in keyof U]: T extends { [k in key]: any } - ? DeepMerge - : U[key]; - } + ? Omit & { + [key in keyof U]: T extends { [k in key]: any } + ? DeepMerge + : U[key]; + } : U : U; diff --git a/x-pack/plugins/apm/server/routes/alerts/chart_preview.ts b/x-pack/plugins/apm/server/routes/alerts/chart_preview.ts index c28bca504835..012cf304aa3c 100644 --- a/x-pack/plugins/apm/server/routes/alerts/chart_preview.ts +++ b/x-pack/plugins/apm/server/routes/alerts/chart_preview.ts @@ -90,8 +90,9 @@ const transactionDurationChartPreview = createApmServerRoute({ }, }); -export const alertsChartPreviewRouteRepository = createApmServerRouteRepository() - .add(transactionErrorRateChartPreview) - .add(transactionDurationChartPreview) - .add(transactionErrorCountChartPreview) - .add(transactionDurationChartPreview); +export const alertsChartPreviewRouteRepository = + createApmServerRouteRepository() + .add(transactionErrorRateChartPreview) + .add(transactionDurationChartPreview) + .add(transactionErrorCountChartPreview) + .add(transactionDurationChartPreview); diff --git a/x-pack/plugins/apm/server/routes/environments.ts b/x-pack/plugins/apm/server/routes/environments.ts index b9d44de68157..f26734db5854 100644 --- a/x-pack/plugins/apm/server/routes/environments.ts +++ b/x-pack/plugins/apm/server/routes/environments.ts @@ -46,6 +46,5 @@ const environmentsRoute = createApmServerRoute({ }, }); -export const environmentsRouteRepository = createApmServerRouteRepository().add( - environmentsRoute -); +export const environmentsRouteRepository = + createApmServerRouteRepository().add(environmentsRoute); diff --git a/x-pack/plugins/apm/server/routes/fallback_to_transactions.ts b/x-pack/plugins/apm/server/routes/fallback_to_transactions.ts index 2c89893ea87f..f25b63d792f7 100644 --- a/x-pack/plugins/apm/server/routes/fallback_to_transactions.ts +++ b/x-pack/plugins/apm/server/routes/fallback_to_transactions.ts @@ -34,6 +34,5 @@ const fallbackToTransactionsRoute = createApmServerRoute({ }, }); -export const fallbackToTransactionsRouteRepository = createApmServerRouteRepository().add( - fallbackToTransactionsRoute -); +export const fallbackToTransactionsRouteRepository = + createApmServerRouteRepository().add(fallbackToTransactionsRoute); diff --git a/x-pack/plugins/apm/server/routes/fleet.ts b/x-pack/plugins/apm/server/routes/fleet.ts index afe18b33c482..5bfbfef5e680 100644 --- a/x-pack/plugins/apm/server/routes/fleet.ts +++ b/x-pack/plugins/apm/server/routes/fleet.ts @@ -165,8 +165,9 @@ const createCloudApmPackagePolicyRoute = createApmServerRoute({ } const savedObjectsClient = context.core.savedObjects.client; const coreStart = await resources.core.start(); - const esClient = coreStart.elasticsearch.client.asScoped(resources.request) - .asCurrentUser; + const esClient = coreStart.elasticsearch.client.asScoped( + resources.request + ).asCurrentUser; const cloudPluginSetup = plugins.cloud?.setup; const fleetPluginStart = await plugins.fleet.start(); const securityPluginStart = await plugins.security.start(); diff --git a/x-pack/plugins/apm/server/routes/historical_data/index.ts b/x-pack/plugins/apm/server/routes/historical_data/index.ts index 6e574a435bc8..be3fd29d14b9 100644 --- a/x-pack/plugins/apm/server/routes/historical_data/index.ts +++ b/x-pack/plugins/apm/server/routes/historical_data/index.ts @@ -20,6 +20,5 @@ const hasDataRoute = createApmServerRoute({ }, }); -export const historicalDataRouteRepository = createApmServerRouteRepository().add( - hasDataRoute -); +export const historicalDataRouteRepository = + createApmServerRouteRepository().add(hasDataRoute); diff --git a/x-pack/plugins/apm/server/routes/metrics.ts b/x-pack/plugins/apm/server/routes/metrics.ts index 9fa2346eb72f..f19b7b0afc4c 100644 --- a/x-pack/plugins/apm/server/routes/metrics.ts +++ b/x-pack/plugins/apm/server/routes/metrics.ts @@ -47,6 +47,5 @@ const metricsChartsRoute = createApmServerRoute({ }, }); -export const metricsRouteRepository = createApmServerRouteRepository().add( - metricsChartsRoute -); +export const metricsRouteRepository = + createApmServerRouteRepository().add(metricsChartsRoute); diff --git a/x-pack/plugins/apm/server/routes/observability_overview.ts b/x-pack/plugins/apm/server/routes/observability_overview.ts index 838bc3a1f5c6..675d6bebcbef 100644 --- a/x-pack/plugins/apm/server/routes/observability_overview.ts +++ b/x-pack/plugins/apm/server/routes/observability_overview.ts @@ -60,6 +60,7 @@ const observabilityOverviewRoute = createApmServerRoute({ }, }); -export const observabilityOverviewRouteRepository = createApmServerRouteRepository() - .add(observabilityOverviewRoute) - .add(observabilityOverviewHasDataRoute); +export const observabilityOverviewRouteRepository = + createApmServerRouteRepository() + .add(observabilityOverviewRoute) + .add(observabilityOverviewHasDataRoute); diff --git a/x-pack/plugins/apm/server/routes/register_routes/index.test.ts b/x-pack/plugins/apm/server/routes/register_routes/index.test.ts index b748d187c5e4..6cee6d8cad92 100644 --- a/x-pack/plugins/apm/server/routes/register_routes/index.test.ts +++ b/x-pack/plugins/apm/server/routes/register_routes/index.test.ts @@ -26,15 +26,15 @@ const getRegisterRouteDependencies = () => { put, }); - const coreSetup = ({ + const coreSetup = { http: { createRouter, }, - } as unknown) as CoreSetup; + } as unknown as CoreSetup; - const logger = ({ + const logger = { error: jest.fn(), - } as unknown) as Logger; + } as unknown as Logger; return { mocks: { @@ -45,14 +45,14 @@ const getRegisterRouteDependencies = () => { coreSetup, logger, }, - dependencies: ({ + dependencies: { core: { setup: coreSetup, }, logger, config: {} as APMConfig, plugins: {}, - } as unknown) as RegisterRouteDependencies, + } as unknown as RegisterRouteDependencies, }; }; diff --git a/x-pack/plugins/apm/server/routes/register_routes/index.ts b/x-pack/plugins/apm/server/routes/register_routes/index.ts index c66048948550..fb1d67ad30c2 100644 --- a/x-pack/plugins/apm/server/routes/register_routes/index.ts +++ b/x-pack/plugins/apm/server/routes/register_routes/index.ts @@ -67,10 +67,12 @@ export function registerRoutes({ const { method, pathname } = parseEndpoint(endpoint); - (router[method] as RouteRegistrar< - typeof method, - ApmPluginRequestHandlerContext - >)( + ( + router[method] as RouteRegistrar< + typeof method, + ApmPluginRequestHandlerContext + > + )( { path: pathname, options, diff --git a/x-pack/plugins/apm/server/routes/service_nodes.ts b/x-pack/plugins/apm/server/routes/service_nodes.ts index af5d8b7591d5..0a0e8a49908d 100644 --- a/x-pack/plugins/apm/server/routes/service_nodes.ts +++ b/x-pack/plugins/apm/server/routes/service_nodes.ts @@ -38,6 +38,5 @@ const serviceNodesRoute = createApmServerRoute({ }, }); -export const serviceNodeRouteRepository = createApmServerRouteRepository().add( - serviceNodesRoute -); +export const serviceNodeRouteRepository = + createApmServerRouteRepository().add(serviceNodesRoute); diff --git a/x-pack/plugins/apm/server/routes/services.ts b/x-pack/plugins/apm/server/routes/services.ts index 550781cc1a02..e0b311f2c3df 100644 --- a/x-pack/plugins/apm/server/routes/services.ts +++ b/x-pack/plugins/apm/server/routes/services.ts @@ -474,14 +474,12 @@ const serviceThroughputRoute = createApmServerRoute({ }); const { start, end } = setup; - const { - bucketSize, - intervalString, - } = getBucketSizeForAggregatedTransactions({ - start, - end, - searchAggregatedTransactions, - }); + const { bucketSize, intervalString } = + getBucketSizeForAggregatedTransactions({ + start, + end, + searchAggregatedTransactions, + }); const throughputUnit = getThroughputUnit(bucketSize); diff --git a/x-pack/plugins/apm/server/routes/settings/agent_configuration.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration.ts index 71413cc75753..b23dc8881413 100644 --- a/x-pack/plugins/apm/server/routes/settings/agent_configuration.ts +++ b/x-pack/plugins/apm/server/routes/settings/agent_configuration.ts @@ -301,12 +301,13 @@ const agentConfigurationAgentNameRoute = createApmServerRoute({ }, }); -export const agentConfigurationRouteRepository = createApmServerRouteRepository() - .add(agentConfigurationRoute) - .add(getSingleAgentConfigurationRoute) - .add(deleteAgentConfigurationRoute) - .add(createOrUpdateAgentConfigurationRoute) - .add(agentConfigurationSearchRoute) - .add(listAgentConfigurationServicesRoute) - .add(listAgentConfigurationEnvironmentsRoute) - .add(agentConfigurationAgentNameRoute); +export const agentConfigurationRouteRepository = + createApmServerRouteRepository() + .add(agentConfigurationRoute) + .add(getSingleAgentConfigurationRoute) + .add(deleteAgentConfigurationRoute) + .add(createOrUpdateAgentConfigurationRoute) + .add(agentConfigurationSearchRoute) + .add(listAgentConfigurationServicesRoute) + .add(listAgentConfigurationEnvironmentsRoute) + .add(agentConfigurationAgentNameRoute); diff --git a/x-pack/plugins/apm/server/routes/source_maps.ts b/x-pack/plugins/apm/server/routes/source_maps.ts index 6a455eca1258..e0f872239b62 100644 --- a/x-pack/plugins/apm/server/routes/source_maps.ts +++ b/x-pack/plugins/apm/server/routes/source_maps.ts @@ -98,7 +98,8 @@ const uploadSourceMapRoute = createApmServerRoute({ await updateSourceMapsOnFleetPolicies({ core, fleetPluginStart, - savedObjectsClient: (savedObjectsClient as unknown) as SavedObjectsClientContract, + savedObjectsClient: + savedObjectsClient as unknown as SavedObjectsClientContract, elasticsearchClient: esClient, }); @@ -133,7 +134,8 @@ const deleteSourceMapRoute = createApmServerRoute({ await updateSourceMapsOnFleetPolicies({ core, fleetPluginStart, - savedObjectsClient: (savedObjectsClient as unknown) as SavedObjectsClientContract, + savedObjectsClient: + savedObjectsClient as unknown as SavedObjectsClientContract, elasticsearchClient: esClient, }); } diff --git a/x-pack/plugins/apm/server/routes/transactions.ts b/x-pack/plugins/apm/server/routes/transactions.ts index c267487cd36b..ac31caacc920 100644 --- a/x-pack/plugins/apm/server/routes/transactions.ts +++ b/x-pack/plugins/apm/server/routes/transactions.ts @@ -179,22 +179,21 @@ const transactionLatencyChartsRoute = createApmServerRoute({ logger, }; - const [ - { currentPeriod, previousPeriod }, - anomalyTimeseries, - ] = await Promise.all([ - getLatencyPeriods({ - ...options, - latencyAggregationType: latencyAggregationType as LatencyAggregationType, - comparisonStart, - comparisonEnd, - }), - getAnomalySeries(options).catch((error) => { - logger.warn(`Unable to retrieve anomalies for latency charts.`); - logger.error(error); - return undefined; - }), - ]); + const [{ currentPeriod, previousPeriod }, anomalyTimeseries] = + await Promise.all([ + getLatencyPeriods({ + ...options, + latencyAggregationType: + latencyAggregationType as LatencyAggregationType, + comparisonStart, + comparisonEnd, + }), + getAnomalySeries(options).catch((error) => { + logger.warn(`Unable to retrieve anomalies for latency charts.`); + logger.error(error); + return undefined; + }), + ]); return { currentPeriod, @@ -277,12 +276,8 @@ const transactionChartsBreakdownRoute = createApmServerRoute({ const { params } = resources; const { serviceName } = params.path; - const { - environment, - kuery, - transactionName, - transactionType, - } = params.query; + const { environment, kuery, transactionName, transactionType } = + params.query; return getTransactionBreakdown({ environment, diff --git a/x-pack/plugins/apm/server/tutorial/index.ts b/x-pack/plugins/apm/server/tutorial/index.ts index 78dd1110e7c6..4c99cce24117 100644 --- a/x-pack/plugins/apm/server/tutorial/index.ts +++ b/x-pack/plugins/apm/server/tutorial/index.ts @@ -26,93 +26,95 @@ const apmIntro = i18n.translate('xpack.apm.tutorial.introduction', { }); const moduleName = 'apm'; -export const tutorialProvider = ({ - apmConfig, - apmIndices, - cloud, - isFleetPluginEnabled, -}: { - apmConfig: APMConfig; - apmIndices: ApmIndicesConfig; - cloud?: CloudSetup; - isFleetPluginEnabled: boolean; -}) => () => { - const indexPatternTitle = getApmIndexPatternTitle(apmIndices); +export const tutorialProvider = + ({ + apmConfig, + apmIndices, + cloud, + isFleetPluginEnabled, + }: { + apmConfig: APMConfig; + apmIndices: ApmIndicesConfig; + cloud?: CloudSetup; + isFleetPluginEnabled: boolean; + }) => + () => { + const indexPatternTitle = getApmIndexPatternTitle(apmIndices); - const savedObjects = [ - { - ...apmIndexPattern, - id: APM_STATIC_INDEX_PATTERN_ID, - attributes: { - ...apmIndexPattern.attributes, - title: indexPatternTitle, + const savedObjects = [ + { + ...apmIndexPattern, + id: APM_STATIC_INDEX_PATTERN_ID, + attributes: { + ...apmIndexPattern.attributes, + title: indexPatternTitle, + }, }, - }, - ]; + ]; - const artifacts: ArtifactsSchema = { - dashboards: [ - { - id: '8d3ed660-7828-11e7-8c47-65b845b5cfb3', - linkLabel: i18n.translate( - 'xpack.apm.tutorial.specProvider.artifacts.dashboards.linkLabel', + const artifacts: ArtifactsSchema = { + dashboards: [ + { + id: '8d3ed660-7828-11e7-8c47-65b845b5cfb3', + linkLabel: i18n.translate( + 'xpack.apm.tutorial.specProvider.artifacts.dashboards.linkLabel', + { + defaultMessage: 'APM dashboard', + } + ), + isOverview: true, + }, + ], + }; + + if (apmConfig['xpack.apm.ui.enabled']) { + // @ts-expect-error artifacts.application is readonly + artifacts.application = { + path: '/app/apm', + label: i18n.translate( + 'xpack.apm.tutorial.specProvider.artifacts.application.label', { - defaultMessage: 'APM dashboard', + defaultMessage: 'Launch APM', } ), - isOverview: true, - }, - ], - }; + }; + } - if (apmConfig['xpack.apm.ui.enabled']) { - // @ts-expect-error artifacts.application is readonly - artifacts.application = { - path: '/app/apm', - label: i18n.translate( - 'xpack.apm.tutorial.specProvider.artifacts.application.label', + return { + id: 'apm', + name: i18n.translate('xpack.apm.tutorial.specProvider.name', { + defaultMessage: 'APM', + }), + moduleName, + category: TutorialsCategory.OTHER, + shortDescription: apmIntro, + longDescription: i18n.translate( + 'xpack.apm.tutorial.specProvider.longDescription', { - defaultMessage: 'Launch APM', - } - ), - }; - } - - return { - id: 'apm', - name: i18n.translate('xpack.apm.tutorial.specProvider.name', { - defaultMessage: 'APM', - }), - moduleName, - category: TutorialsCategory.OTHER, - shortDescription: apmIntro, - longDescription: i18n.translate( - 'xpack.apm.tutorial.specProvider.longDescription', - { - defaultMessage: - 'Application Performance Monitoring (APM) collects in-depth \ + defaultMessage: + 'Application Performance Monitoring (APM) collects in-depth \ performance metrics and errors from inside your application. \ It allows you to monitor the performance of thousands of applications in real time. \ [Learn more]({learnMoreLink}).', - values: { - learnMoreLink: - '{config.docs.base_url}guide/en/apm/get-started/{config.docs.version}/index.html', - }, - } - ), - euiIconType: 'apmApp', - artifacts, - customStatusCheckName: 'apm_fleet_server_status_check', - onPrem: onPremInstructions({ apmConfig, isFleetPluginEnabled }), - elasticCloud: createElasticCloudInstructions(cloud), - previewImagePath: '/plugins/apm/assets/apm.png', - savedObjects, - savedObjectsInstallMsg: i18n.translate( - 'xpack.apm.tutorial.specProvider.savedObjectsInstallMsg', - { - defaultMessage: - 'An APM index pattern is required for some features in the APM UI.', - } - ), - } as TutorialSchema; -}; + values: { + learnMoreLink: + '{config.docs.base_url}guide/en/apm/get-started/{config.docs.version}/index.html', + }, + } + ), + euiIconType: 'apmApp', + artifacts, + customStatusCheckName: 'apm_fleet_server_status_check', + onPrem: onPremInstructions({ apmConfig, isFleetPluginEnabled }), + elasticCloud: createElasticCloudInstructions(cloud), + previewImagePath: '/plugins/apm/assets/apm.png', + savedObjects, + savedObjectsInstallMsg: i18n.translate( + 'xpack.apm.tutorial.specProvider.savedObjectsInstallMsg', + { + defaultMessage: + 'An APM index pattern is required for some features in the APM UI.', + } + ), + } as TutorialSchema; + }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/elements/tag_cloud/index.ts b/x-pack/plugins/canvas/canvas_plugin_src/elements/tag_cloud/index.ts index a0b464390fa2..b3543d532b9b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/elements/tag_cloud/index.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/elements/tag_cloud/index.ts @@ -13,9 +13,9 @@ export const tagCloud: ElementFactory = () => ({ help: 'Tagcloud visualization', icon: 'visTagCloud', expression: `filters - | demodata - | head 150 - | ply by="country" expression={math "count(country)" | as "Count"} + | demodata + | ply by="country" fn={math "count(country)" | as "Count"} + | filterrows fn={getCell "Count" | gte 10} | tagcloud metric={visdimension "Count"} bucket={visdimension "country"} | render`, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__fixtures__/test_styles.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__fixtures__/test_styles.js index 4f621bdd94b3..9e6729d38259 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__fixtures__/test_styles.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__fixtures__/test_styles.js @@ -19,8 +19,7 @@ export const fontStyle = { fontSize: '14px', lineHeight: '21px', }, - css: - 'font-family:Chalkboard, serif;font-weight:bolder;font-style:normal;text-decoration:underline;color:pink;text-align:center;font-size:14px;line-height:21px', + css: 'font-family:Chalkboard, serif;font-weight:bolder;font-style:normal;text-decoration:underline;color:pink;text-align:center;font-size:14px;line-height:21px', }; export const getContainerStyle = async () => { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/if.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/if.test.js index fbfcdef07611..bcf42e850ce2 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/if.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/if.test.js @@ -62,9 +62,10 @@ describe('if', () => { it('without else', () => { testScheduler.run(({ expectObservable }) => { - expectObservable( - fn('some context', { condition: false, then: () => of('foo') }) - ).toBe('(0|)', ['some context']); + expectObservable(fn('some context', { condition: false, then: () => of('foo') })).toBe( + '(0|)', + ['some context'] + ); }); }); }); @@ -78,9 +79,10 @@ describe('if', () => { ${0} `('for then with $value', ({ value }) => { testScheduler.run(({ expectObservable }) => { - expectObservable( - fn('some context', { condition: true, then: () => of(value) }) - ).toBe('(0|)', [value]); + expectObservable(fn('some context', { condition: true, then: () => of(value) })).toBe( + '(0|)', + [value] + ); }); }); @@ -92,9 +94,10 @@ describe('if', () => { ${0} `('for else with $value', ({ value }) => { testScheduler.run(({ expectObservable }) => { - expectObservable( - fn('some context', { condition: false, else: () => of(value) }) - ).toBe('(0|)', [value]); + expectObservable(fn('some context', { condition: false, else: () => of(value) })).toBe( + '(0|)', + [value] + ); }); }); }); 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 322bf7fee980..5ab7b95f0d00 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 @@ -58,9 +58,9 @@ export function ply(): ExpressionFunctionDefinition<'ply', Datatable, Arguments, }) ?? []; const originalDatatables = args.by - ? Object.values( - groupBy(input.rows, (row) => JSON.stringify(pick(row, args.by!))) - ).map((rows) => ({ ...input, rows })) + ? Object.values(groupBy(input.rows, (row) => JSON.stringify(pick(row, args.by!)))).map( + (rows) => ({ ...input, rows }) + ) : [input]; const datatables$ = originalDatatables.map((originalDatatable) => diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/filters/time_filter/components/time_filter.tsx b/x-pack/plugins/canvas/canvas_plugin_src/renderers/filters/time_filter/components/time_filter.tsx index a04eb11c2092..a8343eed272b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/filters/time_filter/components/time_filter.tsx +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/filters/time_filter/components/time_filter.tsx @@ -54,9 +54,11 @@ export interface Props { } export const TimeFilter = ({ filter, commit, dateFormat, commonlyUsedRanges = [] }: Props) => { - const setFilter = (column: string) => ({ start, end }: OnTimeChangeProps) => { - commit(`timefilter from="${start}" to=${end} column=${column}`); - }; + const setFilter = + (column: string) => + ({ start, end }: OnTimeChangeProps) => { + commit(`timefilter from="${start}" to=${end} column=${column}`); + }; const { column, start, end } = getFilterMeta(filter); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/date_format/index.tsx b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/date_format/index.tsx index ef5eb18b4459..8b966b3248ad 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/date_format/index.tsx +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/date_format/index.tsx @@ -17,9 +17,10 @@ import { SetupInitializer } from '../../../plugin'; const { DateFormat: strings } = ArgumentStrings; -const getDateFormatArgInput = (defaultDateFormats: ComponentProps['dateFormats']) => ( - props: Assign -) => ; +const getDateFormatArgInput = + (defaultDateFormats: ComponentProps['dateFormats']) => + (props: Assign) => + ; export const dateFormatInitializer: SetupInitializer> = ( core, 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 0b84abe19116..dd013116bb80 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 @@ -31,6 +31,7 @@ import { string } from './string'; import { textarea } from './textarea'; // @ts-expect-error untyped local import { toggle } from './toggle'; +import { visdimension } from './vis_dimension'; import { SetupInitializer } from '../../plugin'; @@ -48,6 +49,7 @@ export const args = [ string, textarea, toggle, + visdimension, ]; export const initializers = [dateFormatInitializer, numberFormatInitializer]; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/number_format/index.tsx b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/number_format/index.tsx index e1d86ba3ff9d..6277f41b89fe 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/number_format/index.tsx +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/number_format/index.tsx @@ -16,9 +16,10 @@ import { FORMATS_UI_SETTINGS } from '../../../../../../../src/plugins/field_form const { NumberFormat: strings } = ArgumentStrings; -const getNumberFormatArgInput = (defaultNumberFormats: ComponentProps['numberFormats']) => ( - props: Assign -) => ; +const getNumberFormatArgInput = + (defaultNumberFormats: ComponentProps['numberFormats']) => + (props: Assign) => + ; export const numberFormatInitializer: SetupInitializer> = ( core, diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.tsx b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.tsx index dcd087f511a0..d01424af3a58 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.tsx +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.tsx @@ -48,12 +48,12 @@ export const PaletteArgInput: FC = ({ onValueChange, argId, argValue, ren return palette; } - return ({ + return { id: 'custom', label: strings.getCustomPaletteLabel(), colors, gradient, - } as any) as ColorPalette; + } as any as ColorPalette; } catch (e) { renderError(); } 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 69041598f7a3..196803670ec2 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 @@ -43,6 +43,12 @@ SelectArgInput.propTypes = { }), }), argId: PropTypes.string.isRequired, + choices: PropTypes.arrayOf( + PropTypes.shape({ + name: PropTypes.string.isRequired, + value: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.bool]).isRequired, + }) + ), }; export const select = () => ({ diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/vis_dimension.tsx b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/vis_dimension.tsx new file mode 100644 index 000000000000..df75704ababb --- /dev/null +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/vis_dimension.tsx @@ -0,0 +1,99 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useState, useEffect, useCallback } from 'react'; +import { EuiButton, EuiFlexGroup, EuiFlexItem, EuiSelect } from '@elastic/eui'; +import { DatatableColumn, ExpressionAstExpression } from 'src/plugins/expressions'; +import { templateFromReactComponent } from '../../../public/lib/template_from_react_component'; +import { ArgumentStrings } from '../../../i18n'; + +const { VisDimension: strings } = ArgumentStrings; + +interface VisDimensionArgInputProps { + onValueChange: (value: ExpressionAstExpression) => void; + argValue: ExpressionAstExpression; + argId?: string; + columns: DatatableColumn[]; + typeInstance: { + options?: { + confirm?: string; + }; + }; +} + +const VisDimensionArgInput: React.FC = ({ + argValue, + typeInstance, + onValueChange, + argId, + columns, +}: { + // @todo define types + [key: string]: any; +}) => { + const [value, setValue] = useState(argValue); + const confirm = typeInstance?.options?.confirm; + + useEffect(() => { + setValue(argValue); + }, [argValue]); + + const onChange = useCallback( + (ev) => { + const onChangeFn = confirm ? setValue : onValueChange; + const astObj: ExpressionAstExpression = { + type: 'expression', + chain: [ + { + type: 'function', + function: 'visdimension', + arguments: { + _: [ev.target.value], + }, + }, + ], + }; + + onChangeFn(astObj); + }, + [confirm, onValueChange] + ); + + const options = [ + { value: '', text: strings.getDefaultOptionName(), disabled: true }, + ...columns.map((column: DatatableColumn) => ({ value: column.name, text: column.name })), + ]; + + const selectedValue = value.chain[0].arguments._?.[0]; + + const column = + columns + .map((col: DatatableColumn) => col.name) + .find((colName: string) => colName === selectedValue) || ''; + + return ( + + + + + {confirm && ( + + onValueChange(value)}> + {confirm} + + + )} + + ); +}; + +export const visdimension = () => ({ + name: 'vis_dimension', + displayName: strings.getDisplayName(), + help: strings.getHelp(), + simpleTemplate: templateFromReactComponent(VisDimensionArgInput), +}); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/models/index.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/models/index.js index 978ddb2a92f3..0762f70b1985 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/models/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/models/index.js @@ -7,5 +7,6 @@ import { pointseries } from './point_series'; import { math } from './math'; +import { tagcloud } from './tagcloud'; -export const modelSpecs = [pointseries, math]; +export const modelSpecs = [pointseries, math, tagcloud]; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/models/tagcloud.ts b/x-pack/plugins/canvas/canvas_plugin_src/uis/models/tagcloud.ts new file mode 100644 index 000000000000..11cad3461c02 --- /dev/null +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/models/tagcloud.ts @@ -0,0 +1,91 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { get } from 'lodash'; + +import { ViewStrings } from '../../../i18n'; +import { getState, getValue } from '../../../public/lib/resolved_arg'; + +const { Tagcloud: strings } = ViewStrings; + +export const tagcloud = () => ({ + name: 'tagcloud', + displayName: strings.getDisplayName(), + args: [ + { + name: 'metric', + displayName: strings.getMetricColumnDisplayName(), + help: strings.getMetricColumnHelp(), + argType: 'vis_dimension', + }, + { + name: 'bucket', + displayName: strings.getBucketColumnDisplayName(), + help: strings.getBucketColumnHelp(), + argType: 'vis_dimension', + }, + { + name: 'palette', + argType: 'palette', + }, + { + name: 'orientation', + displayName: strings.getOrientationColumnDisplayName(), + help: strings.getOrientationColumnHelp(), + argType: 'select', + default: 'single', + options: { + choices: [ + { value: 'single', name: strings.getOrientationSingle() }, + { value: 'right angled', name: strings.getOrientationRightAngled() }, + { value: 'multiple', name: strings.getOrientationMultiple() }, + ], + }, + }, + { + name: 'scale', + displayName: strings.getScaleColumnDisplayName(), + help: strings.getScaleColumnHelp(), + argType: 'select', + default: 'linear', + options: { + choices: [ + { value: 'linear', name: strings.getScaleLinear() }, + { value: 'log', name: strings.getScaleLog() }, + { value: 'square root', name: strings.getScaleSquareRoot() }, + ], + }, + }, + { + name: 'minFontSize', + displayName: strings.getMinFontHeightColumnDisplayName(), + help: strings.getMinFontHeightColumnHelp(), + argType: 'number', + default: 18, + }, + { + name: 'maxFontSize', + displayName: strings.getMaxFontHeightColumnDisplayName(), + help: strings.getMaxFontHeightColumnHelp(), + argType: 'number', + default: 72, + }, + { + name: 'showLabel', + displayName: strings.getShowLabelColumnDisplayName(), + help: strings.getShowLabelColumnHelp(), + argType: 'toggle', + default: true, + }, + ], + resolve({ context }: any) { + if (getState(context) !== 'ready') { + return { columns: [] }; + } + return { columns: get(getValue(context), 'columns', []) }; + }, +}); 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 ed8428f0203c..74ad90964823 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 @@ -32,7 +32,6 @@ import { shape } from './shape'; import { table } from './table'; // @ts-expect-error untyped local import { timefilterControl } from './timefilterControl'; - import { SetupInitializer } from '../../plugin'; export const viewSpecs = [ diff --git a/x-pack/plugins/canvas/common/lib/autocomplete.ts b/x-pack/plugins/canvas/common/lib/autocomplete.ts index d54c929b7d28..88fb6b052b95 100644 --- a/x-pack/plugins/canvas/common/lib/autocomplete.ts +++ b/x-pack/plugins/canvas/common/lib/autocomplete.ts @@ -152,10 +152,14 @@ export function getAutocompleteSuggestions( const text = expression.substr(0, position) + MARKER + expression.substr(position); try { const ast = parse(text, { addMeta: true }) as ExpressionASTWithMeta; - const { ast: newAst, fnIndex, argName, argIndex, parentFn, contextFn } = getFnArgAtPosition( - ast, - position - ); + const { + ast: newAst, + fnIndex, + argName, + argIndex, + parentFn, + contextFn, + } = getFnArgAtPosition(ast, position); const fn = newAst.node.chain[fnIndex].node; if (parentFn && fn.function.includes(MARKER) && argName) { diff --git a/x-pack/plugins/canvas/i18n/functions/dict/replace.ts b/x-pack/plugins/canvas/i18n/functions/dict/replace.ts index 0c12a36ed825..31993c1f0081 100644 --- a/x-pack/plugins/canvas/i18n/functions/dict/replace.ts +++ b/x-pack/plugins/canvas/i18n/functions/dict/replace.ts @@ -27,8 +27,7 @@ export const help: FunctionHelp> = { flags: i18n.translate('xpack.canvas.functions.replace.args.flagsHelpText', { defaultMessage: 'Specify flags. See {url}.', values: { - url: - 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp', + url: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp', }, }), replacement: i18n.translate('xpack.canvas.functions.replace.args.replacementHelpText', { diff --git a/x-pack/plugins/canvas/i18n/ui.ts b/x-pack/plugins/canvas/i18n/ui.ts index 4002da4115a2..30a09d51ffab 100644 --- a/x-pack/plugins/canvas/i18n/ui.ts +++ b/x-pack/plugins/canvas/i18n/ui.ts @@ -314,6 +314,20 @@ export const ArgumentStrings = { defaultMessage: 'A true/false toggle switch', }), }, + VisDimension: { + getDisplayName: () => + i18n.translate('xpack.canvas.uis.arguments.visDimensionTitle', { + defaultMessage: 'Column', + }), + getHelp: () => + i18n.translate('xpack.canvas.uis.arguments.visDimensionLabel', { + defaultMessage: 'Generates visConfig dimension object', + }), + getDefaultOptionName: () => + i18n.translate('xpack.canvas.uis.arguments.visDimensionDefaultOptionName', { + defaultMessage: 'Select column', + }), + }, }; export const DataSourceStrings = { @@ -1173,4 +1187,90 @@ export const ViewStrings = { "Apply the selected group name to an element's filters function to target this filter", }), }, + Tagcloud: { + getDisplayName: () => + i18n.translate('xpack.canvas.uis.views.tagcloudTitle', { + defaultMessage: 'Tag Cloud', + }), + getScaleColumnDisplayName: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.scaleDisplayName', { + defaultMessage: 'Scale', + }), + getScaleColumnHelp: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.scaleHelp', { + defaultMessage: 'Scale to determine font size of a word', + }), + getScaleLinear: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.scaleLinearLabel', { + defaultMessage: 'Linear', + }), + getScaleLog: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.scaleLogLabel', { + defaultMessage: 'Log', + }), + getScaleSquareRoot: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.scaleSquareRootLabel', { + defaultMessage: 'Square root', + }), + getOrientationColumnDisplayName: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.orientationDisplayName', { + defaultMessage: 'Orientation', + }), + getOrientationColumnHelp: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.orientationHelp', { + defaultMessage: 'Orientation of words inside tagcloud', + }), + getOrientationSingle: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.orientationSingleLabel', { + defaultMessage: 'Single', + }), + getOrientationRightAngled: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.orientationRightAngledLabel', { + defaultMessage: 'Right angled', + }), + getOrientationMultiple: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.orientationMultipleLabel', { + defaultMessage: 'Multiple', + }), + getMinFontHeightColumnDisplayName: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.minFontHeightDisplayName', { + defaultMessage: 'Minimum font height', + }), + getMinFontHeightColumnHelp: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.minFontHeightHelp', { + defaultMessage: 'Minimum height of the element font', + }), + getMaxFontHeightColumnDisplayName: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.maxFontHeightDisplayName', { + defaultMessage: 'Maximum font height', + }), + getMaxFontHeightColumnHelp: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.maxFontHeightHelp', { + defaultMessage: 'Maximum height of the element font', + }), + getShowLabelColumnDisplayName: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.showLabelDisplayName', { + defaultMessage: 'Show label', + }), + getShowLabelColumnHelp: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.showLabelHelp', { + defaultMessage: 'Show label of the chart', + }), + getMetricColumnDisplayName: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.metricDisplayName', { + defaultMessage: 'Metric', + }), + getMetricColumnHelp: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.metricHelp', { + defaultMessage: 'Metric dimension configuration', + }), + getBucketColumnDisplayName: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.bucketDisplayName', { + defaultMessage: 'Bucket', + }), + getBucketColumnHelp: () => + i18n.translate('xpack.canvas.uis.views.tagcloud.args.bucketHelp', { + defaultMessage: 'Bucket dimension configuration', + }), + }, }; diff --git a/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.tsx b/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.tsx index 1d7227d65e53..aec68993df98 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.tsx +++ b/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.tsx @@ -49,10 +49,10 @@ export const ArgTemplateForm: React.FunctionComponent = ({ [template, argumentProps, updatedHandlers] ); - const renderErrorTemplate = useCallback(() => React.createElement(errorTemplate, argumentProps), [ - errorTemplate, - argumentProps, - ]); + const renderErrorTemplate = useCallback( + () => React.createElement(errorTemplate, argumentProps), + [errorTemplate, argumentProps] + ); useEffect(() => { setHandlers(mergeWithFormHandlers(handlers)); 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 c1df18fc06d5..1526b5f6318f 100644 --- a/x-pack/plugins/canvas/public/components/datasource/datasource_component.js +++ b/x-pack/plugins/canvas/public/components/datasource/datasource_component.js @@ -87,14 +87,8 @@ export class DatasourceComponent extends PureComponent { }); setSelectedDatasource = (value) => { - const { - datasource, - resetArgs, - updateArgs, - selectDatasource, - datasources, - setSelecting, - } = this.props; + const { datasource, resetArgs, updateArgs, selectDatasource, datasources, setSelecting } = + this.props; if (datasource.name === value) { // if selecting the current datasource, reset the arguments diff --git a/x-pack/plugins/canvas/public/components/datasource/index.js b/x-pack/plugins/canvas/public/components/datasource/index.js index 5a0cbf6d05bd..06c920937f34 100644 --- a/x-pack/plugins/canvas/public/components/datasource/index.js +++ b/x-pack/plugins/canvas/public/components/datasource/index.js @@ -53,10 +53,12 @@ const mapStateToProps = (state) => ({ 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)); - }, + dispatchAstAtIndex: + ({ index, element, pageId }) => + (ast) => { + dispatch(flushContext(element.id)); + dispatch(setAstAtIndex(index, ast, element, pageId)); + }, }); const mergeProps = (stateProps, dispatchProps, ownProps) => { 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 125e5475241b..02e8b9560d52 100644 --- a/x-pack/plugins/canvas/public/components/enhance/error_boundary.tsx +++ b/x-pack/plugins/canvas/public/components/enhance/error_boundary.tsx @@ -38,10 +38,12 @@ export const errorBoundaryHoc = compose, Pick>({ - resetErrorState: ({ setError, setErrorInfo }) => () => { - setError(null); - setErrorInfo(null); - }, + resetErrorState: + ({ setError, setErrorInfo }) => + () => { + setError(null); + setErrorInfo(null); + }, }), lifecycle({ componentDidCatch(error, errorInfo) { 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.component.tsx similarity index 62% rename from x-pack/plugins/canvas/public/components/es_index_select/es_index_select.js rename to x-pack/plugins/canvas/public/components/es_index_select/es_index_select.component.tsx index 6400cb3a1c2e..636b19092123 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.component.tsx @@ -5,21 +5,35 @@ * 2.0. */ -import React from 'react'; -import PropTypes from 'prop-types'; +import React, { FocusEventHandler } from 'react'; import { EuiComboBox } from '@elastic/eui'; -import { get } from 'lodash'; + +export interface ESIndexSelectProps { + loading: boolean; + value: string; + indices: string[]; + onChange: (index: string) => void; + onBlur: FocusEventHandler | undefined; + onFocus: FocusEventHandler | undefined; +} const defaultIndex = '_all'; -export const ESIndexSelect = ({ value, loading, indices, onChange, onFocus, onBlur }) => { +export const ESIndexSelect: React.FunctionComponent = ({ + value = defaultIndex, + loading, + indices, + onChange, + onFocus, + onBlur, +}) => { const selectedOption = value !== defaultIndex ? [{ label: value }] : []; const options = indices.map((index) => ({ label: index })); return ( onChange(get(index, 'label', defaultIndex))} + onChange={([index]) => onChange(index?.label ?? defaultIndex)} onSearchChange={(searchValue) => { // resets input when user starts typing if (searchValue) { @@ -28,7 +42,7 @@ export const ESIndexSelect = ({ value, loading, indices, onChange, onFocus, onBl }} onBlur={onBlur} onFocus={onFocus} - disabled={loading} + isDisabled={loading} options={options} singleSelection={{ asPlainText: true }} isClearable={false} @@ -37,16 +51,3 @@ export const ESIndexSelect = ({ value, loading, indices, onChange, onFocus, onBl /> ); }; - -ESIndexSelect.propTypes = { - value: PropTypes.string, - onChange: PropTypes.func.isRequired, - onFocus: PropTypes.func, - onBlur: PropTypes.func, - indices: PropTypes.array.isRequired, - loading: PropTypes.bool.isRequired, -}; - -ESIndexSelect.defaultProps = { - value: defaultIndex, -}; diff --git a/x-pack/plugins/canvas/public/components/es_index_select/es_index_select.tsx b/x-pack/plugins/canvas/public/components/es_index_select/es_index_select.tsx new file mode 100644 index 000000000000..7d2e87902d2d --- /dev/null +++ b/x-pack/plugins/canvas/public/components/es_index_select/es_index_select.tsx @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useRef, useState } from 'react'; +import useEffectOnce from 'react-use/lib/useEffectOnce'; +import { getIndices } from '../../lib/es_service'; +import { + ESIndexSelect as Component, + ESIndexSelectProps as Props, +} from './es_index_select.component'; + +type ESIndexSelectProps = Omit; + +export const ESIndexSelect: React.FunctionComponent = (props) => { + const { value, onChange } = props; + + const [indices, setIndices] = useState([]); + const [loading, setLoading] = useState(true); + const mounted = useRef(true); + + useEffectOnce(() => { + getIndices().then((newIndices) => { + if (!mounted.current) { + return; + } + + if (!newIndices) { + newIndices = []; + } + + setLoading(false); + setIndices(newIndices.sort()); + if (!value && newIndices.length) { + onChange(newIndices[0]); + } + }); + + return () => { + mounted.current = false; + }; + }); + + return ; +}; diff --git a/x-pack/plugins/canvas/public/components/es_index_select/index.js b/x-pack/plugins/canvas/public/components/es_index_select/index.js deleted file mode 100644 index bcdbde06d54a..000000000000 --- a/x-pack/plugins/canvas/public/components/es_index_select/index.js +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { compose, withState, lifecycle } from 'recompose'; -import { getIndices } from '../../lib/es_service'; -import { ESIndexSelect as Component } from './es_index_select'; - -export const ESIndexSelect = compose( - withState('loading', 'setLoading', true), - withState('indices', 'setIndices', []), - lifecycle({ - componentDidMount() { - getIndices().then((indices = []) => { - const { setLoading, setIndices, value, onChange } = this.props; - setLoading(false); - setIndices(indices.sort()); - if (!value && indices.length) { - onChange(indices[0]); - } - }); - }, - }) -)(Component); diff --git a/x-pack/plugins/canvas/public/components/es_index_select/index.tsx b/x-pack/plugins/canvas/public/components/es_index_select/index.tsx new file mode 100644 index 000000000000..29a19e877060 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/es_index_select/index.tsx @@ -0,0 +1,9 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { ESIndexSelect } from './es_index_select'; +export { ESIndexSelect as ESIndexSelectComponent } from './es_index_select.component'; diff --git a/x-pack/plugins/canvas/public/components/export_app/export_app.test.tsx b/x-pack/plugins/canvas/public/components/export_app/export_app.test.tsx index 7bd856162949..8d9ea9e8b418 100644 --- a/x-pack/plugins/canvas/public/components/export_app/export_app.test.tsx +++ b/x-pack/plugins/canvas/public/components/export_app/export_app.test.tsx @@ -24,7 +24,7 @@ jest.mock('../routing', () => ({ describe('', () => { test('renders as expected', () => { - const sampleWorkpad = ({ + const sampleWorkpad = { id: 'my-workpad-abcd', css: '', pages: [ @@ -35,7 +35,7 @@ describe('', () => { elements: [3, 4, 5, 6], }, ], - } as any) as CanvasWorkpad; + } as any as CanvasWorkpad; const page1 = mount( {}} /> diff --git a/x-pack/plugins/canvas/public/components/expression_input/__stories__/expression_input.stories.tsx b/x-pack/plugins/canvas/public/components/expression_input/__stories__/expression_input.stories.tsx index 1d98aaf177b7..b5f9653aaad2 100644 --- a/x-pack/plugins/canvas/public/components/expression_input/__stories__/expression_input.stories.tsx +++ b/x-pack/plugins/canvas/public/components/expression_input/__stories__/expression_input.stories.tsx @@ -17,14 +17,12 @@ const sampleFunctionDef = { name: 'markdown', type: 'render', aliases: [], - help: - 'Adds an element that renders Markdown text. TIP: Use the `markdown` function for single numbers, metrics, and paragraphs of text.', + help: 'Adds an element that renders Markdown text. TIP: Use the `markdown` function for single numbers, metrics, and paragraphs of text.', args: { content: { name: 'content', required: false, - help: - 'A string of text that contains Markdown. To concatenate, pass the `string` function multiple times.', + help: 'A string of text that contains Markdown. To concatenate, pass the `string` function multiple times.', types: ['string'], default: '""', aliases: ['_', 'expression'], diff --git a/x-pack/plugins/canvas/public/components/function_form/function_form_context_pending.tsx b/x-pack/plugins/canvas/public/components/function_form/function_form_context_pending.tsx index 6cd7b59a2d21..c3855b42ec2f 100644 --- a/x-pack/plugins/canvas/public/components/function_form/function_form_context_pending.tsx +++ b/x-pack/plugins/canvas/public/components/function_form/function_form_context_pending.tsx @@ -18,30 +18,29 @@ interface FunctionFormContextPendingProps { updateContext: (element?: CanvasElement) => void; } -export const FunctionFormContextPending: React.FunctionComponent = ( - props -) => { - const { contextExpression, expressionType, context, updateContext } = props; - const prevContextExpression = usePrevious(contextExpression); - const fetchContext = useCallback( - (force = false) => { - // dispatch context update if none is provided - if (force || (context == null && expressionType.requiresContext)) { - updateContext(); - } - }, - [context, expressionType.requiresContext, updateContext] - ); +export const FunctionFormContextPending: React.FunctionComponent = + (props) => { + const { contextExpression, expressionType, context, updateContext } = props; + const prevContextExpression = usePrevious(contextExpression); + const fetchContext = useCallback( + (force = false) => { + // dispatch context update if none is provided + if (force || (context == null && expressionType.requiresContext)) { + updateContext(); + } + }, + [context, expressionType.requiresContext, updateContext] + ); - useEffect(() => { - const forceUpdate = - expressionType.requiresContext && prevContextExpression !== contextExpression; - fetchContext(forceUpdate); - }, [contextExpression, expressionType, fetchContext, prevContextExpression]); + useEffect(() => { + const forceUpdate = + expressionType.requiresContext && prevContextExpression !== contextExpression; + fetchContext(forceUpdate); + }, [contextExpression, expressionType, fetchContext, prevContextExpression]); - return ( -
- -
- ); -}; + return ( +
+ +
+ ); + }; diff --git a/x-pack/plugins/canvas/public/components/function_form/index.tsx b/x-pack/plugins/canvas/public/components/function_form/index.tsx index 9caf18e9e8b4..aff019d1cb69 100644 --- a/x-pack/plugins/canvas/public/components/function_form/index.tsx +++ b/x-pack/plugins/canvas/public/components/function_form/index.tsx @@ -73,11 +73,10 @@ export const FunctionForm: React.FunctionComponent = (props) [dispatch, element, expressionIndex, pageId] ); - const updateContext = useCallback(() => dispatch(fetchContext(expressionIndex, element)), [ - dispatch, - element, - expressionIndex, - ]); + const updateContext = useCallback( + () => dispatch(fetchContext(expressionIndex, element)), + [dispatch, element, expressionIndex] + ); const setArgument = useCallback( (argName: string, valueIndex: number) => (value: string | Ast | null) => { diff --git a/x-pack/plugins/canvas/public/components/function_reference_generator/function_examples.ts b/x-pack/plugins/canvas/public/components/function_reference_generator/function_examples.ts index 3181ebbb4af8..a8409270752a 100644 --- a/x-pack/plugins/canvas/public/components/function_reference_generator/function_examples.ts +++ b/x-pack/plugins/canvas/public/components/function_reference_generator/function_examples.ts @@ -35,8 +35,7 @@ all condition={gt 10} condition={lt 20}`, align="center" lHeight=48 } | render`, - help: - 'This sets the color of the metric text to `"red"` if the context passed into `metric` is greater than or equal to 0 and less than 0.8. Otherwise, the color is set to `"green"`.', + help: 'This sets the color of the metric text to `"red"` if the context passed into `metric` is greater than or equal to 0 and less than 0.8. Otherwise, the color is set to `"green"`.', }, }, alterColumn: { @@ -48,8 +47,7 @@ alterColumn column="@timestamp" name="foo"`, | alterColumn "time" name="time_in_ms" type="number" | table | render`, - help: - 'This renames the `time` column to `time_in_ms` and converts the type of the column’s values from `date` to `number`.', + help: 'This renames the `time` column to `time_in_ms` and converts the type of the column’s values from `date` to `number`.', }, }, any: { @@ -64,8 +62,7 @@ any condition={lte 10} condition={gt 30}`, | pointseries color="project" size="max(price)" | pie | render`, - help: - 'This filters out any rows that don’t contain `"elasticsearch"`, `"kibana"` or `"x-pack"` in the `project` field.', + help: 'This filters out any rows that don’t contain `"elasticsearch"`, `"kibana"` or `"x-pack"` in the `project` field.', }, }, as: { @@ -90,8 +87,7 @@ asset id="asset-498f7429-4d56-42a2-a7e4-8bf08d98d114"`, usage: { expression: `image dataurl={asset "asset-c661a7cc-11be-45a1-a401-d7592ea7917a"} mode="contain" | render`, - help: - 'The image asset stored with the ID `"asset-c661a7cc-11be-45a1-a401-d7592ea7917a"` is passed into the `dataurl` argument of the `image` function to display the stored asset.', + help: 'The image asset stored with the ID `"asset-c661a7cc-11be-45a1-a401-d7592ea7917a"` is passed into the `dataurl` argument of the `image` function to display the stored asset.', }, }, axisConfig: { @@ -106,8 +102,7 @@ axisConfig position="right" min=0 max=10 tickSize=1`, xaxis={axisConfig position="top" min=0 max=400 tickSize=100} yaxis={axisConfig position="right"} | render`, - help: - 'This sets the `x-axis` to display on the top of the chart and sets the range of values to `0-400` with ticks displayed at `100` intervals. The `y-axis` is configured to display on the `right`.', + help: 'This sets the `x-axis` to display on the top of the chart and sets the range of values to `0-400` with ticks displayed at `100` intervals. The `y-axis` is configured to display on the `right`.', }, }, case: { @@ -131,8 +126,7 @@ case if={lte 50} then="green"`, default="red" } | render`, - help: - 'This sets the color of the progress indicator and the color of the label to `"green"` if the value is less than or equal to `0.5`, `"orange"` if the value is greater than `0.5` and less than or equal to `0.75`, and `"red"` if `none` of the case conditions are met.', + help: 'This sets the color of the progress indicator and the color of the label to `"green"` if the value is less than or equal to `0.5`, `"orange"` if the value is greater than `0.5` and less than or equal to `0.75`, and `"red"` if `none` of the case conditions are met.', }, }, columns: { @@ -144,8 +138,7 @@ columns exclude="username, country, age"`, | columns include="price, cost, state, project" | table | render`, - help: - 'This only keeps the `price`, `cost`, `state`, and `project` columns from the `demodata` data source and removes all other columns.', + help: 'This only keeps the `price`, `cost`, `state`, and `project` columns from the `demodata` data source and removes all other columns.', }, }, compare: { @@ -164,8 +157,7 @@ compare op="lte" to=100`, | pointseries size="size(cost)" color="project" | pie | render`, - help: - 'This maps all `project` values that aren’t `"kibana"` and `"elasticsearch"` to `"other"`. Alternatively, you can use the individual comparator functions instead of compare.', + help: 'This maps all `project` values that aren’t `"kibana"` and `"elasticsearch"` to `"other"`. Alternatively, you can use the individual comparator functions instead of compare.', }, }, containerStyle: { @@ -197,8 +189,7 @@ containerStyle backgroundImage={asset id=asset-f40d2292-cf9e-4f2c-8c6f-a504a25e9 | formatdate "LLLL" | markdown "Last updated: " {context} | render`, - help: - 'Using the `context` function allows us to pass the output, or _context_, of the previous function as a value to an argument in the next function. Here we get the formatted date string from the previous function and pass it as `content` for the markdown element.', + help: 'Using the `context` function allows us to pass the output, or _context_, of the previous function as a value to an argument in the next function. Here we get the formatted date string from the previous function and pass it as `content` for the markdown element.', }, }, csv: { @@ -212,8 +203,7 @@ containerStyle backgroundImage={asset id=asset-f40d2292-cf9e-4f2c-8c6f-a504a25e9 | pointseries color=fruit size=stock | pie | render`, - help: - 'This creates a `datatable` with `fruit` and `stock` columns with two rows. This is useful for quickly mocking data.', + help: 'This creates a `datatable` with `fruit` and `stock` columns with two rows. This is useful for quickly mocking data.', }, }, date: { @@ -253,8 +243,7 @@ dropdownControl valueColumn=agent filterColumn=agent.keyword filterGroup=group1` expression: `demodata | dropdownControl valueColumn=project filterColumn=project | render`, - help: - 'This creates a dropdown filter element. It requires a data source and uses the unique values from the given `valueColumn` (i.e. `project`) and applies the filter to the `project` column. Note: `filterColumn` should point to a keyword type field for Elasticsearch data sources.', + help: 'This creates a dropdown filter element. It requires a data source and uses the unique values from the given `valueColumn` (i.e. `project`) and applies the filter to the `project` column. Note: `filterColumn` should point to a keyword type field for Elasticsearch data sources.', }, }, eq: { @@ -275,8 +264,7 @@ eq "foo"`, | pointseries size="size(cost)" color="project" | pie | render`, - help: - 'This changes all values in the project column that don’t equal `"kibana"` or `"elasticsearch"` to `"other"`.', + help: 'This changes all values in the project column that don’t equal `"kibana"` or `"elasticsearch"` to `"other"`.', }, }, escount: { @@ -292,8 +280,7 @@ escount query="response:404" index="kibana_sample_data_logs"`, font={font size=24 family="'Open Sans', Helvetica, Arial, sans-serif" color="#000000" align=center} max={filters | escount index="kibana_sample_data_flights"} | render`, - help: - 'The first `escount` expression retrieves the number of flights that were cancelled. The second `escount` expression retrieves the total number of flights.', + help: 'The first `escount` expression retrieves the number of flights that were cancelled. The second `escount` expression retrieves the total number of flights.', }, }, esdocs: { @@ -315,8 +302,7 @@ esdocs index="kibana_sample_data_flights" sort="AvgTicketPrice, asc"`, | plot defaultStyle={seriesStyle lines=3} palette={palette "#7ECAE3" "#003A4D" gradient=true} | render`, - help: - 'This retrieves the first 10000 documents data from the `kibana_sample_data_ecommerce` index sorted by `order_date` in ascending order, and only requests the `customer_gender`, `taxful_total_price`, and `order_date` fields.', + help: 'This retrieves the first 10000 documents data from the `kibana_sample_data_ecommerce` index sorted by `order_date` in ascending order, and only requests the `customer_gender`, `taxful_total_price`, and `order_date` fields.', }, }, essql: { @@ -327,8 +313,7 @@ essql "SELECT * FROM \"apm*\"" count=10000`, | essql query="SELECT Carrier, FlightDelayMin, AvgTicketPrice FROM \"kibana_sample_data_flights\"" | table | render`, - help: - 'This retrieves the `Carrier`, `FlightDelayMin`, and `AvgTicketPrice` fields from the "kibana_sample_data_flights" index.', + help: 'This retrieves the `Carrier`, `FlightDelayMin`, and `AvgTicketPrice` fields from the "kibana_sample_data_flights" index.', }, }, exactly: { @@ -342,8 +327,7 @@ exactly column="project" value="beats"`, | pointseries x=project y="mean(age)" | plot defaultStyle={seriesStyle bars=1} | render`, - help: - 'The `exactly` filter here is added to existing filters retrieved by the `filters` function and further filters down the data to only have `"elasticsearch"` data. The `exactly` filter only applies to this one specific element and will not affect other elements in the workpad.', + help: 'The `exactly` filter here is added to existing filters retrieved by the `filters` function and further filters down the data to only have `"elasticsearch"` data. The `exactly` filter only applies to this one specific element and will not affect other elements in the workpad.', }, }, filterrows: { @@ -360,8 +344,7 @@ filterrows fn={getCell "age" | gt 50}`, | plot defaultStyle={seriesStyle points="2" lines="1"} palette={palette "#01A4A4" "#CC6666" "#D0D102" "#616161" "#00A1CB" "#32742C" "#F18D05" "#113F8C" "#61AE24" "#D70060" gradient=false} | render`, - help: - 'This uses `filterrows` to only keep data from India (`IN`), the United States (`US`), and China (`CN`).', + help: 'This uses `filterrows` to only keep data from India (`IN`), the United States (`US`), and China (`CN`).', }, }, filters: { @@ -383,8 +366,7 @@ filters group="timefilter2" group="dropdownfilter1" ungrouped=true`, italic=true } | render`, - help: - '`filters` sets the existing filters as context and accepts a `group` parameter to opt into specific filter groups. Setting `ungrouped` to `true` opts out of using global filters.', + help: '`filters` sets the existing filters as context and accepts a `group` parameter to opt into specific filter groups. Setting `ungrouped` to `true` opts out of using global filters.', }, }, font: { @@ -423,8 +405,7 @@ formatdate "MM/DD/YYYY"`, | pointseries x="time" y="sum(price)" color="state" | plot defaultStyle={seriesStyle points=5} | render`, - help: - 'This transforms the dates in the `time` field into strings that look like `"Jan ‘19"`, `"Feb ‘19"`, etc. using a MomentJS format.', + help: 'This transforms the dates in the `time` field into strings that look like `"Jan ‘19"`, `"Feb ‘19"`, etc. using a MomentJS format.', }, }, formatnumber: { @@ -438,8 +419,7 @@ formatnumber "0.0a"`, label={formatnumber "0%"} font={font size=24 family="'Open Sans', Helvetica, Arial, sans-serif" color="#000000" align="center"} | render`, - help: - 'The `formatnumber` subexpression receives the same `context` as the `progress` function, which is the output of the `math` function. It formats the value into a percentage.', + help: 'The `formatnumber` subexpression receives the same `context` as the `progress` function, which is the output of the `math` function. It formats the value into a percentage.', }, }, }); 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 a71976006d51..fe5428cea203 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 @@ -57,31 +57,27 @@ interface Props { const os = getClientPlatform(); const getDescriptionListItems = (shortcuts: ShortcutMap[]): DescriptionListItem[] => - shortcuts.map( - (shortcutKeyMap: ShortcutMap): DescriptionListItem => { - const osShortcuts = shortcutKeyMap[os]; - return { - title: shortcutKeyMap.help, - description: osShortcuts.reduce((acc: JSX.Element[], shortcut, i): JSX.Element[] => { - // replace +'s with spaces so we can display the plus symbol for the plus key - shortcut = shortcut.replace(/\+/g, ' '); - if (i !== 0) { - acc.push( {strings.getShortcutSeparator()} ); - } - acc.push( - - {getPrettyShortcut(shortcut) - .split(/( )/g) - .map((key) => - key === ' ' ? key : {key} - )} - - ); - return acc; - }, []), - }; - } - ); + shortcuts.map((shortcutKeyMap: ShortcutMap): DescriptionListItem => { + const osShortcuts = shortcutKeyMap[os]; + return { + title: shortcutKeyMap.help, + description: osShortcuts.reduce((acc: JSX.Element[], shortcut, i): JSX.Element[] => { + // replace +'s with spaces so we can display the plus symbol for the plus key + shortcut = shortcut.replace(/\+/g, ' '); + if (i !== 0) { + acc.push( {strings.getShortcutSeparator()} ); + } + acc.push( + + {getPrettyShortcut(shortcut) + .split(/( )/g) + .map((key) => (key === ' ' ? key : {key}))} + + ); + return acc; + }, []), + }; + }); export const KeyboardShortcutsDoc: FunctionComponent = ({ onClose }) => ( void }> = ({ onPreviousPage const { gotoPage } = useContext(WorkpadRoutingContext); - const onAddPage = useCallback(() => dispatch(pageActions.addPage({ gotoPage })), [ - dispatch, - gotoPage, - ]); + const onAddPage = useCallback( + () => dispatch(pageActions.addPage({ gotoPage })), + [dispatch, gotoPage] + ); const onMovePage = useCallback( (id: string, position: number) => dispatch(pageActions.movePage(id, position, gotoPage)), diff --git a/x-pack/plugins/canvas/public/components/palette_picker/palette_picker.tsx b/x-pack/plugins/canvas/public/components/palette_picker/palette_picker.tsx index dcc77b75f25c..c962dbae46b0 100644 --- a/x-pack/plugins/canvas/public/components/palette_picker/palette_picker.tsx +++ b/x-pack/plugins/canvas/public/components/palette_picker/palette_picker.tsx @@ -7,6 +7,7 @@ import React, { FC } from 'react'; import PropTypes from 'prop-types'; +import { isEqual } from 'lodash'; import { EuiColorPalettePicker, EuiColorPalettePickerPaletteProps } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; @@ -39,6 +40,15 @@ interface ClearableProps { type Props = RequiredProps | ClearableProps; +const findPalette = (colorPalette: ColorPalette | null, colorPalettes: ColorPalette[] = []) => { + const palette = colorPalettes.filter((cp) => cp.id === colorPalette?.id)[0] ?? null; + if (palette === null) { + return colorPalettes.filter((cp) => isEqual(cp.colors, colorPalette?.colors))[0] ?? null; + } + + return palette; +}; + export const PalettePicker: FC = (props) => { const colorPalettes: EuiColorPalettePickerPaletteProps[] = palettes.map((item) => ({ value: item.id, @@ -61,13 +71,15 @@ export const PalettePicker: FC = (props) => { onChange(canvasPalette || null); }; + const foundPalette = findPalette(palette, palettes); + return ( ); } @@ -84,13 +96,15 @@ export const PalettePicker: FC = (props) => { onChange(canvasPalette); }; + const foundPalette = findPalette(palette, palettes); + return ( ); }; diff --git a/x-pack/plugins/canvas/public/components/popover/popover.tsx b/x-pack/plugins/canvas/public/components/popover/popover.tsx index a2793b3759f1..0bd731476e72 100644 --- a/x-pack/plugins/canvas/public/components/popover/popover.tsx +++ b/x-pack/plugins/canvas/public/components/popover/popover.tsx @@ -86,7 +86,7 @@ export class Popover extends Component { }; const appWrapper = document.querySelector('.kbnAppWrapper'); - const EuiPopoverAny = (EuiPopover as any) as React.FC; + const EuiPopoverAny = EuiPopover as any as React.FC; return ( = ({ children, transformMatrix, width, heig // Throw if there is more than one child const childNode = React.Children.only(children); - const matrix = (transformMatrix.map((n, i) => + const matrix = transformMatrix.map((n, i) => i < 12 ? n : Math.round(n) - ) as any) as TransformMatrix3d; + ) as any as TransformMatrix3d; const newStyle: CSSProperties = { width, diff --git a/x-pack/plugins/canvas/public/components/saved_elements_modal/__stories__/fixtures/test_elements.tsx b/x-pack/plugins/canvas/public/components/saved_elements_modal/__stories__/fixtures/test_elements.tsx index 854bf9c685ad..29cb1c8d525c 100644 --- a/x-pack/plugins/canvas/public/components/saved_elements_modal/__stories__/fixtures/test_elements.tsx +++ b/x-pack/plugins/canvas/public/components/saved_elements_modal/__stories__/fixtures/test_elements.tsx @@ -30,8 +30,7 @@ export const getTestCustomElements = async () => { id: 'custom-element-', name: 'customElement3', displayName: 'Custom Element 3', - help: - 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce lobortis aliquet arcu ut turpis duis.', + help: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce lobortis aliquet arcu ut turpis duis.', image: elasticLogo, content: `{\"selectedNodes\":[{\"id\":\"group-dccf4ed7-1593-49a0-9902-caf4d4a4b7f5\",\"position\":{\"left\":250,\"top\":119,\"width\":340,\"height\":517,\"angle\":0,\"parent\":null,\"type\":\"group\"},\"expression\":\"shape fill=\\\"rgba(255,255,255,0)\\\" | render\",\"ast\":{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"shape\",\"arguments\":{\"fill\":[\"rgba(255,255,255,0)\"]}},{\"type\":\"function\",\"function\":\"render\",\"arguments\":{}}]}},{\"id\":\"element-e2c658ee-7614-4d92-a46e-2b1a81a24485\",\"position\":{\"left\":250,\"top\":405,\"width\":340,\"height\":75,\"angle\":0,\"parent\":\"group-dccf4ed7-1593-49a0-9902-caf4d4a4b7f5\",\"type\":\"element\"},\"expression\":\"filters\\n| demodata\\n| markdown \\\"## Jane Doe\\\" \\n font={font family=\\\"'Open Sans', Helvetica, Arial, sans-serif\\\" size=14 align=\\\"center\\\" color=\\\"#000000\\\" weight=\\\"normal\\\" underline=false italic=false}\\n| render\",\"ast\":{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"filters\",\"arguments\":{}},{\"type\":\"function\",\"function\":\"demodata\",\"arguments\":{}},{\"type\":\"function\",\"function\":\"markdown\",\"arguments\":{\"_\":[\"## Jane Doe\"],\"font\":[{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"font\",\"arguments\":{\"family\":[\"'Open Sans', Helvetica, Arial, sans-serif\"],\"size\":[14],\"align\":[\"center\"],\"color\":[\"#000000\"],\"weight\":[\"normal\"],\"underline\":[false],\"italic\":[false]}}]}]}},{\"type\":\"function\",\"function\":\"render\",\"arguments\":{}}]}},{\"id\":\"element-3d16765e-5251-4954-8e2a-6c64ed465b73\",\"position\":{\"left\":250,\"top\":480,\"width\":340,\"height\":75,\"angle\":0,\"parent\":\"group-dccf4ed7-1593-49a0-9902-caf4d4a4b7f5\",\"type\":\"element\"},\"expression\":\"filters\\n| demodata\\n| markdown \\\"### Developer\\\" \\n font={font family=\\\"'Open Sans', Helvetica, Arial, sans-serif\\\" size=14 align=\\\"center\\\" color=\\\"#000000\\\" weight=\\\"normal\\\" underline=false italic=false}\\n| render css=\\\".canvasRenderEl h3 {\\ncolor: #444444;\\n}\\\"\",\"ast\":{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"filters\",\"arguments\":{}},{\"type\":\"function\",\"function\":\"demodata\",\"arguments\":{}},{\"type\":\"function\",\"function\":\"markdown\",\"arguments\":{\"_\":[\"### Developer\"],\"font\":[{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"font\",\"arguments\":{\"family\":[\"'Open Sans', Helvetica, Arial, sans-serif\"],\"size\":[14],\"align\":[\"center\"],\"color\":[\"#000000\"],\"weight\":[\"normal\"],\"underline\":[false],\"italic\":[false]}}]}]}},{\"type\":\"function\",\"function\":\"render\",\"arguments\":{\"css\":[\".canvasRenderEl h3 {\\ncolor: #444444;\\n}\"]}}]}},{\"id\":\"element-624675cf-46e9-4545-b86a-5409bbe53ac1\",\"position\":{\"left\":250,\"top\":555,\"width\":340,\"height\":81,\"angle\":0,\"parent\":\"group-dccf4ed7-1593-49a0-9902-caf4d4a4b7f5\",\"type\":\"element\"},\"expression\":\"filters\\n| demodata\\n| markdown \\n \\\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel sollicitudin mauris, ut scelerisque urna. \\\" \\n font={font family=\\\"'Open Sans', Helvetica, Arial, sans-serif\\\" size=14 align=\\\"center\\\" color=\\\"#000000\\\" weight=\\\"normal\\\" underline=false italic=false}\\n| render\",\"ast\":{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"filters\",\"arguments\":{}},{\"type\":\"function\",\"function\":\"demodata\",\"arguments\":{}},{\"type\":\"function\",\"function\":\"markdown\",\"arguments\":{\"_\":[\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel sollicitudin mauris, ut scelerisque urna. \"],\"font\":[{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"font\",\"arguments\":{\"family\":[\"'Open Sans', Helvetica, Arial, sans-serif\"],\"size\":[14],\"align\":[\"center\"],\"color\":[\"#000000\"],\"weight\":[\"normal\"],\"underline\":[false],\"italic\":[false]}}]}]}},{\"type\":\"function\",\"function\":\"render\",\"arguments\":{}}]}},{\"id\":\"element-c2916246-26dd-4c65-91c6-d1ad3f1791ee\",\"position\":{\"left\":293,\"top\":119,\"width\":254,\"height\":252,\"angle\":0,\"parent\":\"group-dccf4ed7-1593-49a0-9902-caf4d4a4b7f5\",\"type\":\"element\"},\"expression\":\"image dataurl={asset \\\"asset-0c6f377f-771e-432e-8e2e-15c3e9142ad6\\\"} mode=\\\"contain\\\"\\n| render\",\"ast\":{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"image\",\"arguments\":{\"dataurl\":[{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"asset\",\"arguments\":{\"_\":[\"asset-0c6f377f-771e-432e-8e2e-15c3e9142ad6\"]}}]}],\"mode\":[\"contain\"]}},{\"type\":\"function\",\"function\":\"render\",\"arguments\":{}}]}}]}`, }, diff --git a/x-pack/plugins/canvas/public/components/tool_tip_shortcut/index.tsx b/x-pack/plugins/canvas/public/components/tool_tip_shortcut/index.tsx index 5d739de59057..169b8fc1f59a 100644 --- a/x-pack/plugins/canvas/public/components/tool_tip_shortcut/index.tsx +++ b/x-pack/plugins/canvas/public/components/tool_tip_shortcut/index.tsx @@ -25,15 +25,13 @@ interface Props { } export const ToolTipShortcut = compose( - mapProps( - ({ namespace, action }: Props): ComponentProps => { - const shortcutMap = keymap[namespace][action]; - if (typeof shortcutMap === 'string') { - return { shortcut: '' }; - } - - const shortcuts = shortcutMap[os] || []; - return { shortcut: getPrettyShortcut(shortcuts[0]) }; + mapProps(({ namespace, action }: Props): ComponentProps => { + const shortcutMap = keymap[namespace][action]; + if (typeof shortcutMap === 'string') { + return { shortcut: '' }; } - ) + + const shortcuts = shortcutMap[os] || []; + return { shortcut: getPrettyShortcut(shortcuts[0]) }; + }) )(Component); diff --git a/x-pack/plugins/canvas/public/components/workpad/index.js b/x-pack/plugins/canvas/public/components/workpad/index.js index ae9b6a1fee22..6df639a117c4 100644 --- a/x-pack/plugins/canvas/public/components/workpad/index.js +++ b/x-pack/plugins/canvas/public/components/workpad/index.js @@ -55,9 +55,8 @@ const mergeProps = (stateProps, dispatchProps, ownProps) => { }; const AddContexts = (props) => { - const { isFullscreen, setFullscreen, undo, redo, autoplayInterval } = useContext( - WorkpadRoutingContext - ); + const { isFullscreen, setFullscreen, undo, redo, autoplayInterval } = + useContext(WorkpadRoutingContext); const platformService = usePlatformService(); @@ -131,7 +130,10 @@ export const Workpad = compose( }, }), withHandlers({ - onTransitionEnd: ({ setTransition }) => () => setTransition(null), + onTransitionEnd: + ({ setTransition }) => + () => + setTransition(null), nextPage: (props) => () => { const pageNumber = Math.min(props.selectedPageNumber + 1, props.pages.length); props.onPageChange(pageNumber); diff --git a/x-pack/plugins/canvas/public/components/workpad_app/workpad_app.scss b/x-pack/plugins/canvas/public/components/workpad_app/workpad_app.scss index 11f4efdd67a0..3f6d6887e0c8 100644 --- a/x-pack/plugins/canvas/public/components/workpad_app/workpad_app.scss +++ b/x-pack/plugins/canvas/public/components/workpad_app/workpad_app.scss @@ -73,6 +73,9 @@ $canvasLayoutFontSize: $euiFontSizeS; .euiPanel { margin-bottom: $euiSizeS; } + .euiPanel.euiSplitPanel__inner { + margin-bottom: 0; + } } .canvasLayout__footer { diff --git a/x-pack/plugins/canvas/public/components/workpad_header/edit_menu/edit_menu.tsx b/x-pack/plugins/canvas/public/components/workpad_header/edit_menu/edit_menu.tsx index 00f4810be360..f7373c6e5848 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/edit_menu/edit_menu.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_header/edit_menu/edit_menu.tsx @@ -46,15 +46,14 @@ interface OwnProps { commit: CommitFn; } -const withGlobalState = ( - commit: CommitFn, - updateGlobalState: (layoutState: LayoutState) => void -) => (type: string, payload: any) => { - const newLayoutState = commit(type, payload); - if (newLayoutState.currentScene.gestureEnd) { - updateGlobalState(newLayoutState); - } -}; +const withGlobalState = + (commit: CommitFn, updateGlobalState: (layoutState: LayoutState) => void) => + (type: string, payload: any) => { + const newLayoutState = commit(type, payload); + if (newLayoutState.currentScene.gestureEnd) { + updateGlobalState(newLayoutState); + } + }; /* * TODO: this is all copied from interactive_workpad_page and workpad_shortcuts 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 e428dbba57b9..14baf1db583a 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 @@ -106,6 +106,9 @@ export const FullscreenControl = compose( return { getAnimation }; }), withHandlers({ - onTransitionEnd: ({ setTransition }) => () => setTransition(null), + onTransitionEnd: + ({ setTransition }) => + () => + setTransition(null), }) )(FullscreenControlWithContext); diff --git a/x-pack/plugins/canvas/public/components/workpad_header/labs_control/labs_control.tsx b/x-pack/plugins/canvas/public/components/workpad_header/labs_control/labs_control.tsx index fde21c7c85c3..39d29e134cca 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/labs_control/labs_control.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_header/labs_control/labs_control.tsx @@ -34,8 +34,9 @@ export const LabsControl = () => { } const projects = getProjects(['canvas']); - const overrideCount = Object.values(projects).filter((project) => project.status.isOverride) - .length; + const overrideCount = Object.values(projects).filter( + (project) => project.status.isOverride + ).length; return ( <> diff --git a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/flyout.component.tsx b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/flyout.component.tsx index 52e80c316c1e..8c94e131b781 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/flyout.component.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/flyout.component.tsx @@ -108,9 +108,10 @@ export const ShareWebsiteFlyout: FC = ({ }) => { const notifyService = useNotifyService(); - const onCopy = useCallback(() => notifyService.info(strings.getCopyShareConfigMessage()), [ - notifyService, - ]); + const onCopy = useCallback( + () => notifyService.info(strings.getCopyShareConfigMessage()), + [notifyService] + ); const downloadRenderedWorkpad = useDownloadRenderedWorkpad(); const downloadRuntime = useDownloadRuntime(); diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/appearance_form.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/appearance_form.tsx index 027565e71c27..b3e458c39f14 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/appearance_form.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/appearance_form.tsx @@ -49,15 +49,14 @@ export const AppearanceForm: FunctionComponent = ({ padding = padding.replace('px', ''); } - const namedChange = (name: keyof Arguments) => ( - ev: ChangeEvent - ) => { - if (name === 'padding') { - return onChange(name, `${ev.target.value}px`); - } + const namedChange = + (name: keyof Arguments) => (ev: ChangeEvent) => { + if (name === 'padding') { + return onChange(name, `${ev.target.value}px`); + } - onChange(name, ev.target.value); - }; + onChange(name, ev.target.value); + }; return ( 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 2a67461dc4a7..fbadcb3efc6d 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 @@ -50,25 +50,27 @@ export const BorderForm: FunctionComponent = ({ const borderWidthVal = borderWidth ? borderWidth.replace('px', '') : ''; const radiusVal = typeof radius === 'string' ? radius.replace('px', '') : radius; - const namedChange = (name: T) => (val: Arguments[T]) => { - if (name === 'borderWidth') { - return onChange('border', `${val}px ${borderStyle} ${borderColor}`); - } - if (name === 'borderStyle') { - if (val === '') { - return onChange('border', `0px`); + const namedChange = + (name: T) => + (val: Arguments[T]) => { + if (name === 'borderWidth') { + return onChange('border', `${val}px ${borderStyle} ${borderColor}`); } - return onChange('border', `${borderWidth} ${val} ${borderColor}`); - } - if (name === 'borderRadius') { - if (val === '') { - return onChange('borderRadius', `0px`); + if (name === 'borderStyle') { + if (val === '') { + return onChange('border', `0px`); + } + return onChange('border', `${borderWidth} ${val} ${borderColor}`); + } + if (name === 'borderRadius') { + if (val === '') { + return onChange('borderRadius', `0px`); + } + return onChange('borderRadius', `${val}px`); } - return onChange('borderRadius', `${val}px`); - } - onChange(name, val); - }; + onChange(name, val); + }; const borderColorChange = (color: string) => onChange('border', `${borderWidth} ${borderStyle} ${color}`); diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/index.ts b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/index.ts index d54870922216..0aaa9a2b5b92 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/index.ts +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/index.ts @@ -34,14 +34,18 @@ interface OuterProps { const wrap = (Component: ComponentType) => // TODO: this should be in a helper withHandlers({ - getArgValue: ({ argValue }) => (name, alt) => { - const args = get(argValue, 'chain.0.arguments', {}); - return get(args, `${name}.0`, alt); - }, - setArgValue: ({ argValue, onValueChange }) => (name, val) => { - const newValue = set(argValue, `chain.0.arguments.${name}.0`, val); - onValueChange(newValue); - }, + getArgValue: + ({ argValue }) => + (name, alt) => { + const args = get(argValue, 'chain.0.arguments', {}); + return get(args, `${name}.0`, alt); + }, + setArgValue: + ({ argValue, onValueChange }) => + (name, val) => { + const newValue = set(argValue, `chain.0.arguments.${name}.0`, val); + onValueChange(newValue); + }, })(Component); export const containerStyle = () => ({ diff --git a/x-pack/plugins/canvas/public/functions/pie.ts b/x-pack/plugins/canvas/public/functions/pie.ts index a91dc16b770c..11e487273b31 100644 --- a/x-pack/plugins/canvas/public/functions/pie.ts +++ b/x-pack/plugins/canvas/public/functions/pie.ts @@ -134,17 +134,8 @@ export function pieFunctionFactory( }, }, fn: (input, args) => { - const { - tilt, - radius, - labelRadius, - labels, - hole, - legend, - palette, - font, - seriesStyle, - } = args; + const { tilt, radius, labelRadius, labels, hole, legend, palette, font, seriesStyle } = + args; const seriesStyles = keyBy(seriesStyle || [], 'label') || {}; const data: PieData[] = map(groupBy(input.rows, 'color'), (series, label = '') => { diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js b/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js index 828140c8b023..a817a4c196e7 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js @@ -71,7 +71,10 @@ 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); diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/geometry.js b/x-pack/plugins/canvas/public/lib/aeroelastic/geometry.js index 92774720d98a..9fff28142a05 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/geometry.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/geometry.js @@ -31,13 +31,15 @@ const cornerScreenPositions = (transformMatrix, a, b) => mvMultiply(transformMatrix, componentProduct(corner, [a, b, 0, 1])) ); -export const insideAABB = ({ x, y, a, b }) => (transformMatrix, aa, bb) => { - const corners = cornerScreenPositions(transformMatrix, aa, bb); - return corners.every(([xx, yy]) => { - const result = x - a <= xx && xx <= x + a && y - b <= yy && yy <= y + b; - return result; - }); -}; +export const insideAABB = + ({ x, y, a, b }) => + (transformMatrix, aa, bb) => { + const corners = cornerScreenPositions(transformMatrix, aa, bb); + return corners.every(([xx, yy]) => { + const result = x - a <= xx && xx <= x + a && y - b <= yy && yy <= y + b; + return result; + }); + }; /** * 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 a2f212704638..b4d33627d734 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/layout_functions.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/layout_functions.js @@ -228,34 +228,33 @@ const getContentShapes = (allShapes, shapes) => { const primaryShape = (shape) => (shape.type === 'annotation' ? shape.parent : shape.id); -const rotationManipulation = (config) => ({ - shape, - directShape, - cursorPosition: { x, y }, - alterSnapGesture, -}) => { - // rotate around a Z-parallel line going through the shape center (ie. around the center) - if (!shape || !directShape) { - return { transforms: [], shapes: [] }; - } - const center = shape.transformMatrix; - const centerPosition = mvMultiply(center, ORIGIN); - const vector = mvMultiply(multiply(center, directShape.localTransformMatrix), ORIGIN); - const oldAngle = Math.atan2(centerPosition[1] - vector[1], centerPosition[0] - vector[0]); - const newAngle = Math.atan2(centerPosition[1] - y, centerPosition[0] - x); - const closest45deg = (Math.round(newAngle / (Math.PI / 12)) * Math.PI) / 12; - const radius = Math.sqrt(Math.pow(centerPosition[0] - x, 2) + Math.pow(centerPosition[1] - y, 2)); - const closest45degPosition = [Math.cos(closest45deg) * radius, Math.sin(closest45deg) * radius]; - const pixelDifference = Math.sqrt( - Math.pow(closest45degPosition[0] - (centerPosition[0] - x), 2) + - Math.pow(closest45degPosition[1] - (centerPosition[1] - y), 2) - ); - const relaxed = alterSnapGesture.indexOf('relax') !== -1; - const newSnappedAngle = - pixelDifference < config.rotateSnapInPixels && !relaxed ? closest45deg : newAngle; - const result = rotateZ(oldAngle - newSnappedAngle); - return { transforms: [result], shapes: [shape.id] }; -}; +const rotationManipulation = + (config) => + ({ shape, directShape, cursorPosition: { x, y }, alterSnapGesture }) => { + // rotate around a Z-parallel line going through the shape center (ie. around the center) + if (!shape || !directShape) { + return { transforms: [], shapes: [] }; + } + const center = shape.transformMatrix; + const centerPosition = mvMultiply(center, ORIGIN); + const vector = mvMultiply(multiply(center, directShape.localTransformMatrix), ORIGIN); + const oldAngle = Math.atan2(centerPosition[1] - vector[1], centerPosition[0] - vector[0]); + const newAngle = Math.atan2(centerPosition[1] - y, centerPosition[0] - x); + const closest45deg = (Math.round(newAngle / (Math.PI / 12)) * Math.PI) / 12; + const radius = Math.sqrt( + Math.pow(centerPosition[0] - x, 2) + Math.pow(centerPosition[1] - y, 2) + ); + const closest45degPosition = [Math.cos(closest45deg) * radius, Math.sin(closest45deg) * radius]; + const pixelDifference = Math.sqrt( + Math.pow(closest45degPosition[0] - (centerPosition[0] - x), 2) + + Math.pow(closest45degPosition[1] - (centerPosition[1] - y), 2) + ); + const relaxed = alterSnapGesture.indexOf('relax') !== -1; + const newSnappedAngle = + pixelDifference < config.rotateSnapInPixels && !relaxed ? closest45deg : newAngle; + const result = rotateZ(oldAngle - newSnappedAngle); + return { transforms: [result], shapes: [shape.id] }; + }; const minimumSize = (min, { a, b, baseAB }, vector) => { // don't allow an element size of less than the minimumElementSize @@ -266,71 +265,75 @@ const minimumSize = (min, { a, b, baseAB }, vector) => { ]; }; -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) { - return { transforms: [], shapes: [] }; - } - // transform the incoming `transform` so that resizing is aligned with shape orientation - const vector = mvMultiply( - multiply( - invert(compositeComponent(shape.localTransformMatrix)), // rid the translate component - transform - ), - ORIGIN - ); - const orientationMask = [ - resizeMultiplierHorizontal[directShape.horizontalPosition], - resizeMultiplierVertical[directShape.verticalPosition], - 0, - ]; - const orientedVector = componentProduct2d(vector, orientationMask); - const cappedOrientedVector = minimumSize(config.minimumElementSize, shape, orientedVector); - return { - cumulativeTransforms: [], - cumulativeSizes: [gesture.sizes || translate2d(...cappedOrientedVector)], - shapes: [shape.id], +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) { + return { transforms: [], shapes: [] }; + } + // transform the incoming `transform` so that resizing is aligned with shape orientation + const vector = mvMultiply( + multiply( + invert(compositeComponent(shape.localTransformMatrix)), // rid the translate component + transform + ), + ORIGIN + ); + const orientationMask = [ + resizeMultiplierHorizontal[directShape.horizontalPosition], + resizeMultiplierVertical[directShape.verticalPosition], + 0, + ]; + const orientedVector = componentProduct2d(vector, orientationMask); + const cappedOrientedVector = minimumSize(config.minimumElementSize, shape, orientedVector); + return { + cumulativeTransforms: [], + cumulativeSizes: [gesture.sizes || translate2d(...cappedOrientedVector)], + shapes: [shape.id], + }; }; -}; -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) { - return { transforms: [], shapes: [] }; - } - // transform the incoming `transform` so that resizing is aligned with shape orientation - const composite = compositeComponent(shape.localTransformMatrix); - const inv = invert(composite); // rid the translate component - const vector = mvMultiply(multiply(inv, transform), ORIGIN); - const orientationMask = [ - resizeMultiplierHorizontal[directShape.horizontalPosition] / 2, - resizeMultiplierVertical[directShape.verticalPosition] / 2, - 0, - ]; - const orientedVector = componentProduct2d(vector, orientationMask); - const cappedOrientedVector = minimumSize(config.minimumElementSize, shape, orientedVector); - - const antiRotatedVector = mvMultiply( - multiply( - composite, - scale( - resizeMultiplierHorizontal[directShape.horizontalPosition], - resizeMultiplierVertical[directShape.verticalPosition], - 1 +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) { + return { transforms: [], shapes: [] }; + } + // transform the incoming `transform` so that resizing is aligned with shape orientation + const composite = compositeComponent(shape.localTransformMatrix); + const inv = invert(composite); // rid the translate component + const vector = mvMultiply(multiply(inv, transform), ORIGIN); + const orientationMask = [ + resizeMultiplierHorizontal[directShape.horizontalPosition] / 2, + resizeMultiplierVertical[directShape.verticalPosition] / 2, + 0, + ]; + const orientedVector = componentProduct2d(vector, orientationMask); + const cappedOrientedVector = minimumSize(config.minimumElementSize, shape, orientedVector); + + const antiRotatedVector = mvMultiply( + multiply( + composite, + scale( + resizeMultiplierHorizontal[directShape.horizontalPosition], + resizeMultiplierVertical[directShape.verticalPosition], + 1 + ), + translate(cappedOrientedVector[0], cappedOrientedVector[1], 0) ), - translate(cappedOrientedVector[0], cappedOrientedVector[1], 0) - ), - ORIGIN - ); - const sizeMatrix = gesture.sizes || translate2d(...cappedOrientedVector); - return { - cumulativeTransforms: [translate(antiRotatedVector[0], antiRotatedVector[1], 0)], - cumulativeSizes: [sizeMatrix], - shapes: [shape.id], + ORIGIN + ); + const sizeMatrix = gesture.sizes || translate2d(...cappedOrientedVector); + return { + cumulativeTransforms: [translate(antiRotatedVector[0], antiRotatedVector[1], 0)], + cumulativeSizes: [sizeMatrix], + shapes: [shape.id], + }; }; -}; const directShapeTranslateManipulation = (cumulativeTransforms, directShapes) => { const shapes = directShapes @@ -808,55 +811,59 @@ export const getRotationTooltipAnnotation = (config, proper, shape, intents, cur ] : []; -const resizePointAnnotations = (config, parent, a, b) => ([x, y, cursorAngle]) => { - const markerPlace = translate(x * a, y * b, config.resizeAnnotationOffsetZ); - const pixelOffset = translate( - -x * config.resizeAnnotationOffset, - -y * config.resizeAnnotationOffset, - config.atopZ + 10 - ); - const transform = multiply(markerPlace, pixelOffset); - const xName = xNames[x]; - const yName = yNames[y]; - return { - id: [config.resizeHandleName, xName, yName, parent.id].join('_'), - type: 'annotation', - subtype: config.resizeHandleName, - horizontalPosition: xName, - verticalPosition: yName, - cursorAngle, - interactive: true, - parent: parent.id, - localTransformMatrix: transform, - backgroundColor: 'rgb(0,255,0,1)', - a: config.resizeAnnotationSize, - b: config.resizeAnnotationSize, +const resizePointAnnotations = + (config, parent, a, b) => + ([x, y, cursorAngle]) => { + const markerPlace = translate(x * a, y * b, config.resizeAnnotationOffsetZ); + const pixelOffset = translate( + -x * config.resizeAnnotationOffset, + -y * config.resizeAnnotationOffset, + config.atopZ + 10 + ); + const transform = multiply(markerPlace, pixelOffset); + const xName = xNames[x]; + const yName = yNames[y]; + return { + id: [config.resizeHandleName, xName, yName, parent.id].join('_'), + type: 'annotation', + subtype: config.resizeHandleName, + horizontalPosition: xName, + verticalPosition: yName, + cursorAngle, + interactive: true, + parent: parent.id, + localTransformMatrix: transform, + backgroundColor: 'rgb(0,255,0,1)', + a: config.resizeAnnotationSize, + b: config.resizeAnnotationSize, + }; }; -}; -const resizeEdgeAnnotations = (config, parent, a, b) => ([[x0, y0], [x1, y1]]) => { - const x = a * mean(x0, x1); - const y = b * mean(y0, y1); - const markerPlace = translate(x, y, config.atopZ - 10); - const transform = markerPlace; // no offset etc. at the moment - const horizontal = y0 === y1; - const length = horizontal ? a * Math.abs(x1 - x0) : b * Math.abs(y1 - y0); - const sectionHalfLength = Math.max(0, length / 2 - config.resizeAnnotationConnectorOffset); - const width = 0.5; - return { - id: [config.resizeConnectorName, xNames[x0], yNames[y0], xNames[x1], yNames[y1], parent].join( - '_' - ), - type: 'annotation', - subtype: config.resizeConnectorName, - interactive: true, - parent: parent.id, - localTransformMatrix: transform, - backgroundColor: config.devColor, - a: horizontal ? sectionHalfLength : width, - b: horizontal ? width : sectionHalfLength, +const resizeEdgeAnnotations = + (config, parent, a, b) => + ([[x0, y0], [x1, y1]]) => { + const x = a * mean(x0, x1); + const y = b * mean(y0, y1); + const markerPlace = translate(x, y, config.atopZ - 10); + const transform = markerPlace; // no offset etc. at the moment + const horizontal = y0 === y1; + const length = horizontal ? a * Math.abs(x1 - x0) : b * Math.abs(y1 - y0); + const sectionHalfLength = Math.max(0, length / 2 - config.resizeAnnotationConnectorOffset); + const width = 0.5; + return { + id: [config.resizeConnectorName, xNames[x0], yNames[y0], xNames[x1], yNames[y1], parent].join( + '_' + ), + type: 'annotation', + subtype: config.resizeConnectorName, + interactive: true, + parent: parent.id, + localTransformMatrix: transform, + backgroundColor: config.devColor, + a: horizontal ? sectionHalfLength : width, + b: horizontal ? width : sectionHalfLength, + }; }; -}; const groupedShape = (properShape) => (shape) => shape.parent === properShape.id; const magic = (config, shape, shapes) => { @@ -951,79 +958,80 @@ const crystallizeConstraint = (shape) => { return result; }; -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; - const snapOffsetY = constrainedY ? -verticalConstraint.signedDistance : 0; - if (constrainedX || constrainedY) { - if (!snapOffsetX && !snapOffsetY) { +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; + const snapOffsetY = constrainedY ? -verticalConstraint.signedDistance : 0; + if (constrainedX || constrainedY) { + if (!snapOffsetX && !snapOffsetY) { + return shape; + } + const snapOffset = translateComponent( + multiply( + rotateZ(matrixToAngle(draggedElement.localTransformMatrix)), + translate(snapOffsetX, snapOffsetY, 0) + ) + ); + return { + ...shape, + snapDeltaMatrix: snapOffset, + }; + } else if (shape.snapDeltaMatrix || shape.snapResizeVector) { + return crystallizeConstraint(shape); + } else { return shape; } - const snapOffset = translateComponent( - multiply( - rotateZ(matrixToAngle(draggedElement.localTransformMatrix)), - translate(snapOffsetX, snapOffsetY, 0) - ) - ); - return { - ...shape, - snapDeltaMatrix: snapOffset, - }; - } else if (shape.snapDeltaMatrix || shape.snapResizeVector) { - return crystallizeConstraint(shape); - } else { - return shape; - } -}; + }; -const resizeShapeSnap = ( - horizontalConstraint, - verticalConstraint, - draggedElement, - symmetric, - horizontalPosition, - verticalPosition -) => (shape) => { - const constrainedShape = draggedElement && shape.id === draggedElement.id; - const constrainedX = horizontalConstraint && horizontalConstraint.constrained === shape.id; - const constrainedY = verticalConstraint && verticalConstraint.constrained === shape.id; - const snapOffsetX = constrainedX ? horizontalConstraint.signedDistance : 0; - const snapOffsetY = constrainedY ? -verticalConstraint.signedDistance : 0; - if (constrainedX || constrainedY) { - const multiplier = symmetric ? 1 : 0.5; - const angle = matrixToAngle(draggedElement.localTransformMatrix); - const horizontalSign = -resizeMultiplierHorizontal[horizontalPosition]; // fixme unify sign - const verticalSign = resizeMultiplierVertical[verticalPosition]; - // todo turn it into matrix algebra via matrix2d.js - const sin = Math.sin(angle); - const cos = Math.cos(angle); - const snapOffsetA = horizontalSign * (cos * snapOffsetX - sin * snapOffsetY); - const snapOffsetB = verticalSign * (sin * snapOffsetX + cos * snapOffsetY); - const snapTranslateOffset = translateComponent( - multiply( - rotateZ(angle), - translate((1 - multiplier) * -snapOffsetX, (1 - multiplier) * snapOffsetY, 0) - ) - ); - const snapSizeOffset = [multiplier * snapOffsetA, multiplier * snapOffsetB]; - return { - ...shape, - snapDeltaMatrix: snapTranslateOffset, - snapResizeVector: snapSizeOffset, - }; - } else if (constrainedShape) { - return { - ...shape, - snapDeltaMatrix: null, - snapResizeVector: null, - }; - } else { - return crystallizeConstraint(shape); - } -}; +const resizeShapeSnap = + ( + horizontalConstraint, + verticalConstraint, + draggedElement, + symmetric, + horizontalPosition, + verticalPosition + ) => + (shape) => { + const constrainedShape = draggedElement && shape.id === draggedElement.id; + const constrainedX = horizontalConstraint && horizontalConstraint.constrained === shape.id; + const constrainedY = verticalConstraint && verticalConstraint.constrained === shape.id; + const snapOffsetX = constrainedX ? horizontalConstraint.signedDistance : 0; + const snapOffsetY = constrainedY ? -verticalConstraint.signedDistance : 0; + if (constrainedX || constrainedY) { + const multiplier = symmetric ? 1 : 0.5; + const angle = matrixToAngle(draggedElement.localTransformMatrix); + const horizontalSign = -resizeMultiplierHorizontal[horizontalPosition]; // fixme unify sign + const verticalSign = resizeMultiplierVertical[verticalPosition]; + // todo turn it into matrix algebra via matrix2d.js + const sin = Math.sin(angle); + const cos = Math.cos(angle); + const snapOffsetA = horizontalSign * (cos * snapOffsetX - sin * snapOffsetY); + const snapOffsetB = verticalSign * (sin * snapOffsetX + cos * snapOffsetY); + const snapTranslateOffset = translateComponent( + multiply( + rotateZ(angle), + translate((1 - multiplier) * -snapOffsetX, (1 - multiplier) * snapOffsetY, 0) + ) + ); + const snapSizeOffset = [multiplier * snapOffsetA, multiplier * snapOffsetB]; + return { + ...shape, + snapDeltaMatrix: snapTranslateOffset, + snapResizeVector: snapSizeOffset, + }; + } else if (constrainedShape) { + return { + ...shape, + snapDeltaMatrix: null, + snapResizeVector: null, + }; + } else { + return crystallizeConstraint(shape); + } + }; const dissolveGroups = (groupsToDissolve, shapes, selectedShapes) => { return { diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/select.ts b/x-pack/plugins/canvas/public/lib/aeroelastic/select.ts index e84617a3a9fe..bc107ecdd600 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/select.ts +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/select.ts @@ -7,9 +7,11 @@ import { ActionId, Json, PlainFun, Resolve, Selector, State } from '.'; -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))))); -}; +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))))); + }; diff --git a/x-pack/plugins/canvas/public/lib/app_handler_creators.ts b/x-pack/plugins/canvas/public/lib/app_handler_creators.ts index 87c66cf19583..f678dfeb0b2b 100644 --- a/x-pack/plugins/canvas/public/lib/app_handler_creators.ts +++ b/x-pack/plugins/canvas/public/lib/app_handler_creators.ts @@ -24,19 +24,25 @@ export interface Props { // handlers for zooming in and out export const zoomHandlerCreators = { - zoomIn: ({ zoomScale, setZoomScale }: Props) => (): void => { - const scaleUp = - ZOOM_LEVELS.find((zoomLevel: number) => zoomScale < zoomLevel) || MAX_ZOOM_LEVEL; - setZoomScale(scaleUp); - }, - zoomOut: ({ zoomScale, setZoomScale }: Props) => (): void => { - const scaleDown = - ZOOM_LEVELS.slice() - .reverse() - .find((zoomLevel: number) => zoomScale > zoomLevel) || MIN_ZOOM_LEVEL; - setZoomScale(scaleDown); - }, - resetZoom: ({ setZoomScale }: Props) => (): void => { - setZoomScale(1); - }, + zoomIn: + ({ zoomScale, setZoomScale }: Props) => + (): void => { + const scaleUp = + ZOOM_LEVELS.find((zoomLevel: number) => zoomScale < zoomLevel) || MAX_ZOOM_LEVEL; + setZoomScale(scaleUp); + }, + zoomOut: + ({ zoomScale, setZoomScale }: Props) => + (): void => { + const scaleDown = + ZOOM_LEVELS.slice() + .reverse() + .find((zoomLevel: number) => zoomScale > zoomLevel) || MIN_ZOOM_LEVEL; + setZoomScale(scaleDown); + }, + resetZoom: + ({ setZoomScale }: Props) => + (): void => { + setZoomScale(1); + }, }; 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 62d405e167f1..82b982752904 100644 --- a/x-pack/plugins/canvas/public/lib/element_handler_creators.ts +++ b/x-pack/plugins/canvas/public/lib/element_handler_creators.ts @@ -52,55 +52,57 @@ export interface Props { // handlers for clone, delete, and saving custom elements export const basicHandlerCreators = { - cloneNodes: ({ insertNodes, pageId, selectToplevelNodes, selectedNodes }: Props) => (): void => { - const clonedNodes = selectedNodes && cloneSubgraphs(selectedNodes); - if (clonedNodes) { - insertNodes(clonedNodes, pageId); - selectToplevelNodes(clonedNodes); - } - }, - deleteNodes: ({ pageId, removeNodes, selectedNodes }: Props) => (): void => { - if (selectedNodes.length) { - removeNodes(selectedNodes.map(extractId), pageId); - } - }, - createCustomElement: ({ selectedNodes }: Props) => ( - name = '', - description = '', - image = '' - ): void => { - const notifyService = pluginServices.getServices().notify; - const customElementService = pluginServices.getServices().customElement; + cloneNodes: + ({ insertNodes, pageId, selectToplevelNodes, selectedNodes }: Props) => + (): void => { + const clonedNodes = selectedNodes && cloneSubgraphs(selectedNodes); + if (clonedNodes) { + insertNodes(clonedNodes, pageId); + selectToplevelNodes(clonedNodes); + } + }, + deleteNodes: + ({ pageId, removeNodes, selectedNodes }: Props) => + (): void => { + if (selectedNodes.length) { + removeNodes(selectedNodes.map(extractId), pageId); + } + }, + createCustomElement: + ({ selectedNodes }: Props) => + (name = '', description = '', image = ''): void => { + const notifyService = pluginServices.getServices().notify; + const customElementService = pluginServices.getServices().customElement; - if (selectedNodes.length) { - const content = JSON.stringify({ selectedNodes }); - const customElement = { - id: getId('custom-element'), - name: camelCase(name), - displayName: name, - help: description, - image, - content, - }; - customElementService - .create(customElement) - .then(() => - notifyService.success( - `Custom element '${customElement.displayName || customElement.id}' was saved`, - { - 'data-test-subj': 'canvasCustomElementCreate-success', - } + if (selectedNodes.length) { + const content = JSON.stringify({ selectedNodes }); + const customElement = { + id: getId('custom-element'), + name: camelCase(name), + displayName: name, + help: description, + image, + content, + }; + customElementService + .create(customElement) + .then(() => + notifyService.success( + `Custom element '${customElement.displayName || customElement.id}' was saved`, + { + 'data-test-subj': 'canvasCustomElementCreate-success', + } + ) ) - ) - .catch((error: Error) => - notifyService.warning(error, { - title: `Custom element '${ - customElement.displayName || customElement.id - }' was not saved`, - }) - ); - } - }, + .catch((error: Error) => + notifyService.warning(error, { + title: `Custom element '${ + customElement.displayName || customElement.id + }' was not saved`, + }) + ); + } + }, }; // handlers for alignment and distribution @@ -116,140 +118,176 @@ export const alignmentDistributionHandlerCreators = Object.assign( 'distributeHorizontally', 'distributeVertically', ].map((event: string) => ({ - [event]: ({ commit }: Props) => (): void => { - commit('actionEvent', { event }); - }, + [event]: + ({ commit }: Props) => + (): void => { + commit('actionEvent', { event }); + }, })) ); // handlers for group and ungroup export const groupHandlerCreators = { - groupNodes: ({ commit }: Props) => (): void => { - commit('actionEvent', { event: 'group' }); - }, - ungroupNodes: ({ commit }: Props) => (): void => { - commit('actionEvent', { event: 'ungroup' }); - }, + groupNodes: + ({ commit }: Props) => + (): void => { + commit('actionEvent', { event: 'group' }); + }, + ungroupNodes: + ({ commit }: Props) => + (): void => { + commit('actionEvent', { event: 'ungroup' }); + }, }; // handlers for cut/copy/paste export const clipboardHandlerCreators = { - cutNodes: ({ pageId, removeNodes, selectedNodes }: Props) => (): void => { - const notifyService = pluginServices.getServices().notify; + cutNodes: + ({ pageId, removeNodes, selectedNodes }: Props) => + (): void => { + const notifyService = pluginServices.getServices().notify; - if (selectedNodes.length) { - setClipboardData({ selectedNodes }); - removeNodes(selectedNodes.map(extractId), pageId); - notifyService.success('Cut element to clipboard'); - } - }, - copyNodes: ({ selectedNodes }: Props) => (): void => { - const notifyService = pluginServices.getServices().notify; + if (selectedNodes.length) { + setClipboardData({ selectedNodes }); + removeNodes(selectedNodes.map(extractId), pageId); + notifyService.success('Cut element to clipboard'); + } + }, + copyNodes: + ({ selectedNodes }: Props) => + (): void => { + const notifyService = pluginServices.getServices().notify; - if (selectedNodes.length) { - setClipboardData({ selectedNodes }); - notifyService.success('Copied element to clipboard'); - } - }, - pasteNodes: ({ insertNodes, pageId, selectToplevelNodes }: Props) => (): void => { - const { selectedNodes = [] } = JSON.parse(getClipboardData()) || {}; - const clonedNodes = selectedNodes && cloneSubgraphs(selectedNodes); - if (clonedNodes) { - insertNodes(clonedNodes, pageId); // first clone and persist the new node(s) - selectToplevelNodes(clonedNodes); // then select the cloned node(s) - } - }, + if (selectedNodes.length) { + setClipboardData({ selectedNodes }); + notifyService.success('Copied element to clipboard'); + } + }, + pasteNodes: + ({ insertNodes, pageId, selectToplevelNodes }: Props) => + (): void => { + const { selectedNodes = [] } = JSON.parse(getClipboardData()) || {}; + const clonedNodes = selectedNodes && cloneSubgraphs(selectedNodes); + if (clonedNodes) { + insertNodes(clonedNodes, pageId); // first clone and persist the new node(s) + selectToplevelNodes(clonedNodes); // then select the cloned node(s) + } + }, }; // handlers for changing element layer position // TODO: support relayering multiple elements export const layerHandlerCreators = { - bringToFront: ({ elementLayer, pageId, selectedNodes }: Props) => (): void => { - if (selectedNodes.length === 1) { - elementLayer(pageId, selectedNodes[0].id, Infinity); - } - }, - bringForward: ({ elementLayer, pageId, selectedNodes }: Props) => (): void => { - if (selectedNodes.length === 1) { - elementLayer(pageId, selectedNodes[0].id, 1); - } - }, - sendBackward: ({ elementLayer, pageId, selectedNodes }: Props) => (): void => { - if (selectedNodes.length === 1) { - elementLayer(pageId, selectedNodes[0].id, -1); - } - }, - sendToBack: ({ elementLayer, pageId, selectedNodes }: Props) => (): void => { - if (selectedNodes.length === 1) { - elementLayer(pageId, selectedNodes[0].id, -Infinity); - } - }, + bringToFront: + ({ elementLayer, pageId, selectedNodes }: Props) => + (): void => { + if (selectedNodes.length === 1) { + elementLayer(pageId, selectedNodes[0].id, Infinity); + } + }, + bringForward: + ({ elementLayer, pageId, selectedNodes }: Props) => + (): void => { + if (selectedNodes.length === 1) { + elementLayer(pageId, selectedNodes[0].id, 1); + } + }, + sendBackward: + ({ elementLayer, pageId, selectedNodes }: Props) => + (): void => { + if (selectedNodes.length === 1) { + elementLayer(pageId, selectedNodes[0].id, -1); + } + }, + sendToBack: + ({ elementLayer, pageId, selectedNodes }: Props) => + (): void => { + if (selectedNodes.length === 1) { + elementLayer(pageId, selectedNodes[0].id, -Infinity); + } + }, }; // handlers for shifting elements up, down, left, and right export const positionHandlerCreators = { - shiftUp: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { - setMultiplePositions( - selectedNodes.map((element) => { - element.position.top -= ELEMENT_SHIFT_OFFSET; - return element; - }) - ); - }, - shiftDown: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { - setMultiplePositions( - selectedNodes.map((element) => { - element.position.top += ELEMENT_SHIFT_OFFSET; - return element; - }) - ); - }, - shiftLeft: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { - setMultiplePositions( - selectedNodes.map((element) => { - element.position.left -= ELEMENT_SHIFT_OFFSET; - return element; - }) - ); - }, - shiftRight: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { - setMultiplePositions( - selectedNodes.map((element) => { - element.position.left += ELEMENT_SHIFT_OFFSET; - return element; - }) - ); - }, - nudgeUp: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { - setMultiplePositions( - selectedNodes.map((element) => { - element.position.top -= ELEMENT_NUDGE_OFFSET; - return element; - }) - ); - }, - nudgeDown: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { - setMultiplePositions( - selectedNodes.map((element) => { - element.position.top += ELEMENT_NUDGE_OFFSET; - return element; - }) - ); - }, - nudgeLeft: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { - setMultiplePositions( - selectedNodes.map((element) => { - element.position.left -= ELEMENT_NUDGE_OFFSET; - return element; - }) - ); - }, - nudgeRight: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { - setMultiplePositions( - selectedNodes.map((element) => { - element.position.left += ELEMENT_NUDGE_OFFSET; - return element; - }) - ); - }, + shiftUp: + ({ selectedNodes, setMultiplePositions }: Props) => + (): void => { + setMultiplePositions( + selectedNodes.map((element) => { + element.position.top -= ELEMENT_SHIFT_OFFSET; + return element; + }) + ); + }, + shiftDown: + ({ selectedNodes, setMultiplePositions }: Props) => + (): void => { + setMultiplePositions( + selectedNodes.map((element) => { + element.position.top += ELEMENT_SHIFT_OFFSET; + return element; + }) + ); + }, + shiftLeft: + ({ selectedNodes, setMultiplePositions }: Props) => + (): void => { + setMultiplePositions( + selectedNodes.map((element) => { + element.position.left -= ELEMENT_SHIFT_OFFSET; + return element; + }) + ); + }, + shiftRight: + ({ selectedNodes, setMultiplePositions }: Props) => + (): void => { + setMultiplePositions( + selectedNodes.map((element) => { + element.position.left += ELEMENT_SHIFT_OFFSET; + return element; + }) + ); + }, + nudgeUp: + ({ selectedNodes, setMultiplePositions }: Props) => + (): void => { + setMultiplePositions( + selectedNodes.map((element) => { + element.position.top -= ELEMENT_NUDGE_OFFSET; + return element; + }) + ); + }, + nudgeDown: + ({ selectedNodes, setMultiplePositions }: Props) => + (): void => { + setMultiplePositions( + selectedNodes.map((element) => { + element.position.top += ELEMENT_NUDGE_OFFSET; + return element; + }) + ); + }, + nudgeLeft: + ({ selectedNodes, setMultiplePositions }: Props) => + (): void => { + setMultiplePositions( + selectedNodes.map((element) => { + element.position.left -= ELEMENT_NUDGE_OFFSET; + return element; + }) + ); + }, + nudgeRight: + ({ selectedNodes, setMultiplePositions }: Props) => + (): void => { + setMultiplePositions( + selectedNodes.map((element) => { + element.position.left += ELEMENT_NUDGE_OFFSET; + return element; + }) + ); + }, }; diff --git a/x-pack/plugins/canvas/public/plugin.tsx b/x-pack/plugins/canvas/public/plugin.tsx index 3b4a6b6f1ee4..555cedb6b16a 100644 --- a/x-pack/plugins/canvas/public/plugin.tsx +++ b/x-pack/plugins/canvas/public/plugin.tsx @@ -76,7 +76,8 @@ export type CanvasStart = void; /** @internal */ export class CanvasPlugin - implements Plugin { + implements Plugin +{ private appUpdater = new BehaviorSubject(() => ({})); private initContext: PluginInitializerContext; diff --git a/x-pack/plugins/canvas/public/plugin_api.ts b/x-pack/plugins/canvas/public/plugin_api.ts index 55a7390437c2..aafbc2237a53 100644 --- a/x-pack/plugins/canvas/public/plugin_api.ts +++ b/x-pack/plugins/canvas/public/plugin_api.ts @@ -45,9 +45,10 @@ export interface SetupRegistries extends Record { transitions: any[]; } -export function getPluginApi( - expressionsPluginSetup: ExpressionsSetup -): { api: CanvasApi; registries: SetupRegistries } { +export function getPluginApi(expressionsPluginSetup: ExpressionsSetup): { + api: CanvasApi; + registries: SetupRegistries; +} { const registries: SetupRegistries = { elements: [], transformUIs: [], @@ -86,7 +87,7 @@ export function getPluginApi( // There is an issue of the canvas render definition not matching the expression render definition // due to our handlers needing additional methods. For now, we are going to cast to get to the proper // type, but we should work with AppArch to figure out how the Handlers can be genericized - expressionsPluginSetup.registerRenderer((r as unknown) as AnyExpressionRenderDefinition); + expressionsPluginSetup.registerRenderer(r as unknown as AnyExpressionRenderDefinition); }); }, diff --git a/x-pack/plugins/canvas/public/routes/workpad/hooks/use_autoplay_helper.test.tsx b/x-pack/plugins/canvas/public/routes/workpad/hooks/use_autoplay_helper.test.tsx index 0fa347e8e060..085a9093e8b8 100644 --- a/x-pack/plugins/canvas/public/routes/workpad/hooks/use_autoplay_helper.test.tsx +++ b/x-pack/plugins/canvas/public/routes/workpad/hooks/use_autoplay_helper.test.tsx @@ -19,9 +19,10 @@ const getMockedContext = (context: any) => ...context, } as WorkpadRoutingContextType); -const getContextWrapper: (context: WorkpadRoutingContextType) => FC = (context) => ({ - children, -}) => {children}; +const getContextWrapper: (context: WorkpadRoutingContextType) => FC = + (context) => + ({ children }) => + {children}; describe('useAutoplayHelper', () => { beforeEach(() => jest.useFakeTimers()); diff --git a/x-pack/plugins/canvas/public/routes/workpad/hooks/use_autoplay_helper.ts b/x-pack/plugins/canvas/public/routes/workpad/hooks/use_autoplay_helper.ts index 5015da495e47..8e375d3d5d35 100644 --- a/x-pack/plugins/canvas/public/routes/workpad/hooks/use_autoplay_helper.ts +++ b/x-pack/plugins/canvas/public/routes/workpad/hooks/use_autoplay_helper.ts @@ -8,9 +8,8 @@ import { useContext, useEffect, useRef } from 'react'; import { WorkpadRoutingContext } from '../workpad_routing_context'; export const useAutoplayHelper = () => { - const { nextPage, isFullscreen, autoplayInterval, isAutoplayPaused } = useContext( - WorkpadRoutingContext - ); + const { nextPage, isFullscreen, autoplayInterval, isAutoplayPaused } = + useContext(WorkpadRoutingContext); const timer = useRef(undefined); useEffect(() => { diff --git a/x-pack/plugins/canvas/public/routes/workpad/hooks/use_refresh_helper.test.tsx b/x-pack/plugins/canvas/public/routes/workpad/hooks/use_refresh_helper.test.tsx index 59c4821d82a7..d502e634ede0 100644 --- a/x-pack/plugins/canvas/public/routes/workpad/hooks/use_refresh_helper.test.tsx +++ b/x-pack/plugins/canvas/public/routes/workpad/hooks/use_refresh_helper.test.tsx @@ -29,9 +29,10 @@ const getMockedContext = (context: any) => ...context, } as WorkpadRoutingContextType); -const getContextWrapper: (context: WorkpadRoutingContextType) => FC = (context) => ({ - children, -}) => {children}; +const getContextWrapper: (context: WorkpadRoutingContextType) => FC = + (context) => + ({ children }) => + {children}; describe('useRefreshHelper', () => { beforeEach(() => { diff --git a/x-pack/plugins/canvas/public/services/storybook/index.ts b/x-pack/plugins/canvas/public/services/storybook/index.ts index 86ff52155a0b..06ac743265f4 100644 --- a/x-pack/plugins/canvas/public/services/storybook/index.ts +++ b/x-pack/plugins/canvas/public/services/storybook/index.ts @@ -21,14 +21,12 @@ export interface StorybookParams { workpadCount?: number; } -export const pluginServiceProviders: PluginServiceProviders< - CanvasPluginServices, - StorybookParams -> = { - ...stubProviders, - workpad: new PluginServiceProvider(workpadServiceFactory), - notify: new PluginServiceProvider(notifyServiceFactory), -}; +export const pluginServiceProviders: PluginServiceProviders = + { + ...stubProviders, + workpad: new PluginServiceProvider(workpadServiceFactory), + notify: new PluginServiceProvider(notifyServiceFactory), + }; export const argTypes = { hasTemplates: { diff --git a/x-pack/plugins/canvas/public/services/storybook/workpad.ts b/x-pack/plugins/canvas/public/services/storybook/workpad.ts index 3ecac4b49310..e4d176f49007 100644 --- a/x-pack/plugins/canvas/public/services/storybook/workpad.ts +++ b/x-pack/plugins/canvas/public/services/storybook/workpad.ts @@ -34,9 +34,10 @@ const promiseTimeout = (time: number) => () => new Promise((resolve) => setTimeo const { findNoTemplates, findNoWorkpads, findSomeTemplates } = stubs; const getRandomName = () => { - const lorem = 'Lorem ipsum dolor sit amet consectetur adipiscing elit Fusce lobortis aliquet arcu ut turpis duis'.split( - ' ' - ); + const lorem = + 'Lorem ipsum dolor sit amet consectetur adipiscing elit Fusce lobortis aliquet arcu ut turpis duis'.split( + ' ' + ); return [1, 2, 3].map(() => lorem[Math.floor(Math.random() * lorem.length)]).join(' '); }; @@ -56,16 +57,16 @@ export const getSomeWorkpads = (count = 3) => name: getRandomName(), })); -export const findSomeWorkpads = (count = 3, useStaticData = false, timeout = TIMEOUT) => ( - _term: string -) => { - return Promise.resolve() - .then(promiseTimeout(timeout)) - .then(() => ({ - total: count, - workpads: useStaticData ? stubs.getSomeWorkpads(count) : getSomeWorkpads(count), - })); -}; +export const findSomeWorkpads = + (count = 3, useStaticData = false, timeout = TIMEOUT) => + (_term: string) => { + return Promise.resolve() + .then(promiseTimeout(timeout)) + .then(() => ({ + total: count, + workpads: useStaticData ? stubs.getSomeWorkpads(count) : getSomeWorkpads(count), + })); + }; export const workpadServiceFactory: CanvasWorkpadServiceFactory = ({ workpadCount, diff --git a/x-pack/plugins/canvas/public/services/stubs/expressions.ts b/x-pack/plugins/canvas/public/services/stubs/expressions.ts index 9bd07f76eb44..6660c1c6efb3 100644 --- a/x-pack/plugins/canvas/public/services/stubs/expressions.ts +++ b/x-pack/plugins/canvas/public/services/stubs/expressions.ts @@ -22,7 +22,7 @@ export const expressionsServiceFactory: CanvasExpressionsServiceFactory = () => functionDefinitions.forEach((fn) => expressionsService.registerFunction(fn)); renderFunctions.forEach((fn) => { - expressionsService.registerRenderer((fn as unknown) as AnyExpressionRenderDefinition); + expressionsService.registerRenderer(fn as unknown as AnyExpressionRenderDefinition); }); return expressionsService; diff --git a/x-pack/plugins/canvas/public/services/stubs/workpad.ts b/x-pack/plugins/canvas/public/services/stubs/workpad.ts index 2f2598563d49..19979e51b5e4 100644 --- a/x-pack/plugins/canvas/public/services/stubs/workpad.ts +++ b/x-pack/plugins/canvas/public/services/stubs/workpad.ts @@ -39,14 +39,16 @@ const getWorkpads = (count = 3) => { export const getSomeWorkpads = (count = 3) => getWorkpads(count); -export const findSomeWorkpads = (count = 3, timeout = TIMEOUT) => (_term: string) => { - return Promise.resolve() - .then(promiseTimeout(timeout)) - .then(() => ({ - total: count, - workpads: getSomeWorkpads(count), - })); -}; +export const findSomeWorkpads = + (count = 3, timeout = TIMEOUT) => + (_term: string) => { + return Promise.resolve() + .then(promiseTimeout(timeout)) + .then(() => ({ + total: count, + workpads: getSomeWorkpads(count), + })); + }; const templates: CanvasTemplate[] = [ { @@ -65,26 +67,32 @@ const templates: CanvasTemplate[] = [ }, ]; -export const findNoWorkpads = (timeout = TIMEOUT) => (_term: string) => { - return Promise.resolve() - .then(promiseTimeout(timeout)) - .then(() => ({ - total: 0, - workpads: [], - })); -}; +export const findNoWorkpads = + (timeout = TIMEOUT) => + (_term: string) => { + return Promise.resolve() + .then(promiseTimeout(timeout)) + .then(() => ({ + total: 0, + workpads: [], + })); + }; -export const findSomeTemplates = (timeout = TIMEOUT) => () => { - return Promise.resolve() - .then(promiseTimeout(timeout)) - .then(() => getSomeTemplates()); -}; +export const findSomeTemplates = + (timeout = TIMEOUT) => + () => { + return Promise.resolve() + .then(promiseTimeout(timeout)) + .then(() => getSomeTemplates()); + }; -export const findNoTemplates = (timeout = TIMEOUT) => () => { - return Promise.resolve() - .then(promiseTimeout(timeout)) - .then(() => getNoTemplates()); -}; +export const findNoTemplates = + (timeout = TIMEOUT) => + () => { + return Promise.resolve() + .then(promiseTimeout(timeout)) + .then(() => getNoTemplates()); + }; export const getNoTemplates = () => ({ templates: [] }); export const getSomeTemplates = () => ({ templates }); diff --git a/x-pack/plugins/canvas/public/state/middleware/element_stats.ts b/x-pack/plugins/canvas/public/state/middleware/element_stats.ts index b18d13fb6a4c..5c1398d73109 100644 --- a/x-pack/plugins/canvas/public/state/middleware/element_stats.ts +++ b/x-pack/plugins/canvas/public/state/middleware/element_stats.ts @@ -12,30 +12,31 @@ import { State } from '../../../types'; import { setElementStats } from '../actions/transient'; import { getAllElements, getElementCounts, getElementStats } from '../selectors/workpad'; -export const elementStats: Middleware<{}, State> = ({ dispatch, getState }) => (next) => ( - action -) => { - // execute the action - next(action); +export const elementStats: Middleware<{}, State> = + ({ dispatch, getState }) => + (next) => + (action) => { + // execute the action + next(action); - // read the new state - const state = getState(); + // read the new state + const state = getState(); - const stats = getElementStats(state); - const total = getAllElements(state).length; - const counts = getElementCounts(state); - const { ready, error } = counts; + const stats = getElementStats(state); + const total = getAllElements(state).length; + const counts = getElementCounts(state); + const { ready, error } = counts; - // TODO: this should come from getElementStats, once we've gotten element status fixed - const pending = total - ready - error; + // TODO: this should come from getElementStats, once we've gotten element status fixed + const pending = total - ready - error; - if ( - (total > 0 || stats.total > 0) && - (ready !== stats.ready || - pending !== stats.pending || - error !== stats.error || - total !== stats.total) - ) { - dispatch(setElementStats({ total, ready, pending, error })); - } -}; + if ( + (total > 0 || stats.total > 0) && + (ready !== stats.ready || + pending !== stats.pending || + error !== stats.error || + total !== stats.total) + ) { + dispatch(setElementStats({ total, ready, pending, error })); + } + }; diff --git a/x-pack/plugins/canvas/public/state/middleware/in_flight.ts b/x-pack/plugins/canvas/public/state/middleware/in_flight.ts index fcfde412192b..06a71ea062e1 100644 --- a/x-pack/plugins/canvas/public/state/middleware/in_flight.ts +++ b/x-pack/plugins/canvas/public/state/middleware/in_flight.ts @@ -33,31 +33,32 @@ export const inFlightMiddlewareFactory = ({ loadingIndicator, pendingCache, }: InFlightMiddlewareOptions): Middleware => { - return ({ dispatch }) => (next: Dispatch) => { - return (action: AnyAction) => { - if (action.type === setLoadingActionType) { - const cacheKey = pathToKey(action.payload.path); - pendingCache.push(cacheKey); - dispatch(inFlightActive()); - } else if (action.type === setValueActionType) { - const cacheKey = pathToKey(action.payload.path); - const idx = pendingCache.indexOf(cacheKey); - if (idx >= 0) { - pendingCache.splice(idx, 1); + return ({ dispatch }) => + (next: Dispatch) => { + return (action: AnyAction) => { + if (action.type === setLoadingActionType) { + const cacheKey = pathToKey(action.payload.path); + pendingCache.push(cacheKey); + dispatch(inFlightActive()); + } else if (action.type === setValueActionType) { + const cacheKey = pathToKey(action.payload.path); + const idx = pendingCache.indexOf(cacheKey); + if (idx >= 0) { + pendingCache.splice(idx, 1); + } + if (pendingCache.length === 0) { + dispatch(inFlightComplete()); + } + } else if (action.type === inFlightActiveActionType) { + loadingIndicator.show(); + } else if (action.type === inFlightCompleteActionType) { + loadingIndicator.hide(); } - if (pendingCache.length === 0) { - dispatch(inFlightComplete()); - } - } else if (action.type === inFlightActiveActionType) { - loadingIndicator.show(); - } else if (action.type === inFlightCompleteActionType) { - loadingIndicator.hide(); - } - // execute the action - next(action); + // execute the action + next(action); + }; }; - }; }; export const inFlight = inFlightMiddlewareFactory({ 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 156d02b4564b..840dcdae9360 100644 --- a/x-pack/plugins/canvas/public/state/middleware/resolved_args.js +++ b/x-pack/plugins/canvas/public/state/middleware/resolved_args.js @@ -12,21 +12,24 @@ 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) => { - // Get the Element IDs that are present before the action. - const startElementIds = getAllElements(getState()).map((element) => element.id); +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); - // execute the action - next(action); + // execute the action + next(action); - // Get the Element IDs after the action... - 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)); + // Get the Element IDs after the action... + 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)); - // If we have some dead elements, we need to clear them from resolved_args collection - // in transient state. - if (deadIds.length > 0) { - dispatch(clearValues(deadIds)); - } -}; + // If we have some dead elements, we need to clear them from resolved_args collection + // in transient state. + if (deadIds.length > 0) { + dispatch(clearValues(deadIds)); + } + }; 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 f2eb47486ff1..8632d593258e 100644 --- a/x-pack/plugins/canvas/public/state/middleware/workpad_update.js +++ b/x-pack/plugins/canvas/public/state/middleware/workpad_update.js @@ -12,29 +12,32 @@ 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) => { - const oldIsWriteable = isWriteable(getState()); - const oldName = getWorkpadName(getState()); +export const workpadUpdate = + ({ dispatch, getState }) => + (next) => + (action) => { + const oldIsWriteable = isWriteable(getState()); + const oldName = getWorkpadName(getState()); - next(action); + next(action); - // This middleware updates the page title when the workpad name changes - if (getWorkpadName(getState()) !== oldName) { - setDocTitle(getWorkpadName(getState())); - } + // This middleware updates the page title when the workpad name changes + if (getWorkpadName(getState()) !== oldName) { + setDocTitle(getWorkpadName(getState())); + } - // This middleware fetches all of the renderable elements on new, duplicate page - if (action.type === duplicatePage.toString()) { - dispatch(fetchAllRenderables()); - } + // This middleware fetches all of the renderable elements on new, duplicate page + if (action.type === duplicatePage.toString()) { + dispatch(fetchAllRenderables()); + } - // This middleware clears any page selection when the writeable mode changes - if (action.type === setWriteable.toString() && oldIsWriteable !== isWriteable(getState())) { - const win = getWindow(); + // This middleware clears any page selection when the writeable mode changes + if (action.type === setWriteable.toString() && oldIsWriteable !== isWriteable(getState())) { + const win = getWindow(); - // check for browser feature before using it - if (typeof win.getSelection === 'function') { - win.getSelection().collapse(document.querySelector('body'), 0); + // check for browser feature before using it + if (typeof win.getSelection === 'function') { + win.getSelection().collapse(document.querySelector('body'), 0); + } } - } -}; + }; diff --git a/x-pack/plugins/canvas/public/state/selectors/workpad.ts b/x-pack/plugins/canvas/public/state/selectors/workpad.ts index 9cfccf3fc559..c419862e7637 100644 --- a/x-pack/plugins/canvas/public/state/selectors/workpad.ts +++ b/x-pack/plugins/canvas/public/state/selectors/workpad.ts @@ -355,11 +355,13 @@ export function getElements( return elements.map(elementAppendAst); } -const augment = (type: string) => (n: T): T => ({ - ...n, - position: { ...n.position, type }, - ...(type === 'group' && { expression: 'shape fill="rgba(255,255,255,0)" | render' }), // fixme unify with mw/aeroelastic -}); +const augment = + (type: string) => + (n: T): T => ({ + ...n, + position: { ...n.position, type }, + ...(type === 'group' && { expression: 'shape fill="rgba(255,255,255,0)" | render' }), // fixme unify with mw/aeroelastic + }); const getNodesOfPage = (page: CanvasPage): Array => { const elements: Array = get(page, 'elements').map( diff --git a/x-pack/plugins/canvas/server/collectors/workpad_collector.ts b/x-pack/plugins/canvas/server/collectors/workpad_collector.ts index 427c8c8a6571..d42b8480ed7c 100644 --- a/x-pack/plugins/canvas/server/collectors/workpad_collector.ts +++ b/x-pack/plugins/canvas/server/collectors/workpad_collector.ts @@ -314,14 +314,8 @@ export function summarizeWorkpads(workpadDocs: CanvasWorkpad[]): WorkpadTelemetr variableCounts: [], } ); - const { - pageCounts, - pageMin, - pageMax, - elementCounts, - functionCounts, - variableCounts, - } = combinedWorkpadsInfo; + const { pageCounts, pageMin, pageMax, elementCounts, functionCounts, variableCounts } = + combinedWorkpadsInfo; const pageTotal = arraySum(pageCounts); const elementsTotal = arraySum(elementCounts); diff --git a/x-pack/plugins/canvas/server/lib/essql_strategy.test.ts b/x-pack/plugins/canvas/server/lib/essql_strategy.test.ts index 7ef543e848ad..e343de569b22 100644 --- a/x-pack/plugins/canvas/server/lib/essql_strategy.test.ts +++ b/x-pack/plugins/canvas/server/lib/essql_strategy.test.ts @@ -57,7 +57,7 @@ describe('ESSQL search strategy', () => { beforeEach(() => { mockQuery = jest.fn().mockResolvedValueOnce(getMockEssqlResponse()); mockClearCursor = jest.fn(); - mockDeps = ({ + mockDeps = { esClient: { asCurrentUser: { sql: { @@ -66,7 +66,7 @@ describe('ESSQL search strategy', () => { }, }, }, - } as unknown) as any; + } as unknown as any; }); describe('query functionality', () => { diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/create.test.ts b/x-pack/plugins/canvas/server/routes/custom_elements/create.test.ts index 179520b7f461..fe34eeeb6e63 100644 --- a/x-pack/plugins/canvas/server/routes/custom_elements/create.test.ts +++ b/x-pack/plugins/canvas/server/routes/custom_elements/create.test.ts @@ -12,13 +12,13 @@ import { initializeCreateCustomElementRoute } from './create'; import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from 'src/core/server'; import { getMockedRouterDeps } from '../test_helpers'; -const mockRouteContext = ({ +const mockRouteContext = { core: { savedObjects: { client: savedObjectsClientMock.create(), }, }, -} as unknown) as RequestHandlerContext; +} as unknown as RequestHandlerContext; const mockedUUID = '123abc'; const now = new Date(); diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/delete.test.ts b/x-pack/plugins/canvas/server/routes/custom_elements/delete.test.ts index 123936e58b6d..5d7321d6943d 100644 --- a/x-pack/plugins/canvas/server/routes/custom_elements/delete.test.ts +++ b/x-pack/plugins/canvas/server/routes/custom_elements/delete.test.ts @@ -11,13 +11,13 @@ import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from 'sr import { savedObjectsClientMock, httpServerMock } from 'src/core/server/mocks'; import { getMockedRouterDeps } from '../test_helpers'; -const mockRouteContext = ({ +const mockRouteContext = { core: { savedObjects: { client: savedObjectsClientMock.create(), }, }, -} as unknown) as RequestHandlerContext; +} as unknown as RequestHandlerContext; describe('DELETE custom element', () => { let routeHandler: RequestHandler; diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/find.test.ts b/x-pack/plugins/canvas/server/routes/custom_elements/find.test.ts index 819c69981788..e84eb835ce22 100644 --- a/x-pack/plugins/canvas/server/routes/custom_elements/find.test.ts +++ b/x-pack/plugins/canvas/server/routes/custom_elements/find.test.ts @@ -10,13 +10,13 @@ import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from 'sr import { savedObjectsClientMock, httpServerMock } from 'src/core/server/mocks'; import { getMockedRouterDeps } from '../test_helpers'; -const mockRouteContext = ({ +const mockRouteContext = { core: { savedObjects: { client: savedObjectsClientMock.create(), }, }, -} as unknown) as RequestHandlerContext; +} as unknown as RequestHandlerContext; describe('Find custom element', () => { let routeHandler: RequestHandler; diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/get.test.ts b/x-pack/plugins/canvas/server/routes/custom_elements/get.test.ts index 859145ad3d1d..ee1db89bda22 100644 --- a/x-pack/plugins/canvas/server/routes/custom_elements/get.test.ts +++ b/x-pack/plugins/canvas/server/routes/custom_elements/get.test.ts @@ -11,13 +11,13 @@ import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from 'sr import { savedObjectsClientMock, httpServerMock } from 'src/core/server/mocks'; import { getMockedRouterDeps } from '../test_helpers'; -const mockRouteContext = ({ +const mockRouteContext = { core: { savedObjects: { client: savedObjectsClientMock.create(), }, }, -} as unknown) as RequestHandlerContext; +} as unknown as RequestHandlerContext; describe('GET custom element', () => { let routeHandler: RequestHandler; diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/update.test.ts b/x-pack/plugins/canvas/server/routes/custom_elements/update.test.ts index a6a75928e45d..d19fb5516bd4 100644 --- a/x-pack/plugins/canvas/server/routes/custom_elements/update.test.ts +++ b/x-pack/plugins/canvas/server/routes/custom_elements/update.test.ts @@ -14,13 +14,13 @@ import { savedObjectsClientMock, httpServerMock } from 'src/core/server/mocks'; import { okResponse } from '../ok_response'; import { getMockedRouterDeps } from '../test_helpers'; -const mockRouteContext = ({ +const mockRouteContext = { core: { savedObjects: { client: savedObjectsClientMock.create(), }, }, -} as unknown) as RequestHandlerContext; +} as unknown as RequestHandlerContext; const now = new Date(); const nowIso = now.toISOString(); diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/update.ts b/x-pack/plugins/canvas/server/routes/custom_elements/update.ts index ea25b917691f..e38e9467e285 100644 --- a/x-pack/plugins/canvas/server/routes/custom_elements/update.ts +++ b/x-pack/plugins/canvas/server/routes/custom_elements/update.ts @@ -38,10 +38,11 @@ export function initializeUpdateCustomElementRoute(deps: RouteInitializerDeps) { const now = new Date().toISOString(); - const customElementObject = await context.core.savedObjects.client.get( - CUSTOM_ELEMENT_TYPE, - id - ); + const customElementObject = + await context.core.savedObjects.client.get( + CUSTOM_ELEMENT_TYPE, + id + ); await context.core.savedObjects.client.create( CUSTOM_ELEMENT_TYPE, diff --git a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts index 02d7e9ca2e26..977aaacdc266 100644 --- a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts +++ b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts @@ -10,13 +10,13 @@ import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from 'sr import { httpServerMock, elasticsearchServiceMock } from 'src/core/server/mocks'; import { getMockedRouterDeps } from '../test_helpers'; -const mockRouteContext = ({ +const mockRouteContext = { core: { elasticsearch: { client: elasticsearchServiceMock.createScopedClusterClient(), }, }, -} as unknown) as RequestHandlerContext; +} as unknown as RequestHandlerContext; const path = `api/canvas/workpad/find`; diff --git a/x-pack/plugins/canvas/server/routes/templates/list.test.ts b/x-pack/plugins/canvas/server/routes/templates/list.test.ts index 85fdb09aa81f..d055692e1719 100644 --- a/x-pack/plugins/canvas/server/routes/templates/list.test.ts +++ b/x-pack/plugins/canvas/server/routes/templates/list.test.ts @@ -11,13 +11,13 @@ import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from 'sr import { savedObjectsClientMock, httpServerMock } from 'src/core/server/mocks'; import { getMockedRouterDeps } from '../test_helpers'; -const mockRouteContext = ({ +const mockRouteContext = { core: { savedObjects: { client: savedObjectsClientMock.create(), }, }, -} as unknown) as RequestHandlerContext; +} as unknown as RequestHandlerContext; describe('Find workpad', () => { let routeHandler: RequestHandler; diff --git a/x-pack/plugins/canvas/server/routes/workpad/create.test.ts b/x-pack/plugins/canvas/server/routes/workpad/create.test.ts index 158c68f0ea0a..87ead1bf897f 100644 --- a/x-pack/plugins/canvas/server/routes/workpad/create.test.ts +++ b/x-pack/plugins/canvas/server/routes/workpad/create.test.ts @@ -11,14 +11,14 @@ import { initializeCreateWorkpadRoute } from './create'; import { kibanaResponseFactory, RequestHandler } from 'src/core/server'; import { getMockedRouterDeps } from '../test_helpers'; -let mockRouteContext = ({ +let mockRouteContext = { core: { savedObjects: { client: savedObjectsClientMock.create(), }, }, canvas: workpadRouteContextMock.create(), -} as unknown) as MockWorkpadRouteContext; +} as unknown as MockWorkpadRouteContext; jest.mock('uuid/v4', () => jest.fn().mockReturnValue('123abc')); @@ -26,14 +26,14 @@ describe('POST workpad', () => { let routeHandler: RequestHandler; beforeEach(() => { - mockRouteContext = ({ + mockRouteContext = { core: { savedObjects: { client: savedObjectsClientMock.create(), }, }, canvas: workpadRouteContextMock.create(), - } as unknown) as MockWorkpadRouteContext; + } as unknown as MockWorkpadRouteContext; const routerDeps = getMockedRouterDeps(); initializeCreateWorkpadRoute(routerDeps); diff --git a/x-pack/plugins/canvas/server/routes/workpad/delete.test.ts b/x-pack/plugins/canvas/server/routes/workpad/delete.test.ts index f07a83e65a97..b3f1ebd4db52 100644 --- a/x-pack/plugins/canvas/server/routes/workpad/delete.test.ts +++ b/x-pack/plugins/canvas/server/routes/workpad/delete.test.ts @@ -11,13 +11,13 @@ import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from 'sr import { savedObjectsClientMock, httpServerMock } from 'src/core/server/mocks'; import { getMockedRouterDeps } from '../test_helpers'; -const mockRouteContext = ({ +const mockRouteContext = { core: { savedObjects: { client: savedObjectsClientMock.create(), }, }, -} as unknown) as RequestHandlerContext; +} as unknown as RequestHandlerContext; describe('DELETE workpad', () => { let routeHandler: RequestHandler; diff --git a/x-pack/plugins/canvas/server/routes/workpad/find.test.ts b/x-pack/plugins/canvas/server/routes/workpad/find.test.ts index 8bb7d348a291..6379b6f8258b 100644 --- a/x-pack/plugins/canvas/server/routes/workpad/find.test.ts +++ b/x-pack/plugins/canvas/server/routes/workpad/find.test.ts @@ -10,13 +10,13 @@ import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from 'sr import { savedObjectsClientMock, httpServerMock } from 'src/core/server/mocks'; import { getMockedRouterDeps } from '../test_helpers'; -const mockRouteContext = ({ +const mockRouteContext = { core: { savedObjects: { client: savedObjectsClientMock.create(), }, }, -} as unknown) as RequestHandlerContext; +} as unknown as RequestHandlerContext; describe('Find workpad', () => { let routeHandler: RequestHandler; diff --git a/x-pack/plugins/canvas/server/routes/workpad/get.test.ts b/x-pack/plugins/canvas/server/routes/workpad/get.test.ts index e19a20cc3f54..cae485b62f66 100644 --- a/x-pack/plugins/canvas/server/routes/workpad/get.test.ts +++ b/x-pack/plugins/canvas/server/routes/workpad/get.test.ts @@ -14,9 +14,9 @@ import { CanvasWorkpad } from '../../../types'; import { getMockedRouterDeps } from '../test_helpers'; import { workpadRouteContextMock, MockWorkpadRouteContext } from '../../mocks'; -const mockRouteContext = ({ +const mockRouteContext = { canvas: workpadRouteContextMock.create(), -} as unknown) as MockWorkpadRouteContext; +} as unknown as MockWorkpadRouteContext; describe('GET workpad', () => { let routeHandler: RequestHandler; diff --git a/x-pack/plugins/canvas/server/routes/workpad/update.test.ts b/x-pack/plugins/canvas/server/routes/workpad/update.test.ts index 8feadf433f07..240298564fdb 100644 --- a/x-pack/plugins/canvas/server/routes/workpad/update.test.ts +++ b/x-pack/plugins/canvas/server/routes/workpad/update.test.ts @@ -15,14 +15,14 @@ import { okResponse } from '../ok_response'; import { getMockedRouterDeps } from '../test_helpers'; import { workpadRouteContextMock, MockWorkpadRouteContext } from '../../mocks'; -const mockRouteContext = ({ +const mockRouteContext = { core: { savedObjects: { client: savedObjectsClientMock.create(), }, }, canvas: workpadRouteContextMock.create(), -} as unknown) as MockWorkpadRouteContext; +} as unknown as MockWorkpadRouteContext; const workpad = workpads[0]; const now = new Date(); diff --git a/x-pack/plugins/canvas/server/templates/pitch_presentation.ts b/x-pack/plugins/canvas/server/templates/pitch_presentation.ts index 98b48db9ff0f..a9f09ada989c 100644 --- a/x-pack/plugins/canvas/server/templates/pitch_presentation.ts +++ b/x-pack/plugins/canvas/server/templates/pitch_presentation.ts @@ -1644,8 +1644,7 @@ export const pitch: CanvasTemplate = { 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAFAKADAAQAAAABAAADVQAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgDVQUAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAQEBAQEBAgEBAgMCAgIDBAMDAwMEBQQEBAQEBQYFBQUFBQUGBgYGBgYGBgcHBwcHBwgICAgICQkJCQkJCQkJCf/bAEMBAQEBAgIC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JrN1eh2RwsUuaxVvZFB+TmqKy5bBqNnMhyTjNOVRjIrri9D5+pBym2i6DkBjUn+1VaMZqzuB49eKmTOqnFC5yNvvVyMYOfSq2wqAR2qwjcYNTKV1obwhaXvFgHzOPSnc8ZqEAhjt49am5bFS3Y2pxutdybcAdw4qQTZ4qEg4GO9QrjJNYXvud9+XRI1EYZwauow4x2rCVjnP44q6shZvas5o6aVbo0bUcuOKsCTawNZMblm5+tXAxHHWsG7M9SlO6NiNgfm61qwnHPr2rnY3ORWzAxJBJ965ah7+Clc6G3YZDAVtw9vb8PxrnIHUgetbUEu1K4KrPpMJLRJm/E4AweamBAway7eXkFen6VfLc4Tt/KvOqI+lwtbZl4ScZ7+1TIAcFs5rOWQcE9atowA5Ncsu561KaOitblVGO9dDYXgziuIR1C5P+RW5p82XCjg15mKpJps+ny/FyTSPTdNulbAzjnvXYWzMSHTkEdR615vZSqpAHWurguysQavk8dC+x+jZRirKzeh//9L4GsrtCodcgHnn/Guu068KvuQ5UcnJrytHVgO+PaunsLvYFJGPxr9QrU7pnyFCpDmUorsevW91DcwZXqpHGfWuqtZzsWI4B68f/Xryawu1Egdc+p9a7e1v8IARkHIH1rwsTRd7I+rwcoP3pnpWlXhXIlYehFdJb3Y2788evavO7Wdmt/MXkk/5xitiyumjYLnHfB55/lXhYnB812fVYTMFFxpHottd8hu/TFdVbag6jBx9OvavOba+iyvzew//AF1u292rMUB79K8DE4S/Q+owuL/vHocV0kg3xgZ4696ZI4x8/HH61x63bISwOCen/wBarq3sxUO3XGceorx3hbM+ihiVy+ZqXTmNecZxmuankYsf7x61sfaElByccdT/APrrInTedwOSfSuijFLRmM3rczZpFwZCO9c9eopQTKc44B/xrZuY2QZfnnOO9Y0qtInONo7GvTw76pnj4yCs00cTdSsjEN9e3NYckjTKegx69xXTanDG7h1wD1A+lc3dRpkqvU5ya+koTTjtqfGYmjJT916HNXjMVwuck9+mKwriV0k3SN06YP4V115D5aiZm6DgVymoQlwMDLde3b/PtXqYarr5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raADiqh6Crg6j6U5jgrstDII/CnbiKaOo/Cg9RQ/hE9yVTubHTNOJ5xTI/vinfxVAh3I6804jBpp6inv8AeoGtwUbgT6U7ABBHekj+61Kf4aC09EAJLkCpB1qJf9YalH3vwNBqhVAINOYBQT6Uid/qKc/3GqJ7BF6idQaQevpTl+6f89qavf6VLehqkJnacdanRjn6VXb7341Mn3j9R/OoLTLfTp6U7oMnnpTD/Q09vu/lSZsloPHPHrim9DmnL1H4Uw9R9KwuVHcM5qTccn2qIdPzp/dqC/tFjbk49KYwqVfvfnUb9aCmtRhOBSo2BTW6fnQOgoMmWAd3HrUJPPFSp1H1/pUNBpD4WyFnwcetM3E5QcYofr+NNH3z+FBmtj//2Q==', }, }, - css: - ".canvasPage h1, .canvasPage h2, .canvasPage h3, .canvasPage h4, .canvasPage h5 {\nfont-family: 'Futura';\ncolor: #444444;\n}\n\n.canvasPage h1 {\nfont-size: 112px;\nfont-weight: bold;\ncolor: #FFFFFF;\n}\n\n.canvasPage h2 {\nfont-size: 48px;\nfont-weight: bold;\n}\n\n.canvasPage h3 {\nfont-size: 30px;\nfont-weight: 300;\ntext-transform: uppercase;\ncolor: #FFFFFF;\n}\n\n.canvasPage h5 {\nfont-size: 24px;\nfont-style: italic;\n}", + css: ".canvasPage h1, .canvasPage h2, .canvasPage h3, .canvasPage h4, .canvasPage h5 {\nfont-family: 'Futura';\ncolor: #444444;\n}\n\n.canvasPage h1 {\nfont-size: 112px;\nfont-weight: bold;\ncolor: #FFFFFF;\n}\n\n.canvasPage h2 {\nfont-size: 48px;\nfont-weight: bold;\n}\n\n.canvasPage h3 {\nfont-size: 30px;\nfont-weight: 300;\ntext-transform: uppercase;\ncolor: #FFFFFF;\n}\n\n.canvasPage h5 {\nfont-size: 24px;\nfont-style: italic;\n}", variables: [], }, }; diff --git a/x-pack/plugins/canvas/server/templates/status_report.ts b/x-pack/plugins/canvas/server/templates/status_report.ts index 49af400f4511..94f05c371ff9 100644 --- a/x-pack/plugins/canvas/server/templates/status_report.ts +++ b/x-pack/plugins/canvas/server/templates/status_report.ts @@ -17,8 +17,7 @@ export const status: CanvasTemplate = { name: 'Status', width: 612, height: 792, - css: - '.canvasPage h1, .canvasPage h2, .canvasPage h3, .canvasPage h4, .canvasPage h5, .canvasPage h6, .canvasPage li, .canvasPage p, .canvasPage th, .canvasPage td {\nfont-family: "Gill Sans" !important;\ncolor: #333333;\n}\n\n.canvasPage h1, .canvasPage h2 {\nfont-weight: 400;\n}\n\n.canvasPage h2 {\ntext-transform: uppercase;\ncolor: #1785B0;\n}\n\n.canvasMarkdown p,\n.canvasMarkdown li {\nfont-size: 18px;\n}\n\n.canvasMarkdown li {\nmargin-bottom: .75em;\n}\n\n.canvasMarkdown h3:not(:first-child) {\nmargin-top: 2em;\n}\n\n.canvasMarkdown a {\ncolor: #1785B0;\n}\n\n.canvasMarkdown th,\n.canvasMarkdown td {\npadding: .5em 1em;\n}\n\n.canvasMarkdown th {\nbackground-color: #FAFBFD;\n}\n\n.canvasMarkdown table,\n.canvasMarkdown th,\n.canvasMarkdown td {\nborder: 1px solid #e4e9f2;\n}', + css: '.canvasPage h1, .canvasPage h2, .canvasPage h3, .canvasPage h4, .canvasPage h5, .canvasPage h6, .canvasPage li, .canvasPage p, .canvasPage th, .canvasPage td {\nfont-family: "Gill Sans" !important;\ncolor: #333333;\n}\n\n.canvasPage h1, .canvasPage h2 {\nfont-weight: 400;\n}\n\n.canvasPage h2 {\ntext-transform: uppercase;\ncolor: #1785B0;\n}\n\n.canvasMarkdown p,\n.canvasMarkdown li {\nfont-size: 18px;\n}\n\n.canvasMarkdown li {\nmargin-bottom: .75em;\n}\n\n.canvasMarkdown h3:not(:first-child) {\nmargin-top: 2em;\n}\n\n.canvasMarkdown a {\ncolor: #1785B0;\n}\n\n.canvasMarkdown th,\n.canvasMarkdown td {\npadding: .5em 1em;\n}\n\n.canvasMarkdown th {\nbackground-color: #FAFBFD;\n}\n\n.canvasMarkdown table,\n.canvasMarkdown th,\n.canvasMarkdown td {\nborder: 1px solid #e4e9f2;\n}', variables: [], page: 0, pages: [ diff --git a/x-pack/plugins/canvas/server/workpad_route_context.test.ts b/x-pack/plugins/canvas/server/workpad_route_context.test.ts index ec09a364b594..d13b8aa9eb63 100644 --- a/x-pack/plugins/canvas/server/workpad_route_context.test.ts +++ b/x-pack/plugins/canvas/server/workpad_route_context.test.ts @@ -20,13 +20,13 @@ const mockedExpressionService = { const savedObjectsClient = savedObjectsClientMock.create(); -const mockContext = ({ +const mockContext = { core: { savedObjects: { client: savedObjectsClient, }, }, -} as unknown) as RequestHandlerContext; +} as unknown as RequestHandlerContext; const workpadRouteContext = createWorkpadRouteContext({ expressions: mockedExpressionService as any, diff --git a/x-pack/plugins/canvas/shareable_runtime/components/footer/__stories__/scrubber.stories.tsx b/x-pack/plugins/canvas/shareable_runtime/components/footer/__stories__/scrubber.stories.tsx index d92b550779d0..fc30e301ae8a 100644 --- a/x-pack/plugins/canvas/shareable_runtime/components/footer/__stories__/scrubber.stories.tsx +++ b/x-pack/plugins/canvas/shareable_runtime/components/footer/__stories__/scrubber.stories.tsx @@ -28,7 +28,7 @@ storiesOf('shareables/Footer/Scrubber', module) )); diff --git a/x-pack/plugins/canvas/storybook/addon/src/state.ts b/x-pack/plugins/canvas/storybook/addon/src/state.ts index 1aafd67595f9..b0032fbfc461 100644 --- a/x-pack/plugins/canvas/storybook/addon/src/state.ts +++ b/x-pack/plugins/canvas/storybook/addon/src/state.ts @@ -32,22 +32,21 @@ export const getInitialState: () => State = () => getState(); export const getMiddleware = () => applyMiddleware(thunkMiddleware); export const getReducer = () => getRootReducer(getInitialState()); -export const patchDispatch: (store: Store, dispatch: Dispatch) => Dispatch = (store, dispatch) => ( - action -) => { - const channel = addons.getChannel(); - - const previousState = store.getState(); - const returnValue = dispatch(action); - const newState = store.getState(); - const change = diff(previousState, newState) || {}; - - channel.emit(EVENTS.ACTION, { - previousState, - newState, - change, - action: isFunction(action) ? { type: '(thunk)' } : action, - }); - - return returnValue; -}; +export const patchDispatch: (store: Store, dispatch: Dispatch) => Dispatch = + (store, dispatch) => (action) => { + const channel = addons.getChannel(); + + const previousState = store.getState(); + const returnValue = dispatch(action); + const newState = store.getState(); + const change = diff(previousState, newState) || {}; + + channel.emit(EVENTS.ACTION, { + previousState, + newState, + change, + action: isFunction(action) ? { type: '(thunk)' } : action, + }); + + return returnValue; + }; diff --git a/x-pack/plugins/canvas/tasks/mocks/customElementService.js b/x-pack/plugins/canvas/tasks/mocks/customElementService.js index 596d57af97d1..a0c8d3c6f262 100644 --- a/x-pack/plugins/canvas/tasks/mocks/customElementService.js +++ b/x-pack/plugins/canvas/tasks/mocks/customElementService.js @@ -27,8 +27,7 @@ export const getTestCustomElements = () => { id: 'custom-element-', name: 'customElement3', displayName: 'Custom Element 3', - help: - 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce lobortis aliquet arcu ut turpis duis.', + help: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce lobortis aliquet arcu ut turpis duis.', image: '', content: `{\"selectedNodes\":[{\"id\":\"group-dccf4ed7-1593-49a0-9902-caf4d4a4b7f5\",\"position\":{\"left\":250,\"top\":119,\"width\":340,\"height\":517,\"angle\":0,\"parent\":null,\"type\":\"group\"},\"expression\":\"shape fill=\\\"rgba(255,255,255,0)\\\" | render\",\"ast\":{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"shape\",\"arguments\":{\"fill\":[\"rgba(255,255,255,0)\"]}},{\"type\":\"function\",\"function\":\"render\",\"arguments\":{}}]}},{\"id\":\"element-e2c658ee-7614-4d92-a46e-2b1a81a24485\",\"position\":{\"left\":250,\"top\":405,\"width\":340,\"height\":75,\"angle\":0,\"parent\":\"group-dccf4ed7-1593-49a0-9902-caf4d4a4b7f5\",\"type\":\"element\"},\"expression\":\"filters\\n| demodata\\n| markdown \\\"## Jane Doe\\\" \\n font={font family=\\\"'Open Sans', Helvetica, Arial, sans-serif\\\" size=14 align=\\\"center\\\" color=\\\"#000000\\\" weight=\\\"normal\\\" underline=false italic=false}\\n| render\",\"ast\":{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"filters\",\"arguments\":{}},{\"type\":\"function\",\"function\":\"demodata\",\"arguments\":{}},{\"type\":\"function\",\"function\":\"markdown\",\"arguments\":{\"_\":[\"## Jane Doe\"],\"font\":[{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"font\",\"arguments\":{\"family\":[\"'Open Sans', Helvetica, Arial, sans-serif\"],\"size\":[14],\"align\":[\"center\"],\"color\":[\"#000000\"],\"weight\":[\"normal\"],\"underline\":[false],\"italic\":[false]}}]}]}},{\"type\":\"function\",\"function\":\"render\",\"arguments\":{}}]}},{\"id\":\"element-3d16765e-5251-4954-8e2a-6c64ed465b73\",\"position\":{\"left\":250,\"top\":480,\"width\":340,\"height\":75,\"angle\":0,\"parent\":\"group-dccf4ed7-1593-49a0-9902-caf4d4a4b7f5\",\"type\":\"element\"},\"expression\":\"filters\\n| demodata\\n| markdown \\\"### Developer\\\" \\n font={font family=\\\"'Open Sans', Helvetica, Arial, sans-serif\\\" size=14 align=\\\"center\\\" color=\\\"#000000\\\" weight=\\\"normal\\\" underline=false italic=false}\\n| render css=\\\".canvasRenderEl h3 {\\ncolor: #444444;\\n}\\\"\",\"ast\":{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"filters\",\"arguments\":{}},{\"type\":\"function\",\"function\":\"demodata\",\"arguments\":{}},{\"type\":\"function\",\"function\":\"markdown\",\"arguments\":{\"_\":[\"### Developer\"],\"font\":[{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"font\",\"arguments\":{\"family\":[\"'Open Sans', Helvetica, Arial, sans-serif\"],\"size\":[14],\"align\":[\"center\"],\"color\":[\"#000000\"],\"weight\":[\"normal\"],\"underline\":[false],\"italic\":[false]}}]}]}},{\"type\":\"function\",\"function\":\"render\",\"arguments\":{\"css\":[\".canvasRenderEl h3 {\\ncolor: #444444;\\n}\"]}}]}},{\"id\":\"element-624675cf-46e9-4545-b86a-5409bbe53ac1\",\"position\":{\"left\":250,\"top\":555,\"width\":340,\"height\":81,\"angle\":0,\"parent\":\"group-dccf4ed7-1593-49a0-9902-caf4d4a4b7f5\",\"type\":\"element\"},\"expression\":\"filters\\n| demodata\\n| markdown \\n \\\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel sollicitudin mauris, ut scelerisque urna. \\\" \\n font={font family=\\\"'Open Sans', Helvetica, Arial, sans-serif\\\" size=14 align=\\\"center\\\" color=\\\"#000000\\\" weight=\\\"normal\\\" underline=false italic=false}\\n| render\",\"ast\":{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"filters\",\"arguments\":{}},{\"type\":\"function\",\"function\":\"demodata\",\"arguments\":{}},{\"type\":\"function\",\"function\":\"markdown\",\"arguments\":{\"_\":[\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel sollicitudin mauris, ut scelerisque urna. \"],\"font\":[{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"font\",\"arguments\":{\"family\":[\"'Open Sans', Helvetica, Arial, sans-serif\"],\"size\":[14],\"align\":[\"center\"],\"color\":[\"#000000\"],\"weight\":[\"normal\"],\"underline\":[false],\"italic\":[false]}}]}]}},{\"type\":\"function\",\"function\":\"render\",\"arguments\":{}}]}},{\"id\":\"element-c2916246-26dd-4c65-91c6-d1ad3f1791ee\",\"position\":{\"left\":293,\"top\":119,\"width\":254,\"height\":252,\"angle\":0,\"parent\":\"group-dccf4ed7-1593-49a0-9902-caf4d4a4b7f5\",\"type\":\"element\"},\"expression\":\"image dataurl={asset \\\"asset-0c6f377f-771e-432e-8e2e-15c3e9142ad6\\\"} mode=\\\"contain\\\"\\n| render\",\"ast\":{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"image\",\"arguments\":{\"dataurl\":[{\"type\":\"expression\",\"chain\":[{\"type\":\"function\",\"function\":\"asset\",\"arguments\":{\"_\":[\"asset-0c6f377f-771e-432e-8e2e-15c3e9142ad6\"]}}]}],\"mode\":[\"contain\"]}},{\"type\":\"function\",\"function\":\"render\",\"arguments\":{}}]}}]}`, }, diff --git a/x-pack/plugins/cases/common/api/runtime_types.ts b/x-pack/plugins/cases/common/api/runtime_types.ts index 8817764e261d..7edc1162c0e8 100644 --- a/x-pack/plugins/cases/common/api/runtime_types.ts +++ b/x-pack/plugins/cases/common/api/runtime_types.ts @@ -52,11 +52,10 @@ export const throwErrors = (createError: ErrorFactory) => (errors: rt.Errors) => throw createError(formatErrors(errors).join()); }; -export const decodeOrThrow = ( - runtimeType: rt.Type, - createError: ErrorFactory = createPlainError -) => (inputValue: I) => - pipe(runtimeType.decode(inputValue), fold(throwErrors(createError), identity)); +export const decodeOrThrow = + (runtimeType: rt.Type, createError: ErrorFactory = createPlainError) => + (inputValue: I) => + pipe(runtimeType.decode(inputValue), fold(throwErrors(createError), identity)); const getExcessProps = (props: rt.Props, r: Record): string[] => { const ex: string[] = []; diff --git a/x-pack/plugins/cases/public/common/lib/kibana/kibana_react.mock.ts b/x-pack/plugins/cases/public/common/lib/kibana/kibana_react.mock.ts index 066121d2c5bf..18370be61bdf 100644 --- a/x-pack/plugins/cases/public/common/lib/kibana/kibana_react.mock.ts +++ b/x-pack/plugins/cases/public/common/lib/kibana/kibana_react.mock.ts @@ -16,7 +16,7 @@ import { securityMock } from '../../../../../security/public/mocks'; import { triggersActionsUiMock } from '../../../../../triggers_actions_ui/public/mocks'; export const createStartServicesMock = (): StartServices => - (({ + ({ ...coreMock.createStart(), storage: { ...coreMock.createStorage(), remove: jest.fn() }, lens: { @@ -25,7 +25,7 @@ export const createStartServicesMock = (): StartServices => }, security: securityMock.createStart(), triggersActionsUi: triggersActionsUiMock.createStart(), - } as unknown) as StartServices); + } as unknown as StartServices); export const createWithKibanaMock = () => { const services = createStartServicesMock(); diff --git a/x-pack/plugins/cases/public/common/mock/test_providers.tsx b/x-pack/plugins/cases/public/common/mock/test_providers.tsx index 98304808224c..b31e9e4e1b19 100644 --- a/x-pack/plugins/cases/public/common/mock/test_providers.tsx +++ b/x-pack/plugins/cases/public/common/mock/test_providers.tsx @@ -43,7 +43,7 @@ export const TestProviders = React.memo(TestProvidersComponent); export const useFormFieldMock = (options?: Partial>): FieldHook => ({ path: 'path', type: 'type', - value: ('mockedValue' as unknown) as T, + value: 'mockedValue' as unknown as T, isPristine: false, isDirty: false, isModified: false, diff --git a/x-pack/plugins/cases/public/components/case_action_bar/actions.tsx b/x-pack/plugins/cases/public/components/case_action_bar/actions.tsx index 6816575d649f..f6d52583d436 100644 --- a/x-pack/plugins/cases/public/components/case_action_bar/actions.tsx +++ b/x-pack/plugins/cases/public/components/case_action_bar/actions.tsx @@ -27,12 +27,8 @@ const ActionsComponent: React.FC = ({ currentExternalIncident, }) => { // Delete case - const { - handleToggleModal, - handleOnDeleteConfirm, - isDeleted, - isDisplayConfirmDeleteModal, - } = useDeleteCases(); + const { handleToggleModal, handleOnDeleteConfirm, isDeleted, isDisplayConfirmDeleteModal } = + useDeleteCases(); const propertyActions = useMemo( () => [ diff --git a/x-pack/plugins/cases/public/components/case_view/index.tsx b/x-pack/plugins/cases/public/components/case_view/index.tsx index a12a3a5bb869..bb0b894238b9 100644 --- a/x-pack/plugins/cases/public/components/case_view/index.tsx +++ b/x-pack/plugins/cases/public/components/case_view/index.tsx @@ -270,7 +270,11 @@ export const CaseComponent = React.memo( [updateCase, fetchCaseUserActions, caseId, subCaseId] ); - const { loading: isLoadingConnectors, connectors, permissionsError } = useConnectors({ + const { + loading: isLoadingConnectors, + connectors, + permissionsError, + } = useConnectors({ toastPermissionsErrors: false, }); @@ -304,9 +308,10 @@ export const CaseComponent = React.memo( [onUpdateField, connectors] ); - const onSubmitTags = useCallback((newTags) => onUpdateField({ key: 'tags', value: newTags }), [ - onUpdateField, - ]); + const onSubmitTags = useCallback( + (newTags) => onUpdateField({ key: 'tags', value: newTags }), + [onUpdateField] + ); const onSubmitTitle = useCallback( (newTitle) => onUpdateField({ key: 'title', value: newTitle }), diff --git a/x-pack/plugins/cases/public/components/configure_cases/field_mapping_row_static.tsx b/x-pack/plugins/cases/public/components/configure_cases/field_mapping_row_static.tsx index 2509c56dda71..09e3546b2e2e 100644 --- a/x-pack/plugins/cases/public/components/configure_cases/field_mapping_row_static.tsx +++ b/x-pack/plugins/cases/public/components/configure_cases/field_mapping_row_static.tsx @@ -24,9 +24,10 @@ const FieldMappingRowComponent: React.FC = ({ selectedActionType, selectedThirdParty, }) => { - const selectedActionTypeCapitalized = useMemo(() => capitalize(selectedActionType), [ - selectedActionType, - ]); + const selectedActionTypeCapitalized = useMemo( + () => capitalize(selectedActionType), + [selectedActionType] + ); return ( diff --git a/x-pack/plugins/cases/public/components/configure_cases/index.tsx b/x-pack/plugins/cases/public/components/configure_cases/index.tsx index c792990a2882..788c6eeb61b3 100644 --- a/x-pack/plugins/cases/public/components/configure_cases/index.tsx +++ b/x-pack/plugins/cases/public/components/configure_cases/index.tsx @@ -95,9 +95,10 @@ const ConfigureCasesComponent: React.FC> = ({ setEditFlyoutVisibility(true); }, []); - const onCloseAddFlyout = useCallback(() => setAddFlyoutVisibility(false), [ - setAddFlyoutVisibility, - ]); + const onCloseAddFlyout = useCallback( + () => setAddFlyoutVisibility(false), + [setAddFlyoutVisibility] + ); const onCloseEditFlyout = useCallback(() => setEditFlyoutVisibility(false), []); diff --git a/x-pack/plugins/cases/public/components/connector_selector/form.test.tsx b/x-pack/plugins/cases/public/components/connector_selector/form.test.tsx index ea25fce2d4f7..b914b4c7edab 100644 --- a/x-pack/plugins/cases/public/components/connector_selector/form.test.tsx +++ b/x-pack/plugins/cases/public/components/connector_selector/form.test.tsx @@ -32,7 +32,7 @@ describe('ConnectorSelector', () => { it('it should render', async () => { const wrapper = mount( -
+ { it('it should not render when is not in edit mode', async () => { const wrapper = mount( - + = ({ onCaseChanged, selectedCase }) => { - const { data: cases, loading: isLoadingCases, refetchCases } = useGetCases({ + const { + data: cases, + loading: isLoadingCases, + refetchCases, + } = useGetCases({ initialQueryParams: DEFAULT_QUERY_PARAMS, initialFilterOptions: { ...DEFAULT_FILTER_OPTIONS, diff --git a/x-pack/plugins/cases/public/components/connectors/jira/case_fields.test.tsx b/x-pack/plugins/cases/public/components/connectors/jira/case_fields.test.tsx index ae9245534c78..591dbf15d35a 100644 --- a/x-pack/plugins/cases/public/components/connectors/jira/case_fields.test.tsx +++ b/x-pack/plugins/cases/public/components/connectors/jira/case_fields.test.tsx @@ -139,9 +139,11 @@ describe('Jira Fields', () => { const wrapper = mount(); await waitFor(() => - ((wrapper.find(EuiComboBox).props() as unknown) as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - }).onChange([{ label: 'parentId', value: 'parentId' }]) + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ label: 'parentId', value: 'parentId' }]) ); wrapper.update(); expect(onChange).toHaveBeenCalledWith({ @@ -164,9 +166,11 @@ describe('Jira Fields', () => { const wrapper = mount(); await waitFor(() => - ((wrapper.find(EuiComboBox).props() as unknown) as { - onSearchChange: (a: string) => void; - }).onSearchChange('womanId') + ( + wrapper.find(EuiComboBox).props() as unknown as { + onSearchChange: (a: string) => void; + } + ).onSearchChange('womanId') ); wrapper.update(); expect(useGetIssuesMock.mock.calls[2][0].query).toEqual('womanId'); diff --git a/x-pack/plugins/cases/public/components/connectors/jira/search_issues.tsx b/x-pack/plugins/cases/public/components/connectors/jira/search_issues.tsx index 79ac42e034c6..61866d126dfd 100644 --- a/x-pack/plugins/cases/public/components/connectors/jira/search_issues.tsx +++ b/x-pack/plugins/cases/public/components/connectors/jira/search_issues.tsx @@ -42,9 +42,10 @@ const SearchIssuesComponent: React.FC = ({ selectedValue, actionConnector id: selectedValue, }); - useEffect(() => setOptions(issues.map((issue) => ({ label: issue.title, value: issue.key }))), [ - issues, - ]); + useEffect( + () => setOptions(issues.map((issue) => ({ label: issue.title, value: issue.key }))), + [issues] + ); useEffect(() => { if (isLoadingSingleIssue || singleIssue == null) { diff --git a/x-pack/plugins/cases/public/components/connectors/resilient/case_fields.test.tsx b/x-pack/plugins/cases/public/components/connectors/resilient/case_fields.test.tsx index dda6ba5de95c..814c73537b1f 100644 --- a/x-pack/plugins/cases/public/components/connectors/resilient/case_fields.test.tsx +++ b/x-pack/plugins/cases/public/components/connectors/resilient/case_fields.test.tsx @@ -111,9 +111,11 @@ describe('ResilientParamsFields renders', () => { const wrapper = mount(); await waitFor(() => { - ((wrapper.find(EuiComboBox).props() as unknown) as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - }).onChange([{ value: '19', label: 'Denial of Service' }]); + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ value: '19', label: 'Denial of Service' }]); }); expect(onChange).toHaveBeenCalledWith({ incidentTypes: ['19'], severityCode: '6' }); diff --git a/x-pack/plugins/cases/public/components/connectors/resilient/case_fields.tsx b/x-pack/plugins/cases/public/components/connectors/resilient/case_fields.tsx index e1eeb13bf684..44f06f92093d 100644 --- a/x-pack/plugins/cases/public/components/connectors/resilient/case_fields.tsx +++ b/x-pack/plugins/cases/public/components/connectors/resilient/case_fields.tsx @@ -24,166 +24,163 @@ import * as i18n from './translations'; import { ConnectorTypes, ResilientFieldsType } from '../../../../common'; import { ConnectorCard } from '../card'; -const ResilientFieldsComponent: React.FunctionComponent< - ConnectorFieldsProps -> = ({ isEdit = true, fields, connector, onChange }) => { - const init = useRef(true); - const { incidentTypes = null, severityCode = null } = fields ?? {}; - - const { http, notifications } = useKibana().services; - - const { - isLoading: isLoadingIncidentTypes, - incidentTypes: allIncidentTypes, - } = useGetIncidentTypes({ - http, - toastNotifications: notifications.toasts, - connector, - }); - - const { isLoading: isLoadingSeverity, severity } = useGetSeverity({ - http, - toastNotifications: notifications.toasts, - connector, - }); - - const severitySelectOptions: EuiSelectOption[] = useMemo( - () => - severity.map((s) => ({ - value: s.id.toString(), - text: s.name, - })), - [severity] - ); - - const incidentTypesComboBoxOptions: Array> = useMemo( - () => - allIncidentTypes - ? allIncidentTypes.map((type: { id: number; name: string }) => ({ - label: type.name, - value: type.id.toString(), - })) - : [], - [allIncidentTypes] - ); - const listItems = useMemo( - () => [ - ...(incidentTypes != null && incidentTypes.length > 0 - ? [ - { - title: i18n.INCIDENT_TYPES_LABEL, - description: allIncidentTypes - .filter((type) => incidentTypes.includes(type.id.toString())) - .map((type) => type.name) - .join(', '), - }, - ] - : []), - ...(severityCode != null && severityCode.length > 0 - ? [ - { - title: i18n.SEVERITY_LABEL, - description: - severity.find((severityObj) => severityObj.id.toString() === severityCode)?.name ?? - '', - }, - ] - : []), - ], - [incidentTypes, severityCode, allIncidentTypes, severity] - ); - - const onFieldChange = useCallback( - (key, value) => { - onChange({ - ...fields, - incidentTypes, - severityCode, - [key]: value, +const ResilientFieldsComponent: React.FunctionComponent> = + ({ isEdit = true, fields, connector, onChange }) => { + const init = useRef(true); + const { incidentTypes = null, severityCode = null } = fields ?? {}; + + const { http, notifications } = useKibana().services; + + const { isLoading: isLoadingIncidentTypes, incidentTypes: allIncidentTypes } = + useGetIncidentTypes({ + http, + toastNotifications: notifications.toasts, + connector, }); - }, - [incidentTypes, severityCode, onChange, fields] - ); - - const selectedIncidentTypesComboBoxOptionsMemo = useMemo(() => { - const allIncidentTypesAsObject = allIncidentTypes.reduce( - (acc, type) => ({ ...acc, [type.id.toString()]: type.name }), - {} as Record + + const { isLoading: isLoadingSeverity, severity } = useGetSeverity({ + http, + toastNotifications: notifications.toasts, + connector, + }); + + const severitySelectOptions: EuiSelectOption[] = useMemo( + () => + severity.map((s) => ({ + value: s.id.toString(), + text: s.name, + })), + [severity] + ); + + const incidentTypesComboBoxOptions: Array> = useMemo( + () => + allIncidentTypes + ? allIncidentTypes.map((type: { id: number; name: string }) => ({ + label: type.name, + value: type.id.toString(), + })) + : [], + [allIncidentTypes] + ); + const listItems = useMemo( + () => [ + ...(incidentTypes != null && incidentTypes.length > 0 + ? [ + { + title: i18n.INCIDENT_TYPES_LABEL, + description: allIncidentTypes + .filter((type) => incidentTypes.includes(type.id.toString())) + .map((type) => type.name) + .join(', '), + }, + ] + : []), + ...(severityCode != null && severityCode.length > 0 + ? [ + { + title: i18n.SEVERITY_LABEL, + description: + severity.find((severityObj) => severityObj.id.toString() === severityCode) + ?.name ?? '', + }, + ] + : []), + ], + [incidentTypes, severityCode, allIncidentTypes, severity] + ); + + const onFieldChange = useCallback( + (key, value) => { + onChange({ + ...fields, + incidentTypes, + severityCode, + [key]: value, + }); + }, + [incidentTypes, severityCode, onChange, fields] ); - return incidentTypes - ? incidentTypes - .map((type) => ({ - label: allIncidentTypesAsObject[type.toString()], - value: type.toString(), - })) - .filter((type) => type.label != null) - : []; - }, [allIncidentTypes, incidentTypes]); - - const onIncidentChange = useCallback( - (selectedOptions: Array<{ label: string; value?: string }>) => { - onFieldChange( - 'incidentTypes', - selectedOptions.map((selectedOption) => selectedOption.value ?? selectedOption.label) + + const selectedIncidentTypesComboBoxOptionsMemo = useMemo(() => { + const allIncidentTypesAsObject = allIncidentTypes.reduce( + (acc, type) => ({ ...acc, [type.id.toString()]: type.name }), + {} as Record ); - }, - [onFieldChange] - ); - - const onIncidentBlur = useCallback(() => { - if (!incidentTypes) { - onFieldChange('incidentTypes', []); - } - }, [incidentTypes, onFieldChange]); - - // Set field at initialization - useEffect(() => { - if (init.current) { - init.current = false; - onChange({ incidentTypes, severityCode }); - } - }, [incidentTypes, onChange, severityCode]); - - return isEdit ? ( - - - - - - - onFieldChange('severityCode', e.target.value)} - options={severitySelectOptions} - value={severityCode ?? undefined} - /> - - - - ) : ( - - ); -}; + return incidentTypes + ? incidentTypes + .map((type) => ({ + label: allIncidentTypesAsObject[type.toString()], + value: type.toString(), + })) + .filter((type) => type.label != null) + : []; + }, [allIncidentTypes, incidentTypes]); + + const onIncidentChange = useCallback( + (selectedOptions: Array<{ label: string; value?: string }>) => { + onFieldChange( + 'incidentTypes', + selectedOptions.map((selectedOption) => selectedOption.value ?? selectedOption.label) + ); + }, + [onFieldChange] + ); + + const onIncidentBlur = useCallback(() => { + if (!incidentTypes) { + onFieldChange('incidentTypes', []); + } + }, [incidentTypes, onFieldChange]); + + // Set field at initialization + useEffect(() => { + if (init.current) { + init.current = false; + onChange({ incidentTypes, severityCode }); + } + }, [incidentTypes, onChange, severityCode]); + + return isEdit ? ( + + + + + + + onFieldChange('severityCode', e.target.value)} + options={severitySelectOptions} + value={severityCode ?? undefined} + /> + + + + ) : ( + + ); + }; // eslint-disable-next-line import/no-default-export export { ResilientFieldsComponent as default }; diff --git a/x-pack/plugins/cases/public/components/connectors/servicenow/servicenow_itsm_case_fields.tsx b/x-pack/plugins/cases/public/components/connectors/servicenow/servicenow_itsm_case_fields.tsx index 710e23095835..53c0d32dea1a 100644 --- a/x-pack/plugins/cases/public/components/connectors/servicenow/servicenow_itsm_case_fields.tsx +++ b/x-pack/plugins/cases/public/components/connectors/servicenow/servicenow_itsm_case_fields.tsx @@ -30,8 +30,13 @@ const ServiceNowITSMFieldsComponent: React.FunctionComponent< ConnectorFieldsProps > = ({ isEdit = true, fields, connector, onChange }) => { const init = useRef(true); - const { severity = null, urgency = null, impact = null, category = null, subcategory = null } = - fields ?? {}; + const { + severity = null, + urgency = null, + impact = null, + category = null, + subcategory = null, + } = fields ?? {}; const { http, notifications } = useKibana().services; const [choices, setChoices] = useState(defaultFields); diff --git a/x-pack/plugins/cases/public/components/create/connector.test.tsx b/x-pack/plugins/cases/public/components/create/connector.test.tsx index 1b480c3f5d78..a2ffd42f2660 100644 --- a/x-pack/plugins/cases/public/components/create/connector.test.tsx +++ b/x-pack/plugins/cases/public/components/create/connector.test.tsx @@ -172,9 +172,11 @@ describe('Connector', () => { }); act(() => { - ((wrapper.find(EuiComboBox).props() as unknown) as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - }).onChange([{ value: '19', label: 'Denial of Service' }]); + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ value: '19', label: 'Denial of Service' }]); }); act(() => { diff --git a/x-pack/plugins/cases/public/components/create/connector.tsx b/x-pack/plugins/cases/public/components/create/connector.tsx index 2ec6d1ffef23..84695d4011f5 100644 --- a/x-pack/plugins/cases/public/components/create/connector.tsx +++ b/x-pack/plugins/cases/public/components/create/connector.tsx @@ -96,10 +96,10 @@ const ConnectorComponent: React.FC = ({ hideConnectorServiceNowSir, ]); - useEffect(() => setFieldValue('connectorId', defaultConnectorId), [ - defaultConnectorId, - setFieldValue, - ]); + useEffect( + () => setFieldValue('connectorId', defaultConnectorId), + [defaultConnectorId, setFieldValue] + ); const connectorIdConfig = getConnectorsFormValidators({ config: schema.connectorId as FieldConfig, diff --git a/x-pack/plugins/cases/public/components/create/description.tsx b/x-pack/plugins/cases/public/components/create/description.tsx index d831470ea1d5..e1bd563a3d79 100644 --- a/x-pack/plugins/cases/public/components/create/description.tsx +++ b/x-pack/plugins/cases/public/components/create/description.tsx @@ -17,12 +17,8 @@ interface Props { export const fieldName = 'description'; const DescriptionComponent: React.FC = ({ isLoading }) => { - const { - draftComment, - hasIncomingLensState, - openLensModal, - clearDraftComment, - } = useLensDraftComment(); + const { draftComment, hasIncomingLensState, openLensModal, clearDraftComment } = + useLensDraftComment(); const { setFieldValue } = useFormContext(); const [{ title, tags }] = useFormData({ watch: ['title', 'tags'] }); const editorRef = useRef>(); diff --git a/x-pack/plugins/cases/public/components/create/form_context.test.tsx b/x-pack/plugins/cases/public/components/create/form_context.test.tsx index 0ddab55c621d..b988f13ee34c 100644 --- a/x-pack/plugins/cases/public/components/create/form_context.test.tsx +++ b/x-pack/plugins/cases/public/components/create/form_context.test.tsx @@ -101,9 +101,11 @@ const fillForm = (wrapper: ReactWrapper) => { .simulate('change', { target: { value: sampleData.description } }); act(() => { - ((wrapper.find(EuiComboBox).props() as unknown) as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - }).onChange(sampleTags.map((tag) => ({ label: tag }))); + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange(sampleTags.map((tag) => ({ label: tag }))); }); }; @@ -416,9 +418,11 @@ describe('Create case', () => { }); act(() => { - ((wrapper.find(EuiComboBox).at(1).props() as unknown) as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - }).onChange([{ value: '19', label: 'Denial of Service' }]); + ( + wrapper.find(EuiComboBox).at(1).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ value: '19', label: 'Denial of Service' }]); }); wrapper diff --git a/x-pack/plugins/cases/public/components/create/index.test.tsx b/x-pack/plugins/cases/public/components/create/index.test.tsx index 350b971bb05f..ac405673fb9c 100644 --- a/x-pack/plugins/cases/public/components/create/index.test.tsx +++ b/x-pack/plugins/cases/public/components/create/index.test.tsx @@ -63,9 +63,11 @@ const fillForm = (wrapper: ReactWrapper) => { .simulate('change', { target: { value: sampleData.description } }); act(() => { - ((wrapper.find(EuiComboBox).props() as unknown) as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - }).onChange(sampleTags.map((tag) => ({ label: tag }))); + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange(sampleTags.map((tag) => ({ label: tag }))); }); }; diff --git a/x-pack/plugins/cases/public/components/create/tags.test.tsx b/x-pack/plugins/cases/public/components/create/tags.test.tsx index 6efbf1b8c710..b138a5e651f1 100644 --- a/x-pack/plugins/cases/public/components/create/tags.test.tsx +++ b/x-pack/plugins/cases/public/components/create/tags.test.tsx @@ -75,9 +75,11 @@ describe('Tags', () => { ); await waitFor(() => { - ((wrapper.find(EuiComboBox).props() as unknown) as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - }).onChange(['test', 'case'].map((tag) => ({ label: tag }))); + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange(['test', 'case'].map((tag) => ({ label: tag }))); }); expect(globalForm.getFormData()).toEqual({ tags: ['test', 'case'] }); diff --git a/x-pack/plugins/cases/public/components/formatted_date/index.tsx b/x-pack/plugins/cases/public/components/formatted_date/index.tsx index 5bb90bfbff79..caaf63a1add4 100644 --- a/x-pack/plugins/cases/public/components/formatted_date/index.tsx +++ b/x-pack/plugins/cases/public/components/formatted_date/index.tsx @@ -96,21 +96,19 @@ export const FormattedDate = React.memo<{ fieldName: string; value?: string | number | null; className?: string; -}>( - ({ value, fieldName, className = '' }): JSX.Element => { - if (value == null) { - return getOrEmptyTagFromValue(value); - } - const maybeDate = getMaybeDate(value); - return maybeDate.isValid() ? ( - - - - ) : ( - getOrEmptyTagFromValue(value) - ); +}>(({ value, fieldName, className = '' }): JSX.Element => { + if (value == null) { + return getOrEmptyTagFromValue(value); } -); + const maybeDate = getMaybeDate(value); + return maybeDate.isValid() ? ( + + + + ) : ( + getOrEmptyTagFromValue(value) + ); +}); FormattedDate.displayName = 'FormattedDate'; diff --git a/x-pack/plugins/cases/public/components/header_page/index.tsx b/x-pack/plugins/cases/public/components/header_page/index.tsx index d6daf1b57d33..c1c463321d86 100644 --- a/x-pack/plugins/cases/public/components/header_page/index.tsx +++ b/x-pack/plugins/cases/public/components/header_page/index.tsx @@ -52,9 +52,9 @@ const LinkBack = styled.div.attrs({ `; LinkBack.displayName = 'LinkBack'; -const Badge = (styled(EuiBadge)` +const Badge = styled(EuiBadge)` letter-spacing: 0; -` as unknown) as typeof EuiBadge; +` as unknown as typeof EuiBadge; Badge.displayName = 'Badge'; interface BackOptions { diff --git a/x-pack/plugins/cases/public/components/header_page/title.tsx b/x-pack/plugins/cases/public/components/header_page/title.tsx index 629aa612610e..18b10c4f7bbc 100644 --- a/x-pack/plugins/cases/public/components/header_page/title.tsx +++ b/x-pack/plugins/cases/public/components/header_page/title.tsx @@ -19,9 +19,9 @@ const StyledEuiBetaBadge = styled(EuiBetaBadge)` StyledEuiBetaBadge.displayName = 'StyledEuiBetaBadge'; -const Badge = (styled(EuiBadge)` +const Badge = styled(EuiBadge)` letter-spacing: 0; -` as unknown) as typeof EuiBadge; +` as unknown as typeof EuiBadge; Badge.displayName = 'Badge'; interface Props { diff --git a/x-pack/plugins/cases/public/components/insert_timeline/index.test.tsx b/x-pack/plugins/cases/public/components/insert_timeline/index.test.tsx index 84a19578c80d..5b396acc9538 100644 --- a/x-pack/plugins/cases/public/components/insert_timeline/index.test.tsx +++ b/x-pack/plugins/cases/public/components/insert_timeline/index.test.tsx @@ -37,7 +37,7 @@ describe('InsertTimeline ', () => { mount( - + @@ -59,7 +59,7 @@ describe('InsertTimeline ', () => { mount( -
+
diff --git a/x-pack/plugins/cases/public/components/insert_timeline/index.tsx b/x-pack/plugins/cases/public/components/insert_timeline/index.tsx index 473bf5485782..62b8ad715558 100644 --- a/x-pack/plugins/cases/public/components/insert_timeline/index.tsx +++ b/x-pack/plugins/cases/public/components/insert_timeline/index.tsx @@ -15,10 +15,10 @@ export const InsertTimeline = ({ fieldName }: { fieldName: InsertFields }) => { const { setFieldValue, getFormData } = useFormContext(); const timelineHooks = useTimelineContext()?.hooks; const formData = getFormData(); - const onTimelineAttached = useCallback((newValue: string) => setFieldValue(fieldName, newValue), [ - fieldName, - setFieldValue, - ]); + const onTimelineAttached = useCallback( + (newValue: string) => setFieldValue(fieldName, newValue), + [fieldName, setFieldValue] + ); timelineHooks?.useInsertTimeline(formData[fieldName] ?? '', onTimelineAttached); return null; }; diff --git a/x-pack/plugins/cases/public/components/links/index.tsx b/x-pack/plugins/cases/public/components/links/index.tsx index d53d5c973e7d..63032c6d76a2 100644 --- a/x-pack/plugins/cases/public/components/links/index.tsx +++ b/x-pack/plugins/cases/public/components/links/index.tsx @@ -23,9 +23,8 @@ export interface CasesNavigation Promise | void; } -export const LinkButton: React.FC< - PropsForButton | PropsForAnchor -> = ({ children, ...props }) => {children}; +export const LinkButton: React.FC | PropsForAnchor> = + ({ children, ...props }) => {children}; export const LinkAnchor: React.FC = ({ children, ...props }) => ( {children} diff --git a/x-pack/plugins/cases/public/components/markdown_editor/plugins/lens/plugin.tsx b/x-pack/plugins/cases/public/components/markdown_editor/plugins/lens/plugin.tsx index f840b1ea5bb5..4766719b4394 100644 --- a/x-pack/plugins/cases/public/components/markdown_editor/plugins/lens/plugin.tsx +++ b/x-pack/plugins/cases/public/components/markdown_editor/plugins/lens/plugin.tsx @@ -125,10 +125,10 @@ const LensEditorComponent: LensEuiMarkdownEditorUiPlugin['editor'] = ({ [handleClose, markdownContext] ); - const originatingPath = useMemo(() => `${location.pathname}${location.search}`, [ - location.pathname, - location.search, - ]); + const originatingPath = useMemo( + () => `${location.pathname}${location.search}`, + [location.pathname, location.search] + ); const handleCreateInLensClick = useCallback(() => { storage.set(DRAFT_COMMENT_STORAGE_ID, { diff --git a/x-pack/plugins/cases/public/components/markdown_editor/plugins/lens/use_lens_open_visualization.tsx b/x-pack/plugins/cases/public/components/markdown_editor/plugins/lens/use_lens_open_visualization.tsx index 2e6d3634f66b..8060b5383127 100644 --- a/x-pack/plugins/cases/public/components/markdown_editor/plugins/lens/use_lens_open_visualization.tsx +++ b/x-pack/plugins/cases/public/components/markdown_editor/plugins/lens/use_lens_open_visualization.tsx @@ -28,8 +28,8 @@ export const useLensOpenVisualization = ({ comment }: { comment: string }) => { { id: '', timeRange: lensVisualization[0].timeRange, - attributes: (lensVisualization[0] - .attributes as unknown) as TypedLensByValueInput['attributes'], + attributes: lensVisualization[0] + .attributes as unknown as TypedLensByValueInput['attributes'], }, { openInNewTab: true, diff --git a/x-pack/plugins/cases/public/components/markdown_editor/use_plugins.ts b/x-pack/plugins/cases/public/components/markdown_editor/use_plugins.ts index b87b9ae6ad09..c68baf083c12 100644 --- a/x-pack/plugins/cases/public/components/markdown_editor/use_plugins.ts +++ b/x-pack/plugins/cases/public/components/markdown_editor/use_plugins.ts @@ -23,7 +23,8 @@ export const usePlugins = () => { return useMemo(() => { const uiPlugins = getDefaultEuiMarkdownUiPlugins(); const parsingPlugins = getDefaultEuiMarkdownParsingPlugins(); - const processingPlugins = getDefaultEuiMarkdownProcessingPlugins() as TemporaryProcessingPluginsType; + const processingPlugins = + getDefaultEuiMarkdownProcessingPlugins() as TemporaryProcessingPluginsType; if (timelinePlugins) { uiPlugins.push(timelinePlugins.uiPlugin); diff --git a/x-pack/plugins/cases/public/components/recent_cases/index.tsx b/x-pack/plugins/cases/public/components/recent_cases/index.tsx index 607583ff8cf8..2f53fde6980b 100644 --- a/x-pack/plugins/cases/public/components/recent_cases/index.tsx +++ b/x-pack/plugins/cases/public/components/recent_cases/index.tsx @@ -33,9 +33,8 @@ const RecentCasesComponent = ({ hasWritePermissions, }: Omit) => { const currentUser = useCurrentUser(); - const [recentCasesFilterBy, setRecentCasesFilterBy] = useState( - 'recentlyCreated' - ); + const [recentCasesFilterBy, setRecentCasesFilterBy] = + useState('recentlyCreated'); const recentCasesFilterOptions = useMemo( () => diff --git a/x-pack/plugins/cases/public/components/use_push_to_service/callout/callout.tsx b/x-pack/plugins/cases/public/components/use_push_to_service/callout/callout.tsx index bddc066d5f2e..ce96d2e1024f 100644 --- a/x-pack/plugins/cases/public/components/use_push_to_service/callout/callout.tsx +++ b/x-pack/plugins/cases/public/components/use_push_to_service/callout/callout.tsx @@ -31,11 +31,10 @@ const CallOutComponent = ({ type, hasLicenseError, }: CallOutProps) => { - const handleCallOut = useCallback((e) => handleButtonClick(e, id, type), [ - handleButtonClick, - id, - type, - ]); + const handleCallOut = useCallback( + (e) => handleButtonClick(e, id, type), + [handleButtonClick, id, type] + ); const isCaseClosed = useMemo( () => messages.map((m) => m.id).includes(CLOSED_CASE_PUSH_ERROR_ID), diff --git a/x-pack/plugins/cases/public/components/user_action_tree/index.tsx b/x-pack/plugins/cases/public/components/user_action_tree/index.tsx index a8c270ef4d55..784817229caf 100644 --- a/x-pack/plugins/cases/public/components/user_action_tree/index.tsx +++ b/x-pack/plugins/cases/public/components/user_action_tree/index.tsx @@ -150,7 +150,11 @@ export const UserActionTree = React.memo( useFetchAlertData, userCanCrud, }: UserActionTreeProps) => { - const { detailName: caseId, commentId, subCaseId } = useParams<{ + const { + detailName: caseId, + commentId, + subCaseId, + } = useParams<{ detailName: string; commentId?: string; subCaseId?: string; @@ -162,12 +166,8 @@ export const UserActionTree = React.memo( const currentUser = useCurrentUser(); const [manageMarkdownEditIds, setManageMarkdownEditIds] = useState([]); const commentRefs = useRef>({}); - const { - clearDraftComment, - draftComment, - hasIncomingLensState, - openLensModal, - } = useLensDraftComment(); + const { clearDraftComment, draftComment, hasIncomingLensState, openLensModal } = + useLensDraftComment(); const [loadingAlertData, manualAlertsData] = useFetchAlertData( getManualAlertIdsWithNoRuleId(caseData.comments) diff --git a/x-pack/plugins/cases/public/components/user_action_tree/user_action_show_alert.tsx b/x-pack/plugins/cases/public/components/user_action_tree/user_action_show_alert.tsx index 4f5ce0080641..c16382a96bb9 100644 --- a/x-pack/plugins/cases/public/components/user_action_tree/user_action_show_alert.tsx +++ b/x-pack/plugins/cases/public/components/user_action_tree/user_action_show_alert.tsx @@ -22,11 +22,10 @@ const UserActionShowAlertComponent = ({ index, onShowAlertDetails, }: UserActionShowAlertProps) => { - const onClick = useCallback(() => onShowAlertDetails(alertId, index), [ - alertId, - index, - onShowAlertDetails, - ]); + const onClick = useCallback( + () => onShowAlertDetails(alertId, index), + [alertId, index, onShowAlertDetails] + ); return ( {i18n.SHOW_ALERT_TOOLTIP}

}> { test('check url, body, method, signal', async () => { await postCaseConfigure(caseConfigurationMock, abortCtrl.signal); expect(fetchMock).toHaveBeenCalledWith('/api/cases/configure', { - body: - '{"connector":{"id":"123","name":"My connector","type":".jira","fields":null},"owner":"securitySolution","closure_type":"close-by-user"}', + body: '{"connector":{"id":"123","name":"My connector","type":".jira","fields":null},"owner":"securitySolution","closure_type":"close-by-user"}', method: 'POST', signal: abortCtrl.signal, }); @@ -123,8 +122,7 @@ describe('Case Configuration API', () => { abortCtrl.signal ); expect(fetchMock).toHaveBeenCalledWith('/api/cases/configure/123', { - body: - '{"connector":{"id":"456","name":"My Connector 2","type":".none","fields":null},"version":"WzHJ12"}', + body: '{"connector":{"id":"456","name":"My Connector 2","type":".none","fields":null},"version":"WzHJ12"}', method: 'PATCH', signal: abortCtrl.signal, }); diff --git a/x-pack/plugins/cases/public/containers/use_get_case_user_actions.tsx b/x-pack/plugins/cases/public/containers/use_get_case_user_actions.tsx index edafa1b9a10a..e481519ba19a 100644 --- a/x-pack/plugins/cases/public/containers/use_get_case_user_actions.tsx +++ b/x-pack/plugins/cases/public/containers/use_get_case_user_actions.tsx @@ -250,9 +250,8 @@ export const useGetCaseUserActions = ( caseConnectorId: string, subCaseId?: string ): UseGetCaseUserActions => { - const [caseUserActionsState, setCaseUserActionsState] = useState( - initialData - ); + const [caseUserActionsState, setCaseUserActionsState] = + useState(initialData); const abortCtrlRef = useRef(new AbortController()); const isCancelledRef = useRef(false); const toasts = useToasts(); diff --git a/x-pack/plugins/cases/server/authorization/authorization.test.ts b/x-pack/plugins/cases/server/authorization/authorization.test.ts index e602de565f29..f644f7366100 100644 --- a/x-pack/plugins/cases/server/authorization/authorization.test.ts +++ b/x-pack/plugins/cases/server/authorization/authorization.test.ts @@ -34,9 +34,9 @@ describe('authorization', () => { beforeEach(() => { securityStart = securityMock.createStart(); featuresStart = featuresPluginMock.createStart(); - featuresStart.getKibanaFeatures.mockReturnValue(([ + featuresStart.getKibanaFeatures.mockReturnValue([ { id: '1', cases: ['a'] }, - ] as unknown) as KibanaFeature[]); + ] as unknown as KibanaFeature[]); }); it('creates an Authorization object', async () => { @@ -91,7 +91,7 @@ describe('authorization', () => { ); featuresStart = featuresPluginMock.createStart(); - featuresStart.getKibanaFeatures.mockReturnValue(([feature] as unknown) as KibanaFeature[]); + featuresStart.getKibanaFeatures.mockReturnValue([feature] as unknown as KibanaFeature[]); auth = await Authorization.create({ request, @@ -265,10 +265,10 @@ describe('authorization', () => { it('does not throw an error when the user has the privileges needed', async () => { expect.assertions(1); - featuresStart.getKibanaFeatures.mockReturnValue(([ + featuresStart.getKibanaFeatures.mockReturnValue([ feature, { id: '2', cases: ['other-owner'] }, - ] as unknown) as KibanaFeature[]); + ] as unknown as KibanaFeature[]); auth = await Authorization.create({ request, @@ -293,9 +293,9 @@ describe('authorization', () => { it('does not throw an error when the user has the privileges needed with a feature specifying multiple owners', async () => { expect.assertions(1); - featuresStart.getKibanaFeatures.mockReturnValue(([ + featuresStart.getKibanaFeatures.mockReturnValue([ { id: '2', cases: ['a', 'other-owner'] }, - ] as unknown) as KibanaFeature[]); + ] as unknown as KibanaFeature[]); auth = await Authorization.create({ request, @@ -320,9 +320,9 @@ describe('authorization', () => { it('logs a successful authorization when the user has the privileges needed with a feature specifying multiple owners', async () => { expect.assertions(2); - featuresStart.getKibanaFeatures.mockReturnValue(([ + featuresStart.getKibanaFeatures.mockReturnValue([ { id: '2', cases: ['a', 'other-owner'] }, - ] as unknown) as KibanaFeature[]); + ] as unknown as KibanaFeature[]); auth = await Authorization.create({ request, @@ -411,7 +411,7 @@ describe('authorization', () => { ); featuresStart = featuresPluginMock.createStart(); - featuresStart.getKibanaFeatures.mockReturnValue(([feature] as unknown) as KibanaFeature[]); + featuresStart.getKibanaFeatures.mockReturnValue([feature] as unknown as KibanaFeature[]); auth = await Authorization.create({ request, @@ -736,15 +736,17 @@ describe('authorization', () => { })) ); - (securityStart.authz.actions.cases.get as jest.MockedFunction< - typeof securityStart.authz.actions.cases.get - >).mockImplementation((owner, opName) => { + ( + securityStart.authz.actions.cases.get as jest.MockedFunction< + typeof securityStart.authz.actions.cases.get + > + ).mockImplementation((owner, opName) => { return `${owner}:${opName}`; }); - featuresStart.getKibanaFeatures.mockReturnValue(([ + featuresStart.getKibanaFeatures.mockReturnValue([ { id: 'a', cases: ['a', 'b', 'c'] }, - ] as unknown) as KibanaFeature[]); + ] as unknown as KibanaFeature[]); auth = await Authorization.create({ request, diff --git a/x-pack/plugins/cases/server/authorization/authorization.ts b/x-pack/plugins/cases/server/authorization/authorization.ts index 71cd38363778..3598c5b8956f 100644 --- a/x-pack/plugins/cases/server/authorization/authorization.ts +++ b/x-pack/plugins/cases/server/authorization/authorization.ts @@ -204,9 +204,7 @@ export class Authorization { }; } - private async getAuthorizedOwners( - operations: OperationDetails[] - ): Promise<{ + private async getAuthorizedOwners(operations: OperationDetails[]): Promise<{ username?: string; hasAllRequested: boolean; authorizedOwners: string[]; diff --git a/x-pack/plugins/cases/server/client/attachments/add.ts b/x-pack/plugins/cases/server/client/attachments/add.ts index 166ae2ae6501..507405d58cef 100644 --- a/x-pack/plugins/cases/server/client/attachments/add.ts +++ b/x-pack/plugins/cases/server/client/attachments/add.ts @@ -187,15 +187,13 @@ const addGeneratedAlerts = async ( lensEmbeddableFactory, }); - const { - comment: newComment, - commentableCase: updatedCase, - } = await commentableCase.createComment({ - createdDate, - user: userDetails, - commentReq: query, - id: savedObjectID, - }); + const { comment: newComment, commentableCase: updatedCase } = + await commentableCase.createComment({ + createdDate, + user: userDetails, + commentReq: query, + id: savedObjectID, + }); if ( (newComment.attributes.type === CommentType.alert || diff --git a/x-pack/plugins/cases/server/client/attachments/get.ts b/x-pack/plugins/cases/server/client/attachments/get.ts index 4f4ade51f9a5..9a06c5142600 100644 --- a/x-pack/plugins/cases/server/client/attachments/get.ts +++ b/x-pack/plugins/cases/server/client/attachments/get.ts @@ -124,10 +124,8 @@ export const getAllAlertsAttachToCase = async ( includeSubCaseComments: false, }); - const { - filter: authorizationFilter, - ensureSavedObjectsAreAuthorized, - } = await authorization.getAuthorizationFilter(Operations.getAlertsAttachedToCase); + const { filter: authorizationFilter, ensureSavedObjectsAreAuthorized } = + await authorization.getAuthorizationFilter(Operations.getAlertsAttachedToCase); const alerts = await attachmentService.getAllAlertsAttachToCase({ unsecuredSavedObjectsClient, @@ -159,10 +157,8 @@ export async function find( try { checkEnabledCaseConnectorOrThrow(queryParams?.subCaseId); - const { - filter: authorizationFilter, - ensureSavedObjectsAreAuthorized, - } = await authorization.getAuthorizationFilter(Operations.findComments); + const { filter: authorizationFilter, ensureSavedObjectsAreAuthorized } = + await authorization.getAuthorizationFilter(Operations.findComments); const id = queryParams?.subCaseId ?? caseID; const associationType = queryParams?.subCaseId ? AssociationType.subCase : AssociationType.case; diff --git a/x-pack/plugins/cases/server/client/attachments/update.ts b/x-pack/plugins/cases/server/client/attachments/update.ts index da505ed55313..9816efd9a845 100644 --- a/x-pack/plugins/cases/server/client/attachments/update.ts +++ b/x-pack/plugins/cases/server/client/attachments/update.ts @@ -175,14 +175,12 @@ export async function update( } const updatedDate = new Date().toISOString(); - const { - comment: updatedComment, - commentableCase: updatedCase, - } = await commentableCase.updateComment({ - updateRequest: queryParams, - updatedAt: updatedDate, - user, - }); + const { comment: updatedComment, commentableCase: updatedCase } = + await commentableCase.updateComment({ + updateRequest: queryParams, + updatedAt: updatedDate, + user, + }); await userActionService.bulkCreate({ unsecuredSavedObjectsClient, diff --git a/x-pack/plugins/cases/server/client/cases/find.ts b/x-pack/plugins/cases/server/client/cases/find.ts index 4b8f82b939a4..282ff956b7a6 100644 --- a/x-pack/plugins/cases/server/client/cases/find.ts +++ b/x-pack/plugins/cases/server/client/cases/find.ts @@ -43,10 +43,8 @@ export const find = async ( fold(throwErrors(Boom.badRequest), identity) ); - const { - filter: authorizationFilter, - ensureSavedObjectsAreAuthorized, - } = await authorization.getAuthorizationFilter(Operations.findCases); + const { filter: authorizationFilter, ensureSavedObjectsAreAuthorized } = + await authorization.getAuthorizationFilter(Operations.findCases); const queryArgs = { tags: queryParams.tags, diff --git a/x-pack/plugins/cases/server/client/cases/get.ts b/x-pack/plugins/cases/server/client/cases/get.ts index d440cecd27e9..6b0015d4ffb1 100644 --- a/x-pack/plugins/cases/server/client/cases/get.ts +++ b/x-pack/plugins/cases/server/client/cases/get.ts @@ -66,10 +66,8 @@ export const getCasesByAlertID = async ( fold(throwErrors(Boom.badRequest), identity) ); - const { - filter: authorizationFilter, - ensureSavedObjectsAreAuthorized, - } = await authorization.getAuthorizationFilter(Operations.getCaseIDsByAlertID); + const { filter: authorizationFilter, ensureSavedObjectsAreAuthorized } = + await authorization.getAuthorizationFilter(Operations.getCaseIDsByAlertID); const filter = combineAuthorizedAndOwnerFilter( queryParams.owner, @@ -248,10 +246,8 @@ export async function getTags( fold(throwErrors(Boom.badRequest), identity) ); - const { - filter: authorizationFilter, - ensureSavedObjectsAreAuthorized, - } = await authorization.getAuthorizationFilter(Operations.findCases); + const { filter: authorizationFilter, ensureSavedObjectsAreAuthorized } = + await authorization.getAuthorizationFilter(Operations.findCases); const filter = combineAuthorizedAndOwnerFilter(queryParams.owner, authorizationFilter); @@ -298,10 +294,8 @@ export async function getReporters( fold(throwErrors(Boom.badRequest), identity) ); - const { - filter: authorizationFilter, - ensureSavedObjectsAreAuthorized, - } = await authorization.getAuthorizationFilter(Operations.getReporters); + const { filter: authorizationFilter, ensureSavedObjectsAreAuthorized } = + await authorization.getAuthorizationFilter(Operations.getReporters); const filter = combineAuthorizedAndOwnerFilter(queryParams.owner, authorizationFilter); diff --git a/x-pack/plugins/cases/server/client/cases/utils.ts b/x-pack/plugins/cases/server/client/cases/utils.ts index 617191462c55..359ad4b41ead 100644 --- a/x-pack/plugins/cases/server/client/cases/utils.ts +++ b/x-pack/plugins/cases/server/client/cases/utils.ts @@ -173,13 +173,13 @@ export const createIncident = async ({ if (externalId) { try { - currentIncident = ((await actionsClient.execute({ + currentIncident = (await actionsClient.execute({ actionId: connector.id, params: { subAction: 'getIncident', subActionParams: { externalId }, }, - })) as unknown) as ExternalServiceParams | undefined; + })) as unknown as ExternalServiceParams | undefined; } catch (ex) { throw new Error( `Retrieving Incident by id ${externalId} from ${connector.actionTypeId} failed with exception: ${ex}` diff --git a/x-pack/plugins/cases/server/client/configure/client.ts b/x-pack/plugins/cases/server/client/configure/client.ts index ad7e1322c9e0..791fcc70947d 100644 --- a/x-pack/plugins/cases/server/client/configure/client.ts +++ b/x-pack/plugins/cases/server/client/configure/client.ts @@ -144,10 +144,8 @@ async function get( fold(throwErrors(Boom.badRequest), identity) ); - const { - filter: authorizationFilter, - ensureSavedObjectsAreAuthorized, - } = await authorization.getAuthorizationFilter(Operations.findConfigurations); + const { filter: authorizationFilter, ensureSavedObjectsAreAuthorized } = + await authorization.getAuthorizationFilter(Operations.findConfigurations); const filter = combineAuthorizedAndOwnerFilter( queryParams.owner, @@ -237,13 +235,8 @@ async function update( clientArgs: CasesClientArgs, casesClientInternal: CasesClientInternal ): Promise { - const { - caseConfigureService, - logger, - unsecuredSavedObjectsClient, - user, - authorization, - } = clientArgs; + const { caseConfigureService, logger, unsecuredSavedObjectsClient, user, authorization } = + clientArgs; try { const request = pipe( @@ -349,27 +342,20 @@ async function create( clientArgs: CasesClientArgs, casesClientInternal: CasesClientInternal ): Promise { - const { - unsecuredSavedObjectsClient, - caseConfigureService, - logger, - user, - authorization, - } = clientArgs; + const { unsecuredSavedObjectsClient, caseConfigureService, logger, user, authorization } = + clientArgs; try { let error = null; - const { - filter: authorizationFilter, - ensureSavedObjectsAreAuthorized, - } = await authorization.getAuthorizationFilter( - /** - * The operation is createConfiguration because the procedure is part of - * the create route. The user should have all - * permissions to delete the results. - */ - Operations.createConfiguration - ); + const { filter: authorizationFilter, ensureSavedObjectsAreAuthorized } = + await authorization.getAuthorizationFilter( + /** + * The operation is createConfiguration because the procedure is part of + * the create route. The user should have all + * permissions to delete the results. + */ + Operations.createConfiguration + ); const filter = combineAuthorizedAndOwnerFilter( configuration.owner, diff --git a/x-pack/plugins/cases/server/client/mocks.ts b/x-pack/plugins/cases/server/client/mocks.ts index f7c27166ee91..05b7d055656b 100644 --- a/x-pack/plugins/cases/server/client/mocks.ts +++ b/x-pack/plugins/cases/server/client/mocks.ts @@ -101,7 +101,7 @@ export const createCasesClientMock = (): CasesClientMock => { configure: createConfigureSubClientMock(), stats: createStatsSubClientMock(), }; - return (client as unknown) as CasesClientMock; + return client as unknown as CasesClientMock; }; export type CasesClientFactoryMock = jest.Mocked; @@ -112,5 +112,5 @@ export const createCasesClientFactory = (): CasesClientFactoryMock => { create: jest.fn(), }; - return (factory as unknown) as CasesClientFactoryMock; + return factory as unknown as CasesClientFactoryMock; }; diff --git a/x-pack/plugins/cases/server/client/stats/client.ts b/x-pack/plugins/cases/server/client/stats/client.ts index 4cdb11ad15e5..b13a15c799f9 100644 --- a/x-pack/plugins/cases/server/client/stats/client.ts +++ b/x-pack/plugins/cases/server/client/stats/client.ts @@ -58,10 +58,8 @@ async function getStatusTotalsByType( fold(throwErrors(Boom.badRequest), identity) ); - const { - filter: authorizationFilter, - ensureSavedObjectsAreAuthorized, - } = await authorization.getAuthorizationFilter(Operations.getCaseStatuses); + const { filter: authorizationFilter, ensureSavedObjectsAreAuthorized } = + await authorization.getAuthorizationFilter(Operations.getCaseStatuses); // casesStatuses are bounded by us. No need to limit concurrent calls. const [openCases, inProgressCases, closedCases] = await Promise.all([ diff --git a/x-pack/plugins/cases/server/client/sub_cases/client.ts b/x-pack/plugins/cases/server/client/sub_cases/client.ts index 6ca5a80565a7..52aa8431e297 100644 --- a/x-pack/plugins/cases/server/client/sub_cases/client.ts +++ b/x-pack/plugins/cases/server/client/sub_cases/client.ts @@ -100,13 +100,8 @@ export function createSubCasesClient( async function deleteSubCase(ids: string[], clientArgs: CasesClientArgs): Promise { try { - const { - unsecuredSavedObjectsClient, - user, - userActionService, - caseService, - attachmentService, - } = clientArgs; + const { unsecuredSavedObjectsClient, user, userActionService, caseService, attachmentService } = + clientArgs; const [comments, subCases] = await Promise.all([ caseService.getAllSubCaseComments({ unsecuredSavedObjectsClient, id: ids }), diff --git a/x-pack/plugins/cases/server/common/utils.test.ts b/x-pack/plugins/cases/server/common/utils.test.ts index e45b91a28ceb..51d787a0334a 100644 --- a/x-pack/plugins/cases/server/common/utils.test.ts +++ b/x-pack/plugins/cases/server/common/utils.test.ts @@ -769,9 +769,7 @@ describe('common utils', () => { }, ]), }) - ).toEqual( - new Map([['1', 2]]) - ); + ).toEqual(new Map([['1', 2]])); }); it('returns a map with two entry, 2 alerts, and 0 alerts', () => { diff --git a/x-pack/plugins/cases/server/connectors/jira/format.ts b/x-pack/plugins/cases/server/connectors/jira/format.ts index 3dadd9a107d5..b281d94062f4 100644 --- a/x-pack/plugins/cases/server/connectors/jira/format.ts +++ b/x-pack/plugins/cases/server/connectors/jira/format.ts @@ -9,8 +9,11 @@ import { ConnectorJiraTypeFields } from '../../../common'; import { Format } from './types'; export const format: Format = (theCase, alerts) => { - const { priority = null, issueType = null, parent = null } = - (theCase.connector.fields as ConnectorJiraTypeFields['fields']) ?? {}; + const { + priority = null, + issueType = null, + parent = null, + } = (theCase.connector.fields as ConnectorJiraTypeFields['fields']) ?? {}; return { priority, // Jira do not allows empty spaces on labels. We replace white spaces with hyphens diff --git a/x-pack/plugins/cases/server/connectors/servicenow/itsm_format.ts b/x-pack/plugins/cases/server/connectors/servicenow/itsm_format.ts index 22bd84df6630..bc9d50026d1f 100644 --- a/x-pack/plugins/cases/server/connectors/servicenow/itsm_format.ts +++ b/x-pack/plugins/cases/server/connectors/servicenow/itsm_format.ts @@ -9,7 +9,12 @@ import { ConnectorServiceNowITSMTypeFields } from '../../../common'; import { ServiceNowITSMFormat } from './types'; export const format: ServiceNowITSMFormat = (theCase, alerts) => { - const { severity = null, urgency = null, impact = null, category = null, subcategory = null } = - (theCase.connector.fields as ConnectorServiceNowITSMTypeFields['fields']) ?? {}; + const { + severity = null, + urgency = null, + impact = null, + category = null, + subcategory = null, + } = (theCase.connector.fields as ConnectorServiceNowITSMTypeFields['fields']) ?? {}; return { severity, urgency, impact, category, subcategory }; }; diff --git a/x-pack/plugins/cases/server/saved_object_types/migrations/cases.ts b/x-pack/plugins/cases/server/saved_object_types/migrations/cases.ts index 8296de57b37a..bffd4171270e 100644 --- a/x-pack/plugins/cases/server/saved_object_types/migrations/cases.ts +++ b/x-pack/plugins/cases/server/saved_object_types/migrations/cases.ts @@ -50,14 +50,11 @@ export const caseConnectorIdMigration = ( // removing the id field since it will be stored in the references instead const { connector, external_service, ...restAttributes } = doc.attributes; - const { transformedConnector, references: connectorReferences } = transformConnectorIdToReference( - connector - ); + const { transformedConnector, references: connectorReferences } = + transformConnectorIdToReference(connector); - const { - transformedPushConnector, - references: pushConnectorReferences, - } = transformPushConnectorIdToReference(external_service); + const { transformedPushConnector, references: pushConnectorReferences } = + transformPushConnectorIdToReference(external_service); const { references = [] } = doc; diff --git a/x-pack/plugins/cases/server/saved_object_types/migrations/comments.test.ts b/x-pack/plugins/cases/server/saved_object_types/migrations/comments.test.ts index d1bfe7257c01..9e8ff1a33468 100644 --- a/x-pack/plugins/cases/server/saved_object_types/migrations/comments.test.ts +++ b/x-pack/plugins/cases/server/saved_object_types/migrations/comments.test.ts @@ -220,9 +220,9 @@ describe('index migrations', () => { const result = migrations['7.14.0'](caseComment, contextMock); const parsedComment = parseCommentString(result.attributes.comment); - const lensVisualizations = (getLensVisualizations( + const lensVisualizations = getLensVisualizations( parsedComment.children - ) as unknown) as Array<{ + ) as unknown as Array<{ attributes: LensDocShape715 & { references: SavedObjectReference[] }; }>; diff --git a/x-pack/plugins/cases/server/saved_object_types/migrations/comments.ts b/x-pack/plugins/cases/server/saved_object_types/migrations/comments.ts index 03188d8e75e8..d754aec63669 100644 --- a/x-pack/plugins/cases/server/saved_object_types/migrations/comments.ts +++ b/x-pack/plugins/cases/server/saved_object_types/migrations/comments.ts @@ -103,37 +103,34 @@ export const createCommentsMigrations = ( return mergeMigrationFunctionMaps(commentsMigrations, embeddableMigrations); }; -const migrateByValueLensVisualizations = ( - migrate: MigrateFunction, - version: string -): SavedObjectMigrationFn<{ comment?: string }> => ( - doc: SavedObjectUnsanitizedDoc<{ comment?: string }> -) => { - if (doc.attributes.comment == null) { - return doc; - } - - const parsedComment = parseCommentString(doc.attributes.comment); - const migratedComment = parsedComment.children.map((comment) => { - if (isLensMarkdownNode(comment)) { - // casting here because ts complains that comment isn't serializable because LensMarkdownNode - // extends Node which has fields that conflict with SerializableRecord even though it is serializable - return migrate(comment as SerializableRecord) as LensMarkdownNode; +const migrateByValueLensVisualizations = + (migrate: MigrateFunction, version: string): SavedObjectMigrationFn<{ comment?: string }> => + (doc: SavedObjectUnsanitizedDoc<{ comment?: string }>) => { + if (doc.attributes.comment == null) { + return doc; } - return comment; - }); + const parsedComment = parseCommentString(doc.attributes.comment); + const migratedComment = parsedComment.children.map((comment) => { + if (isLensMarkdownNode(comment)) { + // casting here because ts complains that comment isn't serializable because LensMarkdownNode + // extends Node which has fields that conflict with SerializableRecord even though it is serializable + return migrate(comment as SerializableRecord) as LensMarkdownNode; + } + + return comment; + }); - const migratedMarkdown = { ...parsedComment, children: migratedComment }; + const migratedMarkdown = { ...parsedComment, children: migratedComment }; - return { - ...doc, - attributes: { - ...doc.attributes, - comment: stringifyCommentWithoutTrailingNewline(doc.attributes.comment, migratedMarkdown), - }, + return { + ...doc, + attributes: { + ...doc.attributes, + comment: stringifyCommentWithoutTrailingNewline(doc.attributes.comment, migratedMarkdown), + }, + }; }; -}; export const stringifyCommentWithoutTrailingNewline = ( originalComment: string, diff --git a/x-pack/plugins/cases/server/saved_object_types/migrations/configuration.ts b/x-pack/plugins/cases/server/saved_object_types/migrations/configuration.ts index 3209feb2a9a9..527d40fca2e3 100644 --- a/x-pack/plugins/cases/server/saved_object_types/migrations/configuration.ts +++ b/x-pack/plugins/cases/server/saved_object_types/migrations/configuration.ts @@ -34,9 +34,8 @@ export const configureConnectorIdMigration = ( ): SavedObjectSanitizedDoc => { // removing the id field since it will be stored in the references instead const { connector, ...restAttributes } = doc.attributes; - const { transformedConnector, references: connectorReferences } = transformConnectorIdToReference( - connector - ); + const { transformedConnector, references: connectorReferences } = + transformConnectorIdToReference(connector); const { references = [] } = doc; return { diff --git a/x-pack/plugins/cases/server/services/cases/index.test.ts b/x-pack/plugins/cases/server/services/cases/index.test.ts index aec188037f09..18f4ff867cfa 100644 --- a/x-pack/plugins/cases/server/services/cases/index.test.ts +++ b/x-pack/plugins/cases/server/services/cases/index.test.ts @@ -1119,7 +1119,7 @@ describe('CasesService', () => { it('defaults to the none connector and null external_services when attributes is undefined', async () => { unsecuredSavedObjectsClient.get.mockReturnValue( - Promise.resolve(({ + Promise.resolve({ references: [ { id: '1', @@ -1127,7 +1127,7 @@ describe('CasesService', () => { type: ACTION_SAVED_OBJECT_TYPE, }, ], - } as unknown) as SavedObject) + } as unknown as SavedObject) ); const res = await service.getCase({ unsecuredSavedObjectsClient, id: 'a' }); diff --git a/x-pack/plugins/cases/server/services/cases/transform.ts b/x-pack/plugins/cases/server/services/cases/transform.ts index 00b20a629086..e3609689871d 100644 --- a/x-pack/plugins/cases/server/services/cases/transform.ts +++ b/x-pack/plugins/cases/server/services/cases/transform.ts @@ -70,21 +70,15 @@ export function transformUpdateResponseToExternalModel( }; } -export function transformAttributesToESModel( - caseAttributes: CaseAttributes -): { +export function transformAttributesToESModel(caseAttributes: CaseAttributes): { attributes: ESCaseAttributes; referenceHandler: ConnectorReferenceHandler; }; -export function transformAttributesToESModel( - caseAttributes: Partial -): { +export function transformAttributesToESModel(caseAttributes: Partial): { attributes: Partial; referenceHandler: ConnectorReferenceHandler; }; -export function transformAttributesToESModel( - caseAttributes: Partial -): { +export function transformAttributesToESModel(caseAttributes: Partial): { attributes: Partial; referenceHandler: ConnectorReferenceHandler; } { diff --git a/x-pack/plugins/cases/server/services/configure/index.test.ts b/x-pack/plugins/cases/server/services/configure/index.test.ts index 045142ea13e1..876cb7b21f81 100644 --- a/x-pack/plugins/cases/server/services/configure/index.test.ts +++ b/x-pack/plugins/cases/server/services/configure/index.test.ts @@ -696,7 +696,7 @@ describe('CaseConfigureService', () => { it('defaults to the none connector when attributes is undefined', async () => { unsecuredSavedObjectsClient.get.mockReturnValue( - Promise.resolve(({ + Promise.resolve({ references: [ { id: '1', @@ -704,7 +704,7 @@ describe('CaseConfigureService', () => { type: ACTION_SAVED_OBJECT_TYPE, }, ], - } as unknown) as SavedObject) + } as unknown as SavedObject) ); const res = await service.get({ unsecuredSavedObjectsClient, configurationId: '1' }); diff --git a/x-pack/plugins/cases/server/services/configure/index.ts b/x-pack/plugins/cases/server/services/configure/index.ts index a25818f4ff59..db6d033f23ca 100644 --- a/x-pack/plugins/cases/server/services/configure/index.ts +++ b/x-pack/plugins/cases/server/services/configure/index.ts @@ -134,16 +134,17 @@ export class CaseConfigureService { this.log.debug(`Attempting to UPDATE case configuration ${configurationId}`); const esUpdateInfo = transformAttributesToESModel(updatedAttributes); - const updatedConfiguration = await unsecuredSavedObjectsClient.update( - CASE_CONFIGURE_SAVED_OBJECT, - configurationId, - { - ...esUpdateInfo.attributes, - }, - { - references: esUpdateInfo.referenceHandler.build(originalConfiguration.references), - } - ); + const updatedConfiguration = + await unsecuredSavedObjectsClient.update( + CASE_CONFIGURE_SAVED_OBJECT, + configurationId, + { + ...esUpdateInfo.attributes, + }, + { + references: esUpdateInfo.referenceHandler.build(originalConfiguration.references), + } + ); return transformUpdateResponseToExternalModel(updatedConfiguration); } catch (error) { @@ -205,21 +206,15 @@ function transformFindResponseToExternalModel( }; } -function transformAttributesToESModel( - configuration: CasesConfigureAttributes -): { +function transformAttributesToESModel(configuration: CasesConfigureAttributes): { attributes: ESCasesConfigureAttributes; referenceHandler: ConnectorReferenceHandler; }; -function transformAttributesToESModel( - configuration: Partial -): { +function transformAttributesToESModel(configuration: Partial): { attributes: Partial; referenceHandler: ConnectorReferenceHandler; }; -function transformAttributesToESModel( - configuration: Partial -): { +function transformAttributesToESModel(configuration: Partial): { attributes: Partial; referenceHandler: ConnectorReferenceHandler; } { diff --git a/x-pack/plugins/cases/server/services/mocks.ts b/x-pack/plugins/cases/server/services/mocks.ts index c82624cd50ab..a29d227cfbb0 100644 --- a/x-pack/plugins/cases/server/services/mocks.ts +++ b/x-pack/plugins/cases/server/services/mocks.ts @@ -55,7 +55,7 @@ export const createCaseServiceMock = (): CaseServiceMock => { }; // the cast here is required because jest.Mocked tries to include private members and would throw an error - return (service as unknown) as CaseServiceMock; + return service as unknown as CaseServiceMock; }; export const createConfigureServiceMock = (): CaseConfigureServiceMock => { @@ -68,7 +68,7 @@ export const createConfigureServiceMock = (): CaseConfigureServiceMock => { }; // the cast here is required because jest.Mocked tries to include private members and would throw an error - return (service as unknown) as CaseConfigureServiceMock; + return service as unknown as CaseConfigureServiceMock; }; export const connectorMappingsServiceMock = (): ConnectorMappingsServiceMock => { @@ -79,7 +79,7 @@ export const connectorMappingsServiceMock = (): ConnectorMappingsServiceMock => }; // the cast here is required because jest.Mocked tries to include private members and would throw an error - return (service as unknown) as ConnectorMappingsServiceMock; + return service as unknown as ConnectorMappingsServiceMock; }; export const createUserActionServiceMock = (): CaseUserActionServiceMock => { @@ -89,7 +89,7 @@ export const createUserActionServiceMock = (): CaseUserActionServiceMock => { }; // the cast here is required because jest.Mocked tries to include private members and would throw an error - return (service as unknown) as CaseUserActionServiceMock; + return service as unknown as CaseUserActionServiceMock; }; export const createAlertServiceMock = (): AlertServiceMock => ({ @@ -108,5 +108,5 @@ export const createAttachmentServiceMock = (): AttachmentServiceMock => { }; // the cast here is required because jest.Mocked tries to include private members and would throw an error - return (service as unknown) as AttachmentServiceMock; + return service as unknown as AttachmentServiceMock; }; 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 f5f6615f9dcd..900d8c9046ef 100644 --- a/x-pack/plugins/cross_cluster_replication/common/services/utils.ts +++ b/x-pack/plugins/cross_cluster_replication/common/services/utils.ts @@ -12,22 +12,24 @@ 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) => { - setTimeout(() => resolve(data), time); - }); -}; +export const wait = + (time = 1000) => + (data: any): Promise => { + return new Promise((resolve) => { + setTimeout(() => resolve(data), time); + }); + }; /** * Utility to remove empty fields ("") from a request body */ export const removeEmptyFields = (body: Record): Record => - Object.entries(body).reduce((acc: Record, [key, value]: [string, any]): Record< - string, - any - > => { - if (value !== '') { - acc[key] = value; - } - return acc; - }, {}); + Object.entries(body).reduce( + (acc: Record, [key, value]: [string, any]): Record => { + if (value !== '') { + acc[key] = value; + } + return acc; + }, + {} + ); 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 6d54444df427..10e41a8b18d5 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 @@ -102,9 +102,8 @@ describe('Create Follower index', () => { autoFollowPatternAddComponent.update(); const remoteClusterFormFieldFollowerIndex = component.find(RemoteClustersFormField); - const remoteClusterFormFieldAutoFollowPattern = autoFollowPatternAddComponent.find( - RemoteClustersFormField - ); + const remoteClusterFormFieldAutoFollowPattern = + autoFollowPatternAddComponent.find(RemoteClustersFormField); expect(remoteClusterFormFieldFollowerIndex.length).toBe(1); expect(remoteClusterFormFieldAutoFollowPattern.length).toBe(1); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/app.tsx b/x-pack/plugins/cross_cluster_replication/public/app/app.tsx index c6144143e184..dba5db9df5b8 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/app.tsx +++ b/x-pack/plugins/cross_cluster_replication/public/app/app.tsx @@ -102,12 +102,8 @@ class AppComponent extends Component { } render() { - const { - isFetchingPermissions, - fetchPermissionError, - hasPermission, - missingClusterPrivileges, - } = this.state; + const { isFetchingPermissions, fetchPermissionError, hasPermission, missingClusterPrivileges } = + this.state; if (isFetchingPermissions) { return ( 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 dc117a9cd458..451f2a94fe91 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 @@ -73,22 +73,26 @@ const getEmptyFollowerIndex = (remoteClusterName = '') => ({ /** * State transitions: fields update */ -export const updateFields = (fields) => ({ followerIndex }) => ({ - followerIndex: { - ...followerIndex, - ...fields, - }, -}); +export const updateFields = + (fields) => + ({ followerIndex }) => ({ + followerIndex: { + ...followerIndex, + ...fields, + }, + }); /** * State transitions: errors update */ -export const updateFormErrors = (errors) => ({ fieldsErrors }) => ({ - fieldsErrors: { - ...fieldsErrors, - ...errors, - }, -}); +export const updateFormErrors = + (errors) => + ({ fieldsErrors }) => ({ + fieldsErrors: { + ...fieldsErrors, + ...errors, + }, + }); export class FollowerIndexForm extends PureComponent { static propTypes = { 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 5a671b29be49..69fb1a54bec1 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 @@ -20,12 +20,14 @@ import { /** * State transitions: fields update */ -export const updateFields = (newValues) => ({ fields }) => ({ - fields: { - ...fields, - ...newValues, - }, -}); +export const updateFields = + (newValues) => + ({ fields }) => ({ + fields: { + ...fields, + ...newValues, + }, + }); export class FormEntryRow extends PureComponent { static propTypes = { 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 09af1071f008..4e173618b119 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 @@ -213,10 +213,8 @@ export class RemoteClustersFormField extends PureComponent { renderCurrentRemoteClusterNotConnected = (name, fatal) => { const { isEditable, currentUrl } = this.props; - const { - remoteClusterNotConnectedEditable, - remoteClusterNotConnectedNotEditable, - } = this.errorMessages; + const { remoteClusterNotConnectedEditable, remoteClusterNotConnectedNotEditable } = + this.errorMessages; const { title, description } = isEditable ? remoteClusterNotConnectedEditable(name) diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/auto_follow_pattern_list.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/auto_follow_pattern_list.js index 3a4273c1ed0e..4d7eb107ea24 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/auto_follow_pattern_list.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/auto_follow_pattern_list.js @@ -50,12 +50,8 @@ export class AutoFollowPatternList extends PureComponent { }; componentDidMount() { - const { - loadAutoFollowPatterns, - loadAutoFollowStats, - selectAutoFollowPattern, - history, - } = this.props; + const { loadAutoFollowPatterns, loadAutoFollowStats, selectAutoFollowPattern, history } = + this.props; trackUiMetric(METRIC_TYPE.LOADED, UIM_AUTO_FOLLOW_PATTERN_LIST_LOAD); loadAutoFollowPatterns(); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/detail_panel/detail_panel.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/detail_panel/detail_panel.js index b32af06807e2..a83da7e08cdf 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/detail_panel/detail_panel.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/detail_panel/detail_panel.js @@ -268,11 +268,8 @@ export class DetailPanel extends Component { return this.renderAutoFollowPatternNotFound(); } - const { - followIndexPatternPrefix, - followIndexPatternSuffix, - leaderIndexPatterns, - } = autoFollowPattern; + const { followIndexPatternPrefix, followIndexPatternSuffix, leaderIndexPatterns } = + autoFollowPattern; let indexManagementFilter; 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 cd09742b1c55..a876e231e861 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 @@ -12,11 +12,8 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { indexPatterns } from '../../../../../../src/plugins/data/public'; import { indices } from '../../shared_imports'; -const { - indexNameBeginsWithPeriod, - findIllegalCharactersInIndexName, - indexNameContainsSpaces, -} = indices; +const { indexNameBeginsWithPeriod, findIllegalCharactersInIndexName, indexNameContainsSpaces } = + indices; export const validateName = (name = '') => { let errorMsg = null; 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 6945d9e37fa2..32379cb9a2cc 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 @@ -28,29 +28,24 @@ export const clearApiError = (scope) => ({ payload: { error: null, scope }, }); -export const sendApiRequest = ({ - label, - scope, - status, - handler, - onSuccess = () => undefined, - onError = () => undefined, -}) => async (dispatch, getState) => { - dispatch(clearApiError(scope)); - dispatch(apiRequestStart({ label, scope, status })); - - try { - const response = await handler(dispatch); - - dispatch(apiRequestEnd({ label, scope })); - dispatch({ type: `${label}_SUCCESS`, payload: response }); - - onSuccess(response, dispatch, getState); - } catch (error) { - dispatch(apiRequestEnd({ label, scope })); - dispatch(setApiError({ error, scope })); - dispatch({ type: `${label}_FAILURE`, payload: error }); - - onError(error, dispatch, getState); - } -}; +export const sendApiRequest = + ({ label, scope, status, handler, onSuccess = () => undefined, onError = () => undefined }) => + async (dispatch, getState) => { + dispatch(clearApiError(scope)); + dispatch(apiRequestStart({ label, scope, status })); + + try { + const response = await handler(dispatch); + + dispatch(apiRequestEnd({ label, scope })); + dispatch({ type: `${label}_SUCCESS`, payload: response }); + + onSuccess(response, dispatch, getState); + } catch (error) { + dispatch(apiRequestEnd({ label, scope })); + dispatch(setApiError({ error, scope })); + dispatch({ type: `${label}_FAILURE`, payload: error }); + + onError(error, dispatch, getState); + } + }; diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/test_lib.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/test_lib.ts index 3a5a31779793..c125d6b4552f 100644 --- a/x-pack/plugins/cross_cluster_replication/server/routes/api/test_lib.ts +++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/test_lib.ts @@ -9,7 +9,7 @@ import { RequestHandlerContext } from 'src/core/server'; import { License } from '../../shared_imports'; export function mockRouteContext(mockedFunctions: unknown): RequestHandlerContext { - const routeContextMock = ({ + const routeContextMock = { core: { elasticsearch: { client: { @@ -17,7 +17,7 @@ export function mockRouteContext(mockedFunctions: unknown): RequestHandlerContex }, }, }, - } as unknown) as RequestHandlerContext; + } as unknown as RequestHandlerContext; return routeContextMock; } diff --git a/x-pack/plugins/dashboard_enhanced/common/drilldowns/dashboard_drilldown/dashboard_drilldown_persistable_state.ts b/x-pack/plugins/dashboard_enhanced/common/drilldowns/dashboard_drilldown/dashboard_drilldown_persistable_state.ts index bb06bf41a31d..04ee451c91c7 100644 --- a/x-pack/plugins/dashboard_enhanced/common/drilldowns/dashboard_drilldown/dashboard_drilldown_persistable_state.ts +++ b/x-pack/plugins/dashboard_enhanced/common/drilldowns/dashboard_drilldown/dashboard_drilldown_persistable_state.ts @@ -65,10 +65,10 @@ export const createExtract = ({ return { state: { ...state, - action: ({ + action: { ...state.action, config: restOfConfig, - } as unknown) as SerializedAction, + } as unknown as SerializedAction, }, references, }; diff --git a/x-pack/plugins/dashboard_enhanced/public/plugin.ts b/x-pack/plugins/dashboard_enhanced/public/plugin.ts index f739287663d1..339269f95e51 100644 --- a/x-pack/plugins/dashboard_enhanced/public/plugin.ts +++ b/x-pack/plugins/dashboard_enhanced/public/plugin.ts @@ -34,7 +34,8 @@ export interface SetupContract {} export interface StartContract {} export class DashboardEnhancedPlugin - implements Plugin { + implements Plugin +{ public readonly drilldowns = new DashboardDrilldownsService(); constructor(protected readonly context: PluginInitializerContext) {} diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/abstract_dashboard_drilldown/abstract_dashboard_drilldown.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/abstract_dashboard_drilldown/abstract_dashboard_drilldown.tsx index 6f02946596a8..96a17bd89439 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/abstract_dashboard_drilldown/abstract_dashboard_drilldown.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/abstract_dashboard_drilldown/abstract_dashboard_drilldown.tsx @@ -32,7 +32,8 @@ export interface Params { } export abstract class AbstractDashboardDrilldown - implements Drilldown { + implements Drilldown +{ constructor(protected readonly params: Params) {} public abstract readonly id: string; diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_create_drilldown/flyout_create_drilldown.test.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_create_drilldown/flyout_create_drilldown.test.tsx index bd46724a7793..572eca97d611 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_create_drilldown/flyout_create_drilldown.test.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_create_drilldown/flyout_create_drilldown.test.tsx @@ -72,9 +72,9 @@ describe('isCompatible', () => { expectedResult: boolean = true ): Promise { uiActionsEnhanced.getActionFactories.mockImplementation(() => [ - ({ + { supportedTriggers: () => actionFactoriesTriggers, - } as unknown) as UiActionsEnhancedActionFactory, + } as unknown as UiActionsEnhancedActionFactory, ]); let embeddable = new MockEmbeddable( diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_edit_drilldown/menu_item.test.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_edit_drilldown/menu_item.test.tsx index 11c236498080..5c03d90212ff 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_edit_drilldown/menu_item.test.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_edit_drilldown/menu_item.test.tsx @@ -17,11 +17,11 @@ test('', () => { const { getByText, queryByText } = render( diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/embeddable_to_dashboard_drilldown/embeddable_to_dashboard_drilldown.test.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/embeddable_to_dashboard_drilldown/embeddable_to_dashboard_drilldown.test.tsx index 3272a6e27de2..d24ed9b35242 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/embeddable_to_dashboard_drilldown/embeddable_to_dashboard_drilldown.test.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/embeddable_to_dashboard_drilldown/embeddable_to_dashboard_drilldown.test.tsx @@ -90,7 +90,7 @@ describe('.execute() & getHref', () => { }); const getLocationSpy = jest.spyOn(definition, 'getLocation'); const drilldown = new EmbeddableToDashboardDrilldown({ - start: ((() => ({ + start: (() => ({ core: { application: { navigateToApp, @@ -111,7 +111,7 @@ describe('.execute() & getHref', () => { }, }, self: {}, - })) as unknown) as StartServicesGetter< + })) as unknown as StartServicesGetter< Pick >, }); @@ -123,7 +123,7 @@ describe('.execute() & getHref', () => { ...config, }; - const context = ({ + const context = { filters: filtersFromEvent, embeddable: { getInput: () => ({ @@ -134,7 +134,7 @@ describe('.execute() & getHref', () => { }), }, timeFieldName, - } as unknown) as ApplyGlobalFilterActionContext & EnhancedEmbeddableContext; + } as unknown as ApplyGlobalFilterActionContext & EnhancedEmbeddableContext; await drilldown.execute(completeConfig, context); diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/embeddable_to_dashboard_drilldown/embeddable_to_dashboard_drilldown.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/embeddable_to_dashboard_drilldown/embeddable_to_dashboard_drilldown.tsx index 97355d9eb435..97b66e1b7de3 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/embeddable_to_dashboard_drilldown/embeddable_to_dashboard_drilldown.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/embeddable_to_dashboard_drilldown/embeddable_to_dashboard_drilldown.tsx @@ -73,10 +73,8 @@ export class EmbeddableToDashboardDrilldown extends AbstractDashboardDrilldown esFilters.isFilterPinned(f)); } - const { - restOfFilters: filtersFromEvent, - timeRange: timeRangeFromEvent, - } = esFilters.extractTimeRange(context.filters, context.timeFieldName); + const { restOfFilters: filtersFromEvent, timeRange: timeRangeFromEvent } = + esFilters.extractTimeRange(context.filters, context.timeFieldName); if (filtersFromEvent) { params.filters = [...(params.filters ?? []), ...filtersFromEvent]; diff --git a/x-pack/plugins/dashboard_enhanced/server/plugin.ts b/x-pack/plugins/dashboard_enhanced/server/plugin.ts index 10f128fc9bff..89d4d70a1f6f 100644 --- a/x-pack/plugins/dashboard_enhanced/server/plugin.ts +++ b/x-pack/plugins/dashboard_enhanced/server/plugin.ts @@ -24,7 +24,8 @@ export interface SetupContract {} export interface StartContract {} export class DashboardEnhancedPlugin - implements Plugin { + implements Plugin +{ constructor(protected readonly context: PluginInitializerContext) {} public setup(core: CoreSetup, plugins: SetupDependencies): SetupContract { diff --git a/x-pack/plugins/dashboard_mode/server/interceptors/dashboard_mode_request_interceptor.test.ts b/x-pack/plugins/dashboard_mode/server/interceptors/dashboard_mode_request_interceptor.test.ts index e2e2c8c00567..4cc3413720e7 100644 --- a/x-pack/plugins/dashboard_mode/server/interceptors/dashboard_mode_request_interceptor.test.ts +++ b/x-pack/plugins/dashboard_mode/server/interceptors/dashboard_mode_request_interceptor.test.ts @@ -38,18 +38,18 @@ describe('DashboardOnlyModeRequestInterceptor', () => { http: core.http, security, getUiSettingsClient: () => - (Promise.resolve({ + Promise.resolve({ get: () => Promise.resolve(uiSettingsMock), - }) as unknown) as Promise, + }) as unknown as Promise, }); }); test('should not redirects for not app/* requests', async () => { - const request = ({ + const request = { url: { pathname: 'api/test', }, - } as unknown) as KibanaRequest; + } as unknown as KibanaRequest; interceptor(request, {} as LifecycleResponseFactory, toolkit); @@ -57,11 +57,11 @@ describe('DashboardOnlyModeRequestInterceptor', () => { }); test('should not redirects not authenticated users', async () => { - const request = ({ + const request = { url: { pathname: '/app/home', }, - } as unknown) as KibanaRequest; + } as unknown as KibanaRequest; interceptor(request, {} as LifecycleResponseFactory, toolkit); @@ -73,22 +73,22 @@ describe('DashboardOnlyModeRequestInterceptor', () => { describe(`requests to url:"${url}"`, () => { test('redirects to the dashboard_mode app instead', async () => { const { pathname, search, hash } = parseUrl(url); - const request = ({ + const request = { url: { pathname, search, hash }, credentials: { roles: [DASHBOARD_ONLY_MODE_ROLE], }, - } as unknown) as KibanaRequest; + } as unknown as KibanaRequest; - const response = ({ + const response = { redirected: jest.fn(), - } as unknown) as LifecycleResponseFactory; + } as unknown as LifecycleResponseFactory; security.authc.getCurrentUser = jest.fn( (r: KibanaRequest) => - (({ + ({ roles: [DASHBOARD_ONLY_MODE_ROLE], - } as unknown) as AuthenticatedUser) + } as unknown as AuthenticatedUser) ); uiSettingsMock = [DASHBOARD_ONLY_MODE_ROLE]; diff --git a/x-pack/plugins/data_enhanced/public/plugin.ts b/x-pack/plugins/data_enhanced/public/plugin.ts index a222f7c734a1..f26c1e8d0b62 100644 --- a/x-pack/plugins/data_enhanced/public/plugin.ts +++ b/x-pack/plugins/data_enhanced/public/plugin.ts @@ -37,7 +37,8 @@ export type DataEnhancedSetup = ReturnType; export type DataEnhancedStart = ReturnType; export class DataEnhancedPlugin - implements Plugin { + implements Plugin +{ private config!: ConfigSchema; private readonly storage = new Storage(window.localStorage); private usageCollector?: SearchUsageCollector; diff --git a/x-pack/plugins/data_enhanced/public/search/sessions_mgmt/__mocks__/index.tsx b/x-pack/plugins/data_enhanced/public/search/sessions_mgmt/__mocks__/index.tsx index d52ca5b45613..af0a1a583e44 100644 --- a/x-pack/plugins/data_enhanced/public/search/sessions_mgmt/__mocks__/index.tsx +++ b/x-pack/plugins/data_enhanced/public/search/sessions_mgmt/__mocks__/index.tsx @@ -14,6 +14,6 @@ export function LocaleWrapper({ children }: { children?: ReactNode }) { return {children}; } -export const mockUrls = ({ +export const mockUrls = { getUrlGenerator: (id: string) => ({ createUrl: () => `hello-cool-${id}-url` }), -} as unknown) as UrlGeneratorsStart; +} as unknown as UrlGeneratorsStart; diff --git a/x-pack/plugins/data_enhanced/public/search/sessions_mgmt/lib/api.ts b/x-pack/plugins/data_enhanced/public/search/sessions_mgmt/lib/api.ts index eb38d47c26ff..01b64dcaf8a8 100644 --- a/x-pack/plugins/data_enhanced/public/search/sessions_mgmt/lib/api.ts +++ b/x-pack/plugins/data_enhanced/public/search/sessions_mgmt/lib/api.ts @@ -79,46 +79,48 @@ async function getUrlFromState( } // Helper: factory for a function to map server objects to UI objects -const mapToUISession = (urls: UrlGeneratorsStart, config: SessionsConfigSchema) => async ( - savedObject: SavedObject -): Promise => { - const { - name, - appId, - created, - expires, - urlGeneratorId, - initialState, - restoreState, - idMapping, - version, - } = savedObject.attributes; +const mapToUISession = + (urls: UrlGeneratorsStart, config: SessionsConfigSchema) => + async ( + savedObject: SavedObject + ): Promise => { + const { + name, + appId, + created, + expires, + urlGeneratorId, + initialState, + restoreState, + idMapping, + version, + } = savedObject.attributes; - const status = getUIStatus(savedObject.attributes); - const actions = getActions(status); + const status = getUIStatus(savedObject.attributes); + const actions = getActions(status); - // TODO: initialState should be saved without the searchSessionID - if (initialState) delete initialState.searchSessionId; - // derive the URL and add it in - const reloadUrl = await getUrlFromState(urls, urlGeneratorId, initialState); - const restoreUrl = await getUrlFromState(urls, urlGeneratorId, restoreState); + // TODO: initialState should be saved without the searchSessionID + if (initialState) delete initialState.searchSessionId; + // derive the URL and add it in + const reloadUrl = await getUrlFromState(urls, urlGeneratorId, initialState); + const restoreUrl = await getUrlFromState(urls, urlGeneratorId, restoreState); - return { - id: savedObject.id, - name, - appId, - created, - expires, - status, - actions, - restoreUrl, - reloadUrl, - initialState, - restoreState, - numSearches: Object.keys(idMapping).length, - version, + return { + id: savedObject.id, + name, + appId, + created, + expires, + status, + actions, + restoreUrl, + reloadUrl, + initialState, + restoreState, + numSearches: Object.keys(idMapping).length, + version, + }; }; -}; interface SearchSessionManagementDeps { urls: UrlGeneratorsStart; diff --git a/x-pack/plugins/data_enhanced/public/search/ui/connected_search_session_indicator/connected_search_session_indicator.tsx b/x-pack/plugins/data_enhanced/public/search/ui/connected_search_session_indicator/connected_search_session_indicator.tsx index 603df09e1c4c..eed85a9d84ba 100644 --- a/x-pack/plugins/data_enhanced/public/search/ui/connected_search_session_indicator/connected_search_session_indicator.tsx +++ b/x-pack/plugins/data_enhanced/public/search/ui/connected_search_session_indicator/connected_search_session_indicator.tsx @@ -67,10 +67,8 @@ export const createConnectedSearchSessionIndicator = ({ disableSaveAfterSessionCompleteTimedOut$, false ); - const [ - searchSessionIndicator, - setSearchSessionIndicator, - ] = useState(null); + const [searchSessionIndicator, setSearchSessionIndicator] = + useState(null); const searchSessionIndicatorRef = useCallback((ref: SearchSessionIndicatorRef) => { if (ref !== null) { setSearchSessionIndicator(ref); diff --git a/x-pack/plugins/data_enhanced/server/plugin.ts b/x-pack/plugins/data_enhanced/server/plugin.ts index ce98cf06a9df..60a5de6323f5 100644 --- a/x-pack/plugins/data_enhanced/server/plugin.ts +++ b/x-pack/plugins/data_enhanced/server/plugin.ts @@ -18,7 +18,8 @@ import { registerUsageCollector } from './collectors'; import { SearchSessionService } from './search'; export class EnhancedDataServerPlugin - implements Plugin { + implements Plugin +{ private readonly logger: Logger; private sessionService!: SearchSessionService; private config: ConfigSchema; diff --git a/x-pack/plugins/data_enhanced/server/routes/session.ts b/x-pack/plugins/data_enhanced/server/routes/session.ts index 0b786f44454a..3e293aa82dc8 100644 --- a/x-pack/plugins/data_enhanced/server/routes/session.ts +++ b/x-pack/plugins/data_enhanced/server/routes/session.ts @@ -32,15 +32,8 @@ export function registerSessionRoutes(router: DataEnhancedPluginRouter, logger: }, }, async (context, request, res) => { - const { - sessionId, - name, - expires, - initialState, - restoreState, - appId, - urlGeneratorId, - } = request.body; + const { sessionId, name, expires, initialState, restoreState, appId, urlGeneratorId } = + request.body; try { const response = await context.search!.saveSession(sessionId, { diff --git a/x-pack/plugins/data_enhanced/server/saved_objects/search_session_migration.test.ts b/x-pack/plugins/data_enhanced/server/saved_objects/search_session_migration.test.ts index a04a7a4d3302..cdb86772482f 100644 --- a/x-pack/plugins/data_enhanced/server/saved_objects/search_session_migration.test.ts +++ b/x-pack/plugins/data_enhanced/server/saved_objects/search_session_migration.test.ts @@ -15,51 +15,53 @@ import { SEARCH_SESSION_TYPE, SearchSessionStatus } from '../../../../../src/plu import { SavedObjectMigrationContext } from 'kibana/server'; describe('7.12.0 -> 7.13.0', () => { - const mockCompletedSessionSavedObject: SavedObject = { - id: 'id', - type: SEARCH_SESSION_TYPE, - attributes: { - name: 'my_name', - appId: 'my_app_id', - sessionId: 'sessionId', - urlGeneratorId: 'my_url_generator_id', - initialState: {}, - restoreState: {}, - persisted: true, - idMapping: {}, - realmType: 'realmType', - realmName: 'realmName', - username: 'username', - created: '2021-03-26T00:00:00.000Z', - expires: '2021-03-30T00:00:00.000Z', - touched: '2021-03-29T00:00:00.000Z', - status: SearchSessionStatus.COMPLETE, - }, - references: [], - }; + const mockCompletedSessionSavedObject: SavedObject = + { + id: 'id', + type: SEARCH_SESSION_TYPE, + attributes: { + name: 'my_name', + appId: 'my_app_id', + sessionId: 'sessionId', + urlGeneratorId: 'my_url_generator_id', + initialState: {}, + restoreState: {}, + persisted: true, + idMapping: {}, + realmType: 'realmType', + realmName: 'realmName', + username: 'username', + created: '2021-03-26T00:00:00.000Z', + expires: '2021-03-30T00:00:00.000Z', + touched: '2021-03-29T00:00:00.000Z', + status: SearchSessionStatus.COMPLETE, + }, + references: [], + }; - const mockInProgressSessionSavedObject: SavedObject = { - id: 'id', - type: SEARCH_SESSION_TYPE, - attributes: { - name: 'my_name', - appId: 'my_app_id', - sessionId: 'sessionId', - urlGeneratorId: 'my_url_generator_id', - initialState: {}, - restoreState: {}, - persisted: true, - idMapping: {}, - realmType: 'realmType', - realmName: 'realmName', - username: 'username', - created: '2021-03-26T00:00:00.000Z', - expires: '2021-03-30T00:00:00.000Z', - touched: '2021-03-29T00:00:00.000Z', - status: SearchSessionStatus.IN_PROGRESS, - }, - references: [], - }; + const mockInProgressSessionSavedObject: SavedObject = + { + id: 'id', + type: SEARCH_SESSION_TYPE, + attributes: { + name: 'my_name', + appId: 'my_app_id', + sessionId: 'sessionId', + urlGeneratorId: 'my_url_generator_id', + initialState: {}, + restoreState: {}, + persisted: true, + idMapping: {}, + realmType: 'realmType', + realmName: 'realmName', + username: 'username', + created: '2021-03-26T00:00:00.000Z', + expires: '2021-03-30T00:00:00.000Z', + touched: '2021-03-29T00:00:00.000Z', + status: SearchSessionStatus.IN_PROGRESS, + }, + references: [], + }; const migration = searchSessionSavedObjectMigrations['7.13.0']; test('"completed" is populated from "touched" for completed session', () => { diff --git a/x-pack/plugins/data_enhanced/server/search/session/session_service.ts b/x-pack/plugins/data_enhanced/server/search/session/session_service.ts index 9aff99d6f9a3..75f404d0f879 100644 --- a/x-pack/plugins/data_enhanced/server/search/session/session_service.ts +++ b/x-pack/plugins/data_enhanced/server/search/session/session_service.ts @@ -90,7 +90,8 @@ function sleep(ms: number) { return new Promise((r) => setTimeout(r, ms)); } export class SearchSessionService - implements ISearchSessionService { + implements ISearchSessionService +{ private sessionConfig: SearchSessionsConfig; private readonly updateOrCreateBatchQueue: UpdateOrCreateQueueEntry[] = []; diff --git a/x-pack/plugins/data_visualizer/public/application/common/components/fields_stats_grid/fields_stats_grid.tsx b/x-pack/plugins/data_visualizer/public/application/common/components/fields_stats_grid/fields_stats_grid.tsx index f1c164768d6e..8e59345c9bd6 100644 --- a/x-pack/plugins/data_visualizer/public/application/common/components/fields_stats_grid/fields_stats_grid.tsx +++ b/x-pack/plugins/data_visualizer/public/application/common/components/fields_stats_grid/fields_stats_grid.tsx @@ -49,9 +49,8 @@ function getItemIdToExpandedRowMap( export const FieldsStatsGrid: FC = ({ results }) => { const restorableDefaults = getDefaultDataVisualizerListState(); - const [dataVisualizerListState, setDataVisualizerListState] = useState( - restorableDefaults - ); + const [dataVisualizerListState, setDataVisualizerListState] = + useState(restorableDefaults); const visibleFieldTypes = dataVisualizerListState.visibleFieldTypes ?? restorableDefaults.visibleFieldTypes; diff --git a/x-pack/plugins/data_visualizer/public/application/common/components/top_values/top_values.tsx b/x-pack/plugins/data_visualizer/public/application/common/components/top_values/top_values.tsx index 7a20b054462a..a019f7fb0976 100644 --- a/x-pack/plugins/data_visualizer/public/application/common/components/top_values/top_values.tsx +++ b/x-pack/plugins/data_visualizer/public/application/common/components/top_values/top_values.tsx @@ -40,13 +40,8 @@ function getPercentLabel(docCount: number, topValuesSampleSize: number): string export const TopValues: FC = ({ stats, fieldFormat, barColor, compressed }) => { if (stats === undefined) return null; - const { - topValues, - topValuesSampleSize, - topValuesSamplerShardSize, - count, - isTopValuesSampled, - } = stats; + const { topValues, topValuesSampleSize, topValuesSamplerShardSize, count, isTopValuesSampled } = + stats; const progressBarMax = isTopValuesSampled === true ? topValuesSampleSize : count; return ( diff --git a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/edit_flyout/edit_flyout.js b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/edit_flyout/edit_flyout.js index cc6f5c45b310..7ffaf7a4e216 100644 --- a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/edit_flyout/edit_flyout.js +++ b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/edit_flyout/edit_flyout.js @@ -48,14 +48,8 @@ export class EditFlyout extends Component { }; render() { - const { - isFlyoutVisible, - closeEditFlyout, - setOverrides, - overrides, - originalSettings, - fields, - } = this.props; + const { isFlyoutVisible, closeEditFlyout, setOverrides, overrides, originalSettings, fields } = + this.props; return ( diff --git a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/index_data_visualizer_view/index_data_visualizer_view.tsx b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/index_data_visualizer_view/index_data_visualizer_view.tsx index a8adbfad3d44..0eb8e6363d60 100644 --- a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/index_data_visualizer_view/index_data_visualizer_view.tsx +++ b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/index_data_visualizer_view/index_data_visualizer_view.tsx @@ -103,21 +103,22 @@ function getDefaultPageState(): DataVisualizerPageState { documentCountStats: undefined, }; } -export const getDefaultDataVisualizerListState = (): Required => ({ - pageIndex: 0, - pageSize: 10, - sortField: 'fieldName', - sortDirection: 'asc', - visibleFieldTypes: [], - visibleFieldNames: [], - samplerShardSize: 5000, - searchString: '', - searchQuery: defaultSearchQuery, - searchQueryLanguage: SEARCH_QUERY_LANGUAGE.KUERY, - showDistributions: true, - showAllFields: false, - showEmptyFields: false, -}); +export const getDefaultDataVisualizerListState = + (): Required => ({ + pageIndex: 0, + pageSize: 10, + sortField: 'fieldName', + sortDirection: 'asc', + visibleFieldTypes: [], + visibleFieldNames: [], + samplerShardSize: 5000, + searchString: '', + searchQuery: defaultSearchQuery, + searchQueryLanguage: SEARCH_QUERY_LANGUAGE.KUERY, + showDistributions: true, + showAllFields: false, + showEmptyFields: false, + }); export interface IndexDataVisualizerViewProps { currentIndexPattern: IndexPattern; @@ -163,10 +164,10 @@ export const IndexDataVisualizerView: FC = (dataVi autoRefreshSelector: true, }); - const dataLoader = useMemo(() => new DataLoader(currentIndexPattern, toasts), [ - currentIndexPattern, - toasts, - ]); + const dataLoader = useMemo( + () => new DataLoader(currentIndexPattern, toasts), + [currentIndexPattern, toasts] + ); useEffect(() => { if (globalState?.time !== undefined) { diff --git a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/index_pattern_management/index_pattern_management.tsx b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/index_pattern_management/index_pattern_management.tsx index 3cec1141a4d3..38f6a66a5ef2 100644 --- a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/index_pattern_management/index_pattern_management.tsx +++ b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/index_pattern_management/index_pattern_management.tsx @@ -31,7 +31,8 @@ export function DataVisualizerIndexPatternManagement( } = useDataVisualizerKibana(); const { useNewFieldsApi, currentIndexPattern } = props; - const indexPatternFieldEditPermission = indexPatternFieldEditor?.userPermissions.editIndexPattern(); + const indexPatternFieldEditPermission = + indexPatternFieldEditor?.userPermissions.editIndexPattern(); const canEditIndexPatternField = !!indexPatternFieldEditPermission && useNewFieldsApi; const [isAddIndexPatternFieldPopoverOpen, setIsAddIndexPatternFieldPopoverOpen] = useState(false); diff --git a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/index_data_visualizer.tsx b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/index_data_visualizer.tsx index 9a8987967fe6..f9748da51a22 100644 --- a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/index_data_visualizer.tsx +++ b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/index_data_visualizer.tsx @@ -39,159 +39,150 @@ export interface DataVisualizerUrlStateContextProviderProps { additionalLinks: ResultLink[]; } -export const DataVisualizerUrlStateContextProvider: FC = ({ - IndexDataVisualizerComponent, - additionalLinks, -}) => { - const { - services: { - data: { indexPatterns }, - savedObjects: { client: savedObjectsClient }, - notifications: { toasts }, - }, - } = useDataVisualizerKibana(); - const history = useHistory(); - - const [currentIndexPattern, setCurrentIndexPattern] = useState( - undefined - ); - const [currentSavedSearch, setCurrentSavedSearch] = useState | null>( - null - ); - const { search: searchString } = useLocation(); - - useEffect(() => { - const prevSearchString = searchString; - const parsedQueryString = parse(prevSearchString, { sort: false }); +export const DataVisualizerUrlStateContextProvider: FC = + ({ IndexDataVisualizerComponent, additionalLinks }) => { + const { + services: { + data: { indexPatterns }, + savedObjects: { client: savedObjectsClient }, + notifications: { toasts }, + }, + } = useDataVisualizerKibana(); + const history = useHistory(); + + const [currentIndexPattern, setCurrentIndexPattern] = useState( + undefined + ); + const [currentSavedSearch, setCurrentSavedSearch] = useState | null>( + null + ); + const { search: searchString } = useLocation(); + + useEffect(() => { + const prevSearchString = searchString; + const parsedQueryString = parse(prevSearchString, { sort: false }); - const getIndexPattern = async () => { - if (typeof parsedQueryString?.savedSearchId === 'string') { - const savedSearchId = parsedQueryString.savedSearchId; - try { - const savedSearch = await savedObjectsClient.get('search', savedSearchId); - const indexPatternId = savedSearch.references.find((ref) => ref.type === 'index-pattern') - ?.id; - if (indexPatternId !== undefined && savedSearch) { - try { - const indexPattern = await indexPatterns.get(indexPatternId); - setCurrentSavedSearch(savedSearch); - setCurrentIndexPattern(indexPattern); - } catch (e) { - toasts.addError(e, { - title: i18n.translate('xpack.dataVisualizer.index.indexPatternErrorMessage', { - defaultMessage: 'Error finding index pattern', - }), - }); + const getIndexPattern = async () => { + if (typeof parsedQueryString?.savedSearchId === 'string') { + const savedSearchId = parsedQueryString.savedSearchId; + try { + const savedSearch = await savedObjectsClient.get('search', savedSearchId); + const indexPatternId = savedSearch.references.find( + (ref) => ref.type === 'index-pattern' + )?.id; + if (indexPatternId !== undefined && savedSearch) { + try { + const indexPattern = await indexPatterns.get(indexPatternId); + setCurrentSavedSearch(savedSearch); + setCurrentIndexPattern(indexPattern); + } catch (e) { + toasts.addError(e, { + title: i18n.translate('xpack.dataVisualizer.index.indexPatternErrorMessage', { + defaultMessage: 'Error finding index pattern', + }), + }); + } } + } catch (e) { + toasts.addError(e, { + title: i18n.translate('xpack.dataVisualizer.index.savedSearchErrorMessage', { + defaultMessage: 'Error retrieving saved search {savedSearchId}', + values: { savedSearchId }, + }), + }); } - } catch (e) { - toasts.addError(e, { - title: i18n.translate('xpack.dataVisualizer.index.savedSearchErrorMessage', { - defaultMessage: 'Error retrieving saved search {savedSearchId}', - values: { savedSearchId }, - }), - }); } - } - - if (typeof parsedQueryString?.index === 'string') { - const indexPattern = await indexPatterns.get(parsedQueryString.index); - setCurrentIndexPattern(indexPattern); - } - }; - getIndexPattern(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [savedObjectsClient, toasts, indexPatterns]); - - const setUrlState: SetUrlState = useCallback( - ( - accessor: Accessor, - attribute: string | Dictionary, - value?: any, - replaceState?: boolean - ) => { - const prevSearchString = searchString; - const urlState = parseUrlState(prevSearchString); - const parsedQueryString = parse(prevSearchString, { sort: false }); - - if (!Object.prototype.hasOwnProperty.call(urlState, accessor)) { - urlState[accessor] = {}; - } - if (typeof attribute === 'string') { - if (isEqual(getNestedProperty(urlState, `${accessor}.${attribute}`), value)) { - return prevSearchString; + if (typeof parsedQueryString?.index === 'string') { + const indexPattern = await indexPatterns.get(parsedQueryString.index); + setCurrentIndexPattern(indexPattern); + } + }; + getIndexPattern(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [savedObjectsClient, toasts, indexPatterns]); + + const setUrlState: SetUrlState = useCallback( + ( + accessor: Accessor, + attribute: string | Dictionary, + value?: any, + replaceState?: boolean + ) => { + const prevSearchString = searchString; + const urlState = parseUrlState(prevSearchString); + const parsedQueryString = parse(prevSearchString, { sort: false }); + + if (!Object.prototype.hasOwnProperty.call(urlState, accessor)) { + urlState[accessor] = {}; } - urlState[accessor][attribute] = value; - } else { - const attributes = attribute; - Object.keys(attributes).forEach((a) => { - urlState[accessor][a] = attributes[a]; - }); - } - - try { - const oldLocationSearchString = stringify(parsedQueryString, { - sort: false, - encode: false, - }); - - Object.keys(urlState).forEach((a) => { - if (isRisonSerializationRequired(a)) { - parsedQueryString[a] = encode(urlState[a]); - } else { - parsedQueryString[a] = urlState[a]; - } - }); - const newLocationSearchString = stringify(parsedQueryString, { - sort: false, - encode: false, - }); - - if (oldLocationSearchString !== newLocationSearchString) { - const newSearchString = stringify(parsedQueryString, { sort: false }); - if (replaceState) { - history.replace({ search: newSearchString }); - } else { - history.push({ search: newSearchString }); + if (typeof attribute === 'string') { + if (isEqual(getNestedProperty(urlState, `${accessor}.${attribute}`), value)) { + return prevSearchString; } + + urlState[accessor][attribute] = value; + } else { + const attributes = attribute; + Object.keys(attributes).forEach((a) => { + urlState[accessor][a] = attributes[a]; + }); } - } catch (error) { - // eslint-disable-next-line no-console - console.error('Could not save url state', error); - } - }, - [history, searchString] - ); - return ( - - {currentIndexPattern ? ( - - ) : ( -
- )} - - ); -}; + try { + const oldLocationSearchString = stringify(parsedQueryString, { + sort: false, + encode: false, + }); + + Object.keys(urlState).forEach((a) => { + if (isRisonSerializationRequired(a)) { + parsedQueryString[a] = encode(urlState[a]); + } else { + parsedQueryString[a] = urlState[a]; + } + }); + const newLocationSearchString = stringify(parsedQueryString, { + sort: false, + encode: false, + }); + + if (oldLocationSearchString !== newLocationSearchString) { + const newSearchString = stringify(parsedQueryString, { sort: false }); + if (replaceState) { + history.replace({ search: newSearchString }); + } else { + history.push({ search: newSearchString }); + } + } + } catch (error) { + // eslint-disable-next-line no-console + console.error('Could not save url state', error); + } + }, + [history, searchString] + ); + + return ( + + {currentIndexPattern ? ( + + ) : ( +
+ )} + + ); + }; export const IndexDataVisualizer: FC<{ additionalLinks: ResultLink[] }> = ({ additionalLinks }) => { const coreStart = getCoreStart(); - const { - data, - maps, - embeddable, - share, - security, - fileUpload, - lens, - indexPatternFieldEditor, - } = getPluginsStart(); + const { data, maps, embeddable, share, security, fileUpload, lens, indexPatternFieldEditor } = + getPluginsStart(); const services = { data, maps, diff --git a/x-pack/plugins/data_visualizer/public/plugin.ts b/x-pack/plugins/data_visualizer/public/plugin.ts index 4b71b08e9cf2..54f27a2e9d72 100644 --- a/x-pack/plugins/data_visualizer/public/plugin.ts +++ b/x-pack/plugins/data_visualizer/public/plugin.ts @@ -46,7 +46,8 @@ export class DataVisualizerPlugin DataVisualizerPluginStart, DataVisualizerSetupDependencies, DataVisualizerStartDependencies - > { + > +{ public setup(core: CoreSetup, plugins: DataVisualizerSetupDependencies) { if (plugins.home) { registerHomeAddData(plugins.home); diff --git a/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_histogram_for_fields.ts b/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_histogram_for_fields.ts index b8f6e2f53818..6621c793c001 100644 --- a/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_histogram_for_fields.ts +++ b/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_histogram_for_fields.ts @@ -143,46 +143,44 @@ export const getHistogramsForFields = async ( const aggsPath = getSamplerAggregationsResponsePath(samplerShardSize); const aggregations = aggsPath.length > 0 ? get(body.aggregations, aggsPath) : body.aggregations; - const chartsData: ChartData[] = fields.map( - (field): ChartData => { - const fieldName = field.fieldName; - const fieldType = field.type; - const id = stringHash(field.fieldName); - - if (fieldType === KBN_FIELD_TYPES.NUMBER || fieldType === KBN_FIELD_TYPES.DATE) { - if (aggIntervals[id] === undefined) { - return { - type: 'numeric', - data: [], - interval: 0, - stats: [0, 0], - id: fieldName, - }; - } + const chartsData: ChartData[] = fields.map((field): ChartData => { + const fieldName = field.fieldName; + const fieldType = field.type; + const id = stringHash(field.fieldName); + if (fieldType === KBN_FIELD_TYPES.NUMBER || fieldType === KBN_FIELD_TYPES.DATE) { + if (aggIntervals[id] === undefined) { return { - data: aggregations[`${id}_histogram`].buckets, - interval: aggIntervals[id].interval, - stats: [aggIntervals[id].min, aggIntervals[id].max], type: 'numeric', - id: fieldName, - }; - } else if (fieldType === KBN_FIELD_TYPES.STRING || fieldType === KBN_FIELD_TYPES.BOOLEAN) { - return { - type: fieldType === KBN_FIELD_TYPES.STRING ? 'ordinal' : 'boolean', - cardinality: - fieldType === KBN_FIELD_TYPES.STRING ? aggregations[`${id}_cardinality`].value : 2, - data: aggregations[`${id}_terms`].buckets, + data: [], + interval: 0, + stats: [0, 0], id: fieldName, }; } return { - type: 'unsupported', + data: aggregations[`${id}_histogram`].buckets, + interval: aggIntervals[id].interval, + stats: [aggIntervals[id].min, aggIntervals[id].max], + type: 'numeric', + id: fieldName, + }; + } else if (fieldType === KBN_FIELD_TYPES.STRING || fieldType === KBN_FIELD_TYPES.BOOLEAN) { + return { + type: fieldType === KBN_FIELD_TYPES.STRING ? 'ordinal' : 'boolean', + cardinality: + fieldType === KBN_FIELD_TYPES.STRING ? aggregations[`${id}_cardinality`].value : 2, + data: aggregations[`${id}_terms`].buckets, id: fieldName, }; } - ); + + return { + type: 'unsupported', + id: fieldName, + }; + }); return chartsData; }; diff --git a/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_chart_action.test.ts b/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_chart_action.test.ts index 0742c3999dbc..1af87eccf398 100644 --- a/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_chart_action.test.ts +++ b/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_chart_action.test.ts @@ -19,7 +19,7 @@ import { Filter, RangeFilter } from '../../../../../../src/plugins/data/public'; import { DiscoverAppLocator } from '../../../../../../src/plugins/discover/public'; import { sharePluginMock } from '../../../../../../src/plugins/share/public/mocks'; -const i18nTranslateSpy = (i18n.translate as unknown) as jest.SpyInstance; +const i18nTranslateSpy = i18n.translate as unknown as jest.SpyInstance; jest.mock('@kbn/i18n', () => ({ i18n: { @@ -88,11 +88,11 @@ const setup = ( ], }; - const embeddable: VisualizeEmbeddableContract = ({ + const embeddable: VisualizeEmbeddableContract = { type: VISUALIZE_EMBEDDABLE_TYPE, getInput: () => input, getOutput: () => output, - } as unknown) as VisualizeEmbeddableContract; + } as unknown as VisualizeEmbeddableContract; const context = { filters, diff --git a/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_chart_action.ts b/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_chart_action.ts index 7b59a4e51d04..4ab9146a06c5 100644 --- a/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_chart_action.ts +++ b/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_chart_action.ts @@ -31,7 +31,8 @@ export const ACTION_EXPLORE_DATA_CHART = 'ACTION_EXPLORE_DATA_CHART'; */ export class ExploreDataChartAction extends AbstractExploreDataAction - implements Action { + implements Action +{ public readonly id = ACTION_EXPLORE_DATA_CHART; public readonly type = ACTION_EXPLORE_DATA_CHART; diff --git a/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_context_menu_action.test.ts b/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_context_menu_action.test.ts index 9f0aa0bc32be..77158b0d5cb6 100644 --- a/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_context_menu_action.test.ts +++ b/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_context_menu_action.test.ts @@ -17,7 +17,7 @@ import { ViewMode } from '../../../../../../src/plugins/embeddable/public'; import { DiscoverAppLocator } from '../../../../../../src/plugins/discover/public'; import { sharePluginMock } from '../../../../../../src/plugins/share/public/mocks'; -const i18nTranslateSpy = (i18n.translate as unknown) as jest.SpyInstance; +const i18nTranslateSpy = i18n.translate as unknown as jest.SpyInstance; jest.mock('@kbn/i18n', () => ({ i18n: { @@ -74,11 +74,11 @@ const setup = ({ dashboardOnlyMode = false }: { dashboardOnlyMode?: boolean } = ], }; - const embeddable: VisualizeEmbeddableContract = ({ + const embeddable: VisualizeEmbeddableContract = { type: VISUALIZE_EMBEDDABLE_TYPE, getInput: () => input, getOutput: () => output, - } as unknown) as VisualizeEmbeddableContract; + } as unknown as VisualizeEmbeddableContract; const context = { embeddable, diff --git a/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_context_menu_action.ts b/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_context_menu_action.ts index 88c093a299cb..3580a3f191e6 100644 --- a/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_context_menu_action.ts +++ b/x-pack/plugins/discover_enhanced/public/actions/explore_data/explore_data_context_menu_action.ts @@ -33,7 +33,8 @@ export const ACTION_EXPLORE_DATA = 'ACTION_EXPLORE_DATA'; */ export class ExploreDataContextMenuAction extends AbstractExploreDataAction - implements Action { + implements Action +{ public readonly id = ACTION_EXPLORE_DATA; public readonly type = ACTION_EXPLORE_DATA; diff --git a/x-pack/plugins/discover_enhanced/public/plugin.ts b/x-pack/plugins/discover_enhanced/public/plugin.ts index 60f242d682ff..3b437ead81d7 100644 --- a/x-pack/plugins/discover_enhanced/public/plugin.ts +++ b/x-pack/plugins/discover_enhanced/public/plugin.ts @@ -39,7 +39,8 @@ export interface DiscoverEnhancedStartDependencies { export class DiscoverEnhancedPlugin implements - Plugin { + Plugin +{ public readonly config: Config; constructor(protected readonly context: PluginInitializerContext) { diff --git a/x-pack/plugins/discover_enhanced/server/plugin.ts b/x-pack/plugins/discover_enhanced/server/plugin.ts index 81b629523483..d5dd32791dcd 100644 --- a/x-pack/plugins/discover_enhanced/server/plugin.ts +++ b/x-pack/plugins/discover_enhanced/server/plugin.ts @@ -25,7 +25,8 @@ interface StartDependencies { } export class DiscoverEnhancedPlugin - implements Plugin { + implements Plugin +{ private config$: Observable; constructor(protected readonly context: PluginInitializerContext) { diff --git a/x-pack/plugins/drilldowns/url_drilldown/public/lib/url_drilldown.test.ts b/x-pack/plugins/drilldowns/url_drilldown/public/lib/url_drilldown.test.ts index a6896367bd61..bff507836d17 100644 --- a/x-pack/plugins/drilldowns/url_drilldown/public/lib/url_drilldown.test.ts +++ b/x-pack/plugins/drilldowns/url_drilldown/public/lib/url_drilldown.test.ts @@ -49,14 +49,14 @@ const mockDataPoints = [ }, ]; -const mockEmbeddable = ({ +const mockEmbeddable = { getInput: () => ({ filters: [], timeRange: { from: 'now-15m', to: 'now' }, query: { query: 'test', language: 'kuery' }, }), getOutput: () => ({}), -} as unknown) as IEmbeddable; +} as unknown as IEmbeddable; const mockNavigateToUrl = jest.fn(() => Promise.resolve()); diff --git a/x-pack/plugins/drilldowns/url_drilldown/public/lib/variables/event_variables.test.ts b/x-pack/plugins/drilldowns/url_drilldown/public/lib/variables/event_variables.test.ts index 2a56a5fa0e10..d66d998d7440 100644 --- a/x-pack/plugins/drilldowns/url_drilldown/public/lib/variables/event_variables.test.ts +++ b/x-pack/plugins/drilldowns/url_drilldown/public/lib/variables/event_variables.test.ts @@ -53,7 +53,7 @@ describe('VALUE_CLICK_TRIGGER', () => { describe('handles undefined, null or missing values', () => { test('undefined or missing values are removed from the result scope', () => { - const point = createPoint(({ field: undefined } as unknown) as { + const point = createPoint({ field: undefined } as unknown as { field: string; value: string | null | number | boolean; }); @@ -90,10 +90,10 @@ describe('ROW_CLICK_TRIGGER', () => { }); test('getEventScopeValues() returns correct variables for row click trigger', () => { - const context = ({ + const context = { embeddable: {}, data: rowClickData as any, - } as unknown) as RowClickContext; + } as unknown as RowClickContext; const res = getEventScopeValues(context); expect(res).toEqual({ diff --git a/x-pack/plugins/drilldowns/url_drilldown/public/plugin.ts b/x-pack/plugins/drilldowns/url_drilldown/public/plugin.ts index b733691c639b..053803d69a3e 100644 --- a/x-pack/plugins/drilldowns/url_drilldown/public/plugin.ts +++ b/x-pack/plugins/drilldowns/url_drilldown/public/plugin.ts @@ -32,7 +32,8 @@ export interface SetupContract {} export interface StartContract {} export class UrlDrilldownPlugin - implements Plugin { + implements Plugin +{ constructor(protected readonly context: PluginInitializerContext) {} public setup(core: CoreSetup, plugins: SetupDependencies): SetupContract { diff --git a/x-pack/plugins/embeddable_enhanced/public/plugin.ts b/x-pack/plugins/embeddable_enhanced/public/plugin.ts index 4b27b31ad3e0..4e83b5b0ffcd 100644 --- a/x-pack/plugins/embeddable_enhanced/public/plugin.ts +++ b/x-pack/plugins/embeddable_enhanced/public/plugin.ts @@ -48,7 +48,8 @@ export interface SetupContract {} export interface StartContract {} export class EmbeddableEnhancedPlugin - implements Plugin { + implements Plugin +{ constructor(protected readonly context: PluginInitializerContext) {} private uiActions?: StartDependencies['uiActionsEnhanced']; diff --git a/x-pack/plugins/encrypted_saved_objects/server/audit/index.mock.ts b/x-pack/plugins/encrypted_saved_objects/server/audit/index.mock.ts index 4b8f183e4928..a74ef1cb4fd2 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/audit/index.mock.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/audit/index.mock.ts @@ -9,11 +9,11 @@ import type { EncryptedSavedObjectsAuditLogger } from './audit_logger'; export const encryptedSavedObjectsAuditLoggerMock = { create() { - return ({ + return { encryptAttributesSuccess: jest.fn(), encryptAttributeFailure: jest.fn(), decryptAttributesSuccess: jest.fn(), decryptAttributeFailure: jest.fn(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; }, }; diff --git a/x-pack/plugins/encrypted_saved_objects/server/create_migration.ts b/x-pack/plugins/encrypted_saved_objects/server/create_migration.ts index 18786e0f9d1c..f166e018d9c9 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/create_migration.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/create_migration.ts @@ -46,109 +46,117 @@ export type CreateEncryptedSavedObjectsMigrationFn = < opts: CreateEncryptedSavedObjectsMigrationFnOpts ) => SavedObjectOptionalMigrationFn; -export const getCreateMigration = ( - encryptedSavedObjectsService: Readonly, - instantiateServiceWithLegacyType: ( - typeRegistration: EncryptedSavedObjectTypeRegistration - ) => EncryptedSavedObjectsService -): CreateEncryptedSavedObjectsMigrationFn => (opts) => { - const { - isMigrationNeededPredicate, - migration, - shouldMigrateIfDecryptionFails, - inputType, - migratedType, - } = opts; - - if (inputType && migratedType && inputType.type !== migratedType.type) { - throw new Error( - `An Invalid Encrypted Saved Objects migration is trying to migrate across types ("${inputType.type}" => "${migratedType.type}"), which isn't permitted` - ); - } - - const inputService = inputType - ? instantiateServiceWithLegacyType(inputType) - : encryptedSavedObjectsService; - - const migratedService = migratedType - ? instantiateServiceWithLegacyType(migratedType) - : encryptedSavedObjectsService; - - return (encryptedDoc, context) => { - if (!isMigrationNeededPredicate(encryptedDoc)) { - return encryptedDoc; +export const getCreateMigration = + ( + encryptedSavedObjectsService: Readonly, + instantiateServiceWithLegacyType: ( + typeRegistration: EncryptedSavedObjectTypeRegistration + ) => EncryptedSavedObjectsService + ): CreateEncryptedSavedObjectsMigrationFn => + (opts) => { + const { + isMigrationNeededPredicate, + migration, + shouldMigrateIfDecryptionFails, + inputType, + migratedType, + } = opts; + + if (inputType && migratedType && inputType.type !== migratedType.type) { + throw new Error( + `An Invalid Encrypted Saved Objects migration is trying to migrate across types ("${inputType.type}" => "${migratedType.type}"), which isn't permitted` + ); } - // After it is converted, the object's old ID is stored in the `originId` field. In addition, objects that are imported a certain way - // may have this field set, but it would not be necessary to use this to decrypt saved object attributes. - const { type, id, originId } = encryptedDoc; - - // If an object is slated to be converted, it should be decrypted flexibly: - // * If this is an index migration: - // a. If there is one or more pending migration _before_ the conversion, the object will be decrypted and re-encrypted with its - // namespace in the descriptor. Then, after the conversion, the object will be decrypted with its namespace and old ID in the - // descriptor and re-encrypted with its new ID (without a namespace) in the descriptor. - // b. If there are no pending migrations before the conversion, then after the conversion the object will be decrypted with its - // namespace and old ID in the descriptor and re-encrypted with its new ID (without a namespace) in the descriptor. - // * If this is *not* an index migration, then it is a single document migration. In that case, the object will be decrypted and - // re-encrypted without a namespace in the descriptor. - // To account for these different scenarios, when this field is set, the ESO service will attempt several different permutations of - // the descriptor when decrypting the object. - const isTypeBeingConverted = - !!context.convertToMultiNamespaceTypeVersion && - semver.lte(context.migrationVersion, context.convertToMultiNamespaceTypeVersion); - - // This approximates the behavior of getDescriptorNamespace(); the intent is that if there is ever a case where a multi-namespace object - // has the `namespace` field, it will not be encrypted with that field in its descriptor. It would be preferable to rely on - // getDescriptorNamespace() here, but that requires the SO type registry which can only be retrieved from a promise, and this is not an - // async function - const descriptorNamespace = context.isSingleNamespaceType ? encryptedDoc.namespace : undefined; - let decryptDescriptorNamespace = descriptorNamespace; - - // If an object has been converted right before this migration function is called, it will no longer have a `namespace` field, but it - // will have a `namespaces` field; in that case, the first/only element in that array should be used as the namespace in the descriptor - // during decryption. - if (isTypeBeingConverted) { - decryptDescriptorNamespace = encryptedDoc.namespaces?.length - ? normalizeNamespace(encryptedDoc.namespaces[0]) // `namespaces` contains string values, but we need to normalize this to the namespace ID representation - : encryptedDoc.namespace; - } + const inputService = inputType + ? instantiateServiceWithLegacyType(inputType) + : encryptedSavedObjectsService; - // These descriptors might have a `namespace` that is undefined. That is expected for multi-namespace and namespace-agnostic types. - const decryptDescriptor = { id, type, namespace: decryptDescriptorNamespace }; - const encryptDescriptor = { id, type, namespace: descriptorNamespace }; - - // decrypt the attributes using the input type definition - // if an error occurs during decryption, use the shouldMigrateIfDecryptionFails flag - // to determine whether to throw the error or continue the migration - // if we are continuing the migration, strip encrypted attributes from the document using stripOrDecryptAttributesSync - const documentToMigrate = mapAttributes(encryptedDoc, (inputAttributes) => { - try { - return inputService.decryptAttributesSync(decryptDescriptor, inputAttributes, { - isTypeBeingConverted, - originId, - }); - } catch (err) { - if (!shouldMigrateIfDecryptionFails || !(err instanceof EncryptionError)) { - throw err; - } + const migratedService = migratedType + ? instantiateServiceWithLegacyType(migratedType) + : encryptedSavedObjectsService; + + return (encryptedDoc, context) => { + if (!isMigrationNeededPredicate(encryptedDoc)) { + return encryptedDoc; + } - context.log.warn( - `Decryption failed for encrypted Saved Object "${encryptedDoc.id}" of type "${encryptedDoc.type}" with error: ${err.message}. Encrypted attributes have been stripped from the original document and migration will be applied but this may cause errors later on.` - ); - return inputService.stripOrDecryptAttributesSync(decryptDescriptor, inputAttributes, { - isTypeBeingConverted, - originId, - }).attributes; + // After it is converted, the object's old ID is stored in the `originId` field. In addition, objects that are imported a certain way + // may have this field set, but it would not be necessary to use this to decrypt saved object attributes. + const { type, id, originId } = encryptedDoc; + + // If an object is slated to be converted, it should be decrypted flexibly: + // * If this is an index migration: + // a. If there is one or more pending migration _before_ the conversion, the object will be decrypted and re-encrypted with its + // namespace in the descriptor. Then, after the conversion, the object will be decrypted with its namespace and old ID in the + // descriptor and re-encrypted with its new ID (without a namespace) in the descriptor. + // b. If there are no pending migrations before the conversion, then after the conversion the object will be decrypted with its + // namespace and old ID in the descriptor and re-encrypted with its new ID (without a namespace) in the descriptor. + // * If this is *not* an index migration, then it is a single document migration. In that case, the object will be decrypted and + // re-encrypted without a namespace in the descriptor. + // To account for these different scenarios, when this field is set, the ESO service will attempt several different permutations of + // the descriptor when decrypting the object. + const isTypeBeingConverted = + !!context.convertToMultiNamespaceTypeVersion && + semver.lte(context.migrationVersion, context.convertToMultiNamespaceTypeVersion); + + // This approximates the behavior of getDescriptorNamespace(); the intent is that if there is ever a case where a multi-namespace object + // has the `namespace` field, it will not be encrypted with that field in its descriptor. It would be preferable to rely on + // getDescriptorNamespace() here, but that requires the SO type registry which can only be retrieved from a promise, and this is not an + // async function + const descriptorNamespace = context.isSingleNamespaceType + ? encryptedDoc.namespace + : undefined; + let decryptDescriptorNamespace = descriptorNamespace; + + // If an object has been converted right before this migration function is called, it will no longer have a `namespace` field, but it + // will have a `namespaces` field; in that case, the first/only element in that array should be used as the namespace in the descriptor + // during decryption. + if (isTypeBeingConverted) { + decryptDescriptorNamespace = encryptedDoc.namespaces?.length + ? normalizeNamespace(encryptedDoc.namespaces[0]) // `namespaces` contains string values, but we need to normalize this to the namespace ID representation + : encryptedDoc.namespace; } - }); - // migrate and encrypt the document - return mapAttributes(migration(documentToMigrate, context), (migratedAttributes) => { - return migratedService.encryptAttributesSync(encryptDescriptor, migratedAttributes); - }); + // These descriptors might have a `namespace` that is undefined. That is expected for multi-namespace and namespace-agnostic types. + const decryptDescriptor = { id, type, namespace: decryptDescriptorNamespace }; + const encryptDescriptor = { id, type, namespace: descriptorNamespace }; + + // decrypt the attributes using the input type definition + // if an error occurs during decryption, use the shouldMigrateIfDecryptionFails flag + // to determine whether to throw the error or continue the migration + // if we are continuing the migration, strip encrypted attributes from the document using stripOrDecryptAttributesSync + const documentToMigrate = mapAttributes(encryptedDoc, (inputAttributes) => { + try { + return inputService.decryptAttributesSync(decryptDescriptor, inputAttributes, { + isTypeBeingConverted, + originId, + }); + } catch (err) { + if (!shouldMigrateIfDecryptionFails || !(err instanceof EncryptionError)) { + throw err; + } + + context.log.warn( + `Decryption failed for encrypted Saved Object "${encryptedDoc.id}" of type "${encryptedDoc.type}" with error: ${err.message}. Encrypted attributes have been stripped from the original document and migration will be applied but this may cause errors later on.` + ); + return inputService.stripOrDecryptAttributesSync( + decryptDescriptor, + inputAttributes, + { + isTypeBeingConverted, + originId, + } + ).attributes; + } + }); + + // migrate and encrypt the document + return mapAttributes(migration(documentToMigrate, context), (migratedAttributes) => { + return migratedService.encryptAttributesSync(encryptDescriptor, migratedAttributes); + }); + }; }; -}; function mapAttributes(obj: SavedObjectUnsanitizedDoc, mapper: (attributes: T) => T) { return Object.assign(obj, { diff --git a/x-pack/plugins/encrypted_saved_objects/server/crypto/encrypted_saved_objects_service.mocks.ts b/x-pack/plugins/encrypted_saved_objects/server/crypto/encrypted_saved_objects_service.mocks.ts index 2e8e37e61dee..18df968502b1 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/crypto/encrypted_saved_objects_service.mocks.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/crypto/encrypted_saved_objects_service.mocks.ts @@ -12,7 +12,7 @@ import type { } from './encrypted_saved_objects_service'; function createEncryptedSavedObjectsServiceMock() { - return ({ + return { isRegistered: jest.fn(), stripOrDecryptAttributes: jest.fn(), encryptAttributes: jest.fn(), @@ -20,7 +20,7 @@ function createEncryptedSavedObjectsServiceMock() { encryptAttributesSync: jest.fn(), decryptAttributesSync: jest.fn(), stripOrDecryptAttributesSync: jest.fn(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; } export const encryptedSavedObjectsServiceMock = { diff --git a/x-pack/plugins/encrypted_saved_objects/server/crypto/encrypted_saved_objects_service.ts b/x-pack/plugins/encrypted_saved_objects/server/crypto/encrypted_saved_objects_service.ts index 0cf775b88e7d..4980817393c5 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/crypto/encrypted_saved_objects_service.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/crypto/encrypted_saved_objects_service.ts @@ -122,10 +122,8 @@ export class EncryptedSavedObjectsService { * Map of all registered saved object types where the `key` is saved object type and the `value` * is the definition (names of attributes that need to be encrypted etc.). */ - private readonly typeDefinitions: Map< - string, - EncryptedSavedObjectAttributesDefinition - > = new Map(); + private readonly typeDefinitions: Map = + new Map(); constructor(private readonly options: EncryptedSavedObjectsServiceOptions) {} diff --git a/x-pack/plugins/encrypted_saved_objects/server/crypto/encryption_key_rotation_service.mocks.ts b/x-pack/plugins/encrypted_saved_objects/server/crypto/encryption_key_rotation_service.mocks.ts index a69154c0e7be..9580cb85f524 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/crypto/encryption_key_rotation_service.mocks.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/crypto/encryption_key_rotation_service.mocks.ts @@ -8,7 +8,7 @@ import type { EncryptionKeyRotationService } from './encryption_key_rotation_service'; function createEncryptionKeyRotationServiceMock() { - return ({ rotate: jest.fn() } as unknown) as jest.Mocked; + return { rotate: jest.fn() } as unknown as jest.Mocked; } export const encryptionKeyRotationServiceMock = { diff --git a/x-pack/plugins/encrypted_saved_objects/server/plugin.ts b/x-pack/plugins/encrypted_saved_objects/server/plugin.ts index fa1b6415d206..565d4379014c 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/plugin.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/plugin.ts @@ -47,7 +47,8 @@ export interface EncryptedSavedObjectsPluginStart { */ export class EncryptedSavedObjectsPlugin implements - Plugin { + Plugin +{ private readonly logger: Logger; private savedObjectsSetup!: ClientInstanciator; diff --git a/x-pack/plugins/encrypted_saved_objects/server/routes/key_rotation.test.ts b/x-pack/plugins/encrypted_saved_objects/server/routes/key_rotation.test.ts index 138d111cb8f9..a052b847a50f 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/routes/key_rotation.test.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/routes/key_rotation.test.ts @@ -25,7 +25,7 @@ describe('Key rotation routes', () => { router = routeParamsMock.router; mockEncryptionKeyRotationService = routeParamsMock.encryptionKeyRotationService; - mockContext = ({} as unknown) as RequestHandlerContext; + mockContext = {} as unknown as RequestHandlerContext; defineKeyRotationRoutes(routeParamsMock); }); @@ -92,8 +92,7 @@ describe('Key rotation routes', () => { payload: 'Kibana is not configured to support encryption key rotation. Update `kibana.yml` to include `xpack.encryptedSavedObjects.keyRotation.decryptionOnlyKeys` to rotate your encryption keys.', options: { - body: - 'Kibana is not configured to support encryption key rotation. Update `kibana.yml` to include `xpack.encryptedSavedObjects.keyRotation.decryptionOnlyKeys` to rotate your encryption keys.', + body: 'Kibana is not configured to support encryption key rotation. Update `kibana.yml` to include `xpack.encryptedSavedObjects.keyRotation.decryptionOnlyKeys` to rotate your encryption keys.', }, }); }); @@ -145,8 +144,7 @@ describe('Key rotation routes', () => { 'Encryption key rotation is in progress already. Please wait until it is completed and try again.', options: { statusCode: 429, - body: - 'Encryption key rotation is in progress already. Please wait until it is completed and try again.', + body: 'Encryption key rotation is in progress already. Please wait until it is completed and try again.', }, }); diff --git a/x-pack/plugins/encrypted_saved_objects/server/routes/key_rotation.ts b/x-pack/plugins/encrypted_saved_objects/server/routes/key_rotation.ts index 2a8076d537eb..f59c4fa61f4a 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/routes/key_rotation.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/routes/key_rotation.ts @@ -45,15 +45,13 @@ export function defineKeyRotationRoutes({ async (context, request, response) => { if (config.keyRotation.decryptionOnlyKeys.length === 0) { return response.badRequest({ - body: - 'Kibana is not configured to support encryption key rotation. Update `kibana.yml` to include `xpack.encryptedSavedObjects.keyRotation.decryptionOnlyKeys` to rotate your encryption keys.', + body: 'Kibana is not configured to support encryption key rotation. Update `kibana.yml` to include `xpack.encryptedSavedObjects.keyRotation.decryptionOnlyKeys` to rotate your encryption keys.', }); } if (rotationInProgress) { return response.customError({ - body: - 'Encryption key rotation is in progress already. Please wait until it is completed and try again.', + body: 'Encryption key rotation is in progress already. Please wait until it is completed and try again.', statusCode: 429, }); } 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 0d958d29b215..116a112fa165 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 @@ -1478,7 +1478,7 @@ describe('#bulkResolve', () => { }; mockBaseClient.bulkResolve.mockResolvedValue( - (mockedResponse as unknown) as SavedObjectsBulkResolveResponse + mockedResponse as unknown as SavedObjectsBulkResolveResponse ); const bulkResolveParams = [ @@ -1527,7 +1527,7 @@ describe('#bulkResolve', () => { }; mockBaseClient.bulkResolve.mockResolvedValue( - (mockedResponse as unknown) as SavedObjectsBulkResolveResponse + mockedResponse as unknown as SavedObjectsBulkResolveResponse ); const bulkResolveParams = [ @@ -1601,7 +1601,7 @@ describe('#bulkResolve', () => { }; mockBaseClient.bulkResolve.mockResolvedValue( - (mockedResponse as unknown) as SavedObjectsBulkResolveResponse + mockedResponse as unknown as SavedObjectsBulkResolveResponse ); const decryptionError = new EncryptionError( @@ -1679,7 +1679,7 @@ describe('#bulkResolve', () => { ], }; mockBaseClient.bulkResolve.mockResolvedValue( - (mockedResponse as unknown) as SavedObjectsBulkResolveResponse + mockedResponse as unknown as SavedObjectsBulkResolveResponse ); const bulkGetParams = [{ type: 'known-type', id: 'bad' }]; diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/analytics/views/query_detail.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/analytics/views/query_detail.tsx index e68984459cf1..814173744249 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/analytics/views/query_detail.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/analytics/views/query_detail.tsx @@ -27,9 +27,8 @@ export const QueryDetail: React.FC = () => { const { query } = useDecodedParams(); const queryTitle = query === '""' ? query : `"${query}"`; - const { totalQueriesForQuery, queriesPerDayForQuery, startDate, topClicksForQuery } = useValues( - AnalyticsLogic - ); + const { totalQueriesForQuery, queriesPerDayForQuery, startDate, topClicksForQuery } = + useValues(AnalyticsLogic); return ( diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/add_domain/add_domain_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/add_domain/add_domain_logic.test.ts index 4dd699a733b8..3f913d76f475 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/add_domain/add_domain_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/add_domain/add_domain_logic.test.ts @@ -395,9 +395,10 @@ describe('AddDomainLogic', () => { AddDomainLogic.actions.validateDomainInitialVerification('https://elastic.co', '/'); await nextTick(); - expect( - AddDomainLogic.actions.performDomainValidationStep - ).toHaveBeenCalledWith('initialValidation', ['url']); + expect(AddDomainLogic.actions.performDomainValidationStep).toHaveBeenCalledWith( + 'initialValidation', + ['url'] + ); }); }); @@ -408,9 +409,10 @@ describe('AddDomainLogic', () => { AddDomainLogic.actions.validateDomainContentVerification(); await nextTick(); - expect( - AddDomainLogic.actions.performDomainValidationStep - ).toHaveBeenCalledWith('contentVerification', ['url_request', 'url_content']); + expect(AddDomainLogic.actions.performDomainValidationStep).toHaveBeenCalledWith( + 'contentVerification', + ['url_request', 'url_content'] + ); }); }); @@ -421,9 +423,10 @@ describe('AddDomainLogic', () => { AddDomainLogic.actions.validateDomainIndexingRestrictions(); await nextTick(); - expect( - AddDomainLogic.actions.performDomainValidationStep - ).toHaveBeenCalledWith('indexingRestrictions', ['robots_txt']); + expect(AddDomainLogic.actions.performDomainValidationStep).toHaveBeenCalledWith( + 'indexingRestrictions', + ['robots_txt'] + ); }); }); @@ -434,9 +437,10 @@ describe('AddDomainLogic', () => { AddDomainLogic.actions.validateDomainNetworkConnectivity(); await nextTick(); - expect( - AddDomainLogic.actions.performDomainValidationStep - ).toHaveBeenCalledWith('networkConnectivity', ['dns', 'tcp']); + expect(AddDomainLogic.actions.performDomainValidationStep).toHaveBeenCalledWith( + 'networkConnectivity', + ['dns', 'tcp'] + ); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/add_domain/add_domain_logic.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/add_domain/add_domain_logic.ts index 020515b2cad8..ab85f8a585d1 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/add_domain/add_domain_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/add_domain/add_domain_logic.ts @@ -57,9 +57,9 @@ export interface AddDomainLogicActions { checks: string[]; }; setAddDomainFormInputValue(newValue: string): string; - setDomainValidationResult( - change: CrawlerDomainValidationResultChange - ): { change: CrawlerDomainValidationResultChange }; + setDomainValidationResult(change: CrawlerDomainValidationResultChange): { + change: CrawlerDomainValidationResultChange; + }; startDomainValidation(): void; submitNewDomain(): void; validateDomainInitialVerification( diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/manage_crawls_popover/automatic_crawl_scheduler_logic.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/manage_crawls_popover/automatic_crawl_scheduler_logic.ts index 432aa9f139dd..126d9d0f1076 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/manage_crawls_popover/automatic_crawl_scheduler_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/manage_crawls_popover/automatic_crawl_scheduler_logic.ts @@ -36,9 +36,9 @@ export interface AutomaticCrawlSchedulerLogicActions { enableCrawlAutomatically(): void; fetchCrawlSchedule(): void; saveChanges(): void; - setCrawlFrequency( - crawlFrequency: CrawlSchedule['frequency'] - ): { crawlFrequency: CrawlSchedule['frequency'] }; + setCrawlFrequency(crawlFrequency: CrawlSchedule['frequency']): { + crawlFrequency: CrawlSchedule['frequency']; + }; setCrawlSchedule(crawlSchedule: CrawlSchedule): { crawlSchedule: CrawlSchedule }; setCrawlUnit(crawlUnit: CrawlSchedule['unit']): { crawlUnit: CrawlSchedule['unit'] }; submitCrawlSchedule(): void; diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/credentials.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/credentials.tsx index f777278190db..77a66fbc76ad 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/credentials.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/credentials.tsx @@ -31,9 +31,8 @@ import { CredentialsList } from './credentials_list'; import { CredentialsLogic } from './credentials_logic'; export const Credentials: React.FC = () => { - const { fetchCredentials, fetchDetails, resetCredentials, showCredentialsForm } = useActions( - CredentialsLogic - ); + const { fetchCredentials, fetchDetails, resetCredentials, showCredentialsForm } = + useActions(CredentialsLogic); const { meta, dataLoading, shouldShowCredentialsForm } = useValues(CredentialsLogic); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/results/add_result_flyout.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/results/add_result_flyout.tsx index a20e4e137f89..9d341cc2f552 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/results/add_result_flyout.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/results/add_result_flyout.tsx @@ -43,9 +43,8 @@ export const AddResultFlyout: React.FC = () => { const { search } = useActions(searchLogic); const { promotedIds, hiddenIds } = useValues(CurationLogic); - const { addPromotedId, removePromotedId, addHiddenId, removeHiddenId } = useActions( - CurationLogic - ); + const { addPromotedId, removePromotedId, addHiddenId, removeHiddenId } = + useActions(CurationLogic); return ( diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/document_creation/document_creation_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/document_creation/document_creation_logic.test.ts index a75cb7853678..cf1b45d46826 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/document_creation/document_creation_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/document_creation/document_creation_logic.test.ts @@ -516,7 +516,7 @@ describe('DocumentCreationLogic', () => { describe('chunks large uploads', () => { // Using an array of #s for speed, it doesn't really matter what the contents of the documents are for this test - const largeDocumentsArray = ([...Array(200).keys()] as unknown) as object[]; + const largeDocumentsArray = [...Array(200).keys()] as unknown as object[]; const mockFirstResponse = { validDocuments: { total: 99, examples: largeDocumentsArray.slice(0, 98) }, diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/document_creation/utils.test.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/document_creation/utils.test.ts index 88cde227d38a..3a5bb36477f5 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/document_creation/utils.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/document_creation/utils.test.ts @@ -15,7 +15,7 @@ describe('readUploadedFileAsText', () => { }); it('throws an error if the file cannot be read', async () => { - const badFile = ('causes an error' as unknown) as File; + const badFile = 'causes an error' as unknown as File; await expect(readUploadedFileAsText(badFile)).rejects.toThrow(); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine/engine_router.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine/engine_router.tsx index 8b0e6428babf..669a72900074 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine/engine_router.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine/engine_router.tsx @@ -67,9 +67,8 @@ export const EngineRouter: React.FC = () => { const { engineName: engineNameFromUrl } = useParams() as { engineName: string }; const { engineName, dataLoading, engineNotFound, isMetaEngine } = useValues(EngineLogic); - const { setEngineName, initializeEngine, pollEmptyEngine, stopPolling, clearEngine } = useActions( - EngineLogic - ); + const { setEngineName, initializeEngine, pollEmptyEngine, stopPolling, clearEngine } = + useActions(EngineLogic); useEffect(() => { setEngineName(engineNameFromUrl); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engines/components/tables/meta_engines_table_logic.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engines/components/tables/meta_engines_table_logic.ts index 94205a5392b6..63d4fe99ff62 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engines/components/tables/meta_engines_table_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engines/components/tables/meta_engines_table_logic.ts @@ -17,9 +17,9 @@ interface MetaEnginesTableValues { } interface MetaEnginesTableActions { - addSourceEngines( - sourceEngines: MetaEnginesTableValues['sourceEngines'] - ): { sourceEngines: MetaEnginesTableValues['sourceEngines'] }; + addSourceEngines(sourceEngines: MetaEnginesTableValues['sourceEngines']): { + sourceEngines: MetaEnginesTableValues['sourceEngines']; + }; displayRow(itemId: string): { itemId: string }; fetchOrDisplayRow(itemId: string): { itemId: string }; fetchSourceEngines(engineName: string): { engineName: string }; diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engines/engines_overview.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engines/engines_overview.tsx index d1dd5514757d..4a08c592fdb6 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engines/engines_overview.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engines/engines_overview.tsx @@ -49,9 +49,8 @@ export const EnginesOverview: React.FC = () => { metaEnginesLoading, } = useValues(EnginesLogic); - const { loadEngines, loadMetaEngines, onEnginesPagination, onMetaEnginesPagination } = useActions( - EnginesLogic - ); + const { loadEngines, loadMetaEngines, onEnginesPagination, onMetaEnginesPagination } = + useActions(EnginesLogic); useEffect(() => { loadEngines(); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/library/library.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/library/library.tsx index 9b5d6090f2f8..55c9cc795834 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/library/library.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/library/library.tsx @@ -268,10 +268,10 @@ export const Library: React.FC = () => { isMetaEngine: true, result: { ...props.result, - 'this-description-is-a-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-long-key': { - raw: - 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?', - }, + 'this-description-is-a-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-really-long-key': + { + raw: 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?', + }, _meta: { id: 'my-id-is-a-really-long-id-yes-it-is', score: 100, diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/meta_engine_creation/meta_engine_creation.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/meta_engine_creation/meta_engine_creation.tsx index 1455444ab2b4..d83379fb7a2a 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/meta_engine_creation/meta_engine_creation.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/meta_engine_creation/meta_engine_creation.tsx @@ -57,16 +57,11 @@ export const MetaEngineCreation: React.FC = () => { }, } = useValues(AppLogic); - const { - fetchIndexedEngineNames, - setRawName, - setSelectedIndexedEngineNames, - submitEngine, - } = useActions(MetaEngineCreationLogic); + const { fetchIndexedEngineNames, setRawName, setSelectedIndexedEngineNames, submitEngine } = + useActions(MetaEngineCreationLogic); - const { rawName, name, indexedEngineNames, selectedIndexedEngineNames, isLoading } = useValues( - MetaEngineCreationLogic - ); + const { rawName, name, indexedEngineNames, selectedIndexedEngineNames, isLoading } = + useValues(MetaEngineCreationLogic); useEffect(() => { fetchIndexedEngineNames(); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/meta_engine_creation/meta_engine_creation_logic.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/meta_engine_creation/meta_engine_creation_logic.ts index 95ef53d82cc4..5296676a38b3 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/meta_engine_creation/meta_engine_creation_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/meta_engine_creation/meta_engine_creation_logic.ts @@ -31,9 +31,9 @@ interface MetaEngineCreationValues { interface MetaEngineCreationActions { fetchIndexedEngineNames(page?: number): { page: number }; onEngineCreationSuccess(): void; - setIndexedEngineNames( - indexedEngineNames: MetaEngineCreationValues['indexedEngineNames'] - ): { indexedEngineNames: MetaEngineCreationValues['indexedEngineNames'] }; + setIndexedEngineNames(indexedEngineNames: MetaEngineCreationValues['indexedEngineNames']): { + indexedEngineNames: MetaEngineCreationValues['indexedEngineNames']; + }; setRawName(rawName: string): { rawName: string }; setSelectedIndexedEngineNames( selectedIndexedEngineNames: MetaEngineCreationValues['selectedIndexedEngineNames'] diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/relevance_tuning/relevance_tuning.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/relevance_tuning/relevance_tuning.tsx index 87fcf91718b5..b36ab2f12892 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/relevance_tuning/relevance_tuning.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/relevance_tuning/relevance_tuning.tsx @@ -29,9 +29,8 @@ import { RelevanceTuningLogic } from '.'; export const RelevanceTuning: React.FC = () => { const { dataLoading, engineHasSchemaFields, unsavedChanges } = useValues(RelevanceTuningLogic); - const { initializeRelevanceTuning, resetSearchSettings, updateSearchSettings } = useActions( - RelevanceTuningLogic - ); + const { initializeRelevanceTuning, resetSearchSettings, updateSearchSettings } = + useActions(RelevanceTuningLogic); useEffect(() => { initializeRelevanceTuning(); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/result/result.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/result/result.test.tsx index 1e361f113d88..dfb01a1a793c 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/result/result.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/result/result.test.tsx @@ -124,9 +124,9 @@ describe('Result', () => { describe('dragging', () => { // In the real world, the drag library sets data attributes, role, tabIndex, etc. - const mockDragHandleProps = ({ + const mockDragHandleProps = { someMockProp: true, - } as unknown) as DraggableProvidedDragHandleProps; + } as unknown as DraggableProvidedDragHandleProps; it('will render a drag handle with the passed props', () => { const wrapper = shallow(); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/result_settings/result_settings.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/result_settings/result_settings.tsx index c315927433a0..1b9b5670af35 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/result_settings/result_settings.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/result_settings/result_settings.tsx @@ -37,13 +37,8 @@ const UNSAVED_MESSAGE = i18n.translate( ); export const ResultSettings: React.FC = () => { - const { - dataLoading, - schema, - stagedUpdates, - resultFieldsAtDefaultSettings, - resultFieldsEmpty, - } = useValues(ResultSettingsLogic); + const { dataLoading, schema, stagedUpdates, resultFieldsAtDefaultSettings, resultFieldsEmpty } = + useValues(ResultSettingsLogic); const { initializeResultSettingsData, saveResultSettings, diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/result_settings/sample_response/sample_response_logic.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/result_settings/sample_response/sample_response_logic.ts index dfa39367b67c..d4c5a842daac 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/result_settings/sample_response/sample_response_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/result_settings/sample_response/sample_response_logic.ts @@ -33,9 +33,9 @@ interface SampleResponseValues { interface SampleResponseActions { queryChanged: (query: string) => { query: string }; - getSearchResultsSuccess: ( - response: SampleSearchResponse | string - ) => { response: SampleSearchResponse | string }; + getSearchResultsSuccess: (response: SampleSearchResponse | string) => { + response: SampleSearchResponse | string; + }; getSearchResultsFailure: (response: string) => { response: string }; getSearchResults: ( query: string, diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/engine_assignment_selector.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/engine_assignment_selector.test.tsx index 01c46e6423d7..9e2d708e20e7 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/engine_assignment_selector.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/engine_assignment_selector.test.tsx @@ -90,9 +90,11 @@ describe('EngineAssignmentSelector', () => { it('handles engine checkbox click', async () => { const wrapper = shallow(); await waitFor(() => - ((wrapper.find(EuiComboBox).props() as unknown) as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - }).onChange([{ label: engines[0].name, value: engines[0].name }]) + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ label: engines[0].name, value: engines[0].name }]) ); wrapper.update(); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/engine_assignment_selector.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/engine_assignment_selector.tsx index bb40a1a4fa27..09ee0940cee9 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/engine_assignment_selector.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/engine_assignment_selector.tsx @@ -26,17 +26,11 @@ import { import { RoleMappingsLogic } from './role_mappings_logic'; export const EngineAssignmentSelector: React.FC = () => { - const { handleAccessAllEnginesChange, handleEngineSelectionChange } = useActions( - RoleMappingsLogic - ); + const { handleAccessAllEnginesChange, handleEngineSelectionChange } = + useActions(RoleMappingsLogic); - const { - accessAllEngines, - availableEngines, - roleType, - selectedEngines, - selectedOptions, - } = useValues(RoleMappingsLogic); + const { accessAllEngines, availableEngines, roleType, selectedEngines, selectedOptions } = + useValues(RoleMappingsLogic); const hasEngineAssignment = selectedEngines.size > 0 || accessAllEngines; diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/role_mappings_logic.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/role_mappings_logic.ts index 7b7bcd864ebd..2cee0b58e703 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/role_mappings_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/role_mappings_logic.ts @@ -48,11 +48,9 @@ const emptyUser = { username: '', email: '' } as ElasticsearchUser; interface RoleMappingsActions extends RoleMappingsBaseActions { setRoleMapping(roleMapping: ASRoleMapping): { roleMapping: ASRoleMapping }; setSingleUserRoleMapping(data?: UserMapping): { singleUserRoleMapping: UserMapping }; - setRoleMappings({ - roleMappings, - }: { + setRoleMappings({ roleMappings }: { roleMappings: ASRoleMapping[] }): { roleMappings: ASRoleMapping[]; - }): { roleMappings: ASRoleMapping[] }; + }; setRoleMappingsData(data: RoleMappingsServerDetails): RoleMappingsServerDetails; handleAccessAllEnginesChange(selected: boolean): { selected: boolean }; handleEngineSelectionChange(engineNames: string[]): { engineNames: string[] }; diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/user.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/user.tsx index 018d29706b05..57f08c22220f 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/user.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/user.tsx @@ -24,8 +24,8 @@ import { RoleTypes } from '../../types'; import { EngineAssignmentSelector } from './engine_assignment_selector'; import { RoleMappingsLogic } from './role_mappings_logic'; -const standardRoles = (['owner', 'admin'] as unknown) as RoleTypes[]; -const advancedRoles = (['dev', 'editor', 'analyst'] as unknown) as RoleTypes[]; +const standardRoles = ['owner', 'admin'] as unknown as RoleTypes[]; +const advancedRoles = ['dev', 'editor', 'analyst'] as unknown as RoleTypes[]; export const User: React.FC = () => { const { diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/schema/views/schema.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/schema/views/schema.tsx index d2a760e8accf..f8273edd5dfc 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/schema/views/schema.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/schema/views/schema.tsx @@ -21,12 +21,10 @@ import { SCHEMA_TITLE } from '../constants'; import { SchemaLogic } from '../schema_logic'; export const Schema: React.FC = () => { - const { loadSchema, updateSchema, addSchemaField, openModal, closeModal } = useActions( - SchemaLogic - ); - const { dataLoading, isUpdating, hasSchema, hasSchemaChanged, isModalOpen } = useValues( - SchemaLogic - ); + const { loadSchema, updateSchema, addSchemaField, openModal, closeModal } = + useActions(SchemaLogic); + const { dataLoading, isUpdating, hasSchema, hasSchemaChanged, isModalOpen } = + useValues(SchemaLogic); useEffect(() => { loadSchema(); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/source_engines/components/add_source_engines_modal.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/source_engines/components/add_source_engines_modal.tsx index 24e27e03818a..44dd550d952d 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/source_engines/components/add_source_engines_modal.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/source_engines/components/add_source_engines_modal.tsx @@ -33,9 +33,8 @@ import { SourceEnginesLogic } from '../source_engines_logic'; export const AddSourceEnginesModal: React.FC = () => { const { addSourceEngines, closeModal, onAddEnginesSelection } = useActions(SourceEnginesLogic); - const { selectableEngineNames, selectedEngineNamesToAdd, modalLoading } = useValues( - SourceEnginesLogic - ); + const { selectableEngineNames, selectedEngineNamesToAdd, modalLoading } = + useValues(SourceEnginesLogic); return ( diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/source_engines/source_engines_logic.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/source_engines/source_engines_logic.ts index af3c955258cf..bae87f9370a3 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/source_engines/source_engines_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/source_engines/source_engines_logic.ts @@ -32,19 +32,19 @@ interface SourceEnginesLogicActions { fetchIndexedEngines: () => void; fetchSourceEngines: () => void; onSourceEngineRemove: (sourceEngineNameToRemove: string) => { sourceEngineNameToRemove: string }; - onSourceEnginesAdd: ( - sourceEnginesToAdd: EngineDetails[] - ) => { sourceEnginesToAdd: EngineDetails[] }; - onSourceEnginesFetch: ( - sourceEngines: SourceEnginesLogicValues['sourceEngines'] - ) => { sourceEngines: SourceEnginesLogicValues['sourceEngines'] }; + onSourceEnginesAdd: (sourceEnginesToAdd: EngineDetails[]) => { + sourceEnginesToAdd: EngineDetails[]; + }; + onSourceEnginesFetch: (sourceEngines: SourceEnginesLogicValues['sourceEngines']) => { + sourceEngines: SourceEnginesLogicValues['sourceEngines']; + }; removeSourceEngine: (sourceEngineName: string) => { sourceEngineName: string }; setIndexedEngines: (indexedEngines: EngineDetails[]) => { indexedEngines: EngineDetails[] }; openModal: () => void; closeModal: () => void; - onAddEnginesSelection: ( - selectedEngineNamesToAdd: string[] - ) => { selectedEngineNamesToAdd: string[] }; + onAddEnginesSelection: (selectedEngineNamesToAdd: string[]) => { + selectedEngineNamesToAdd: string[]; + }; } export const SourceEnginesLogic = kea< diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/synonyms/components/synonym_modal.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/synonyms/components/synonym_modal.tsx index 64832c193854..3db4f4b73267 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/synonyms/components/synonym_modal.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/synonyms/components/synonym_modal.tsx @@ -35,9 +35,8 @@ import { SynonymsLogic } from '../index'; export const SynonymModal: React.FC = () => { const { isModalOpen, modalLoading, activeSynonymSet } = useValues(SynonymsLogic); - const { closeModal, createSynonymSet, updateSynonymSet, deleteSynonymSet } = useActions( - SynonymsLogic - ); + const { closeModal, createSynonymSet, updateSynonymSet, deleteSynonymSet } = + useActions(SynonymsLogic); const modalTitle = activeSynonymSet ? SYNONYM_UPDATE_TITLE : SYNONYM_CREATE_TITLE; const id = activeSynonymSet?.id || 'createNewSynonymSet'; diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/flash_messages/handle_api_errors.ts b/x-pack/plugins/enterprise_search/public/applications/shared/flash_messages/handle_api_errors.ts index 7c82dfb971a1..4fe8ad1cb851 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/flash_messages/handle_api_errors.ts +++ b/x-pack/plugins/enterprise_search/public/applications/shared/flash_messages/handle_api_errors.ts @@ -53,9 +53,9 @@ export const flashAPIErrors = ( response: HttpResponse, { isQueued }: Options = {} ) => { - const errorFlashMessages: IFlashMessage[] = getErrorsFromHttpResponse( - response - ).map((message) => ({ type: 'error', message })); + const errorFlashMessages: IFlashMessage[] = getErrorsFromHttpResponse(response).map( + (message) => ({ type: 'error', message }) + ); if (isQueued) { FlashMessagesLogic.actions.setQueuedMessages(errorFlashMessages); diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/types.ts b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/types.ts index 2eba171c270f..6b65cdad55d7 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/types.ts +++ b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/types.ts @@ -33,9 +33,9 @@ export interface RoleMappingsBaseActions { initializeSingleUserRoleMapping(roleMappingId?: string): { roleMappingId?: string }; initializeRoleMappings(): void; resetState(): void; - setElasticsearchUser( - elasticsearchUser?: ElasticsearchUser - ): { elasticsearchUser: ElasticsearchUser }; + setElasticsearchUser(elasticsearchUser?: ElasticsearchUser): { + elasticsearchUser: ElasticsearchUser; + }; openRoleMappingFlyout(): void; openSingleUserRoleMappingFlyout(): void; closeUsersAndRolesFlyout(): void; diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/user_selector.test.tsx b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/user_selector.test.tsx index 0aea55a51040..bc700268d46f 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/user_selector.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/user_selector.test.tsx @@ -30,7 +30,7 @@ describe('UserSelector', () => { const handleRoleChange = jest.fn(); const handleUsernameSelectChange = jest.fn(); - const roleType = ('user' as unknown) as ASRole; + const roleType = 'user' as unknown as ASRole; const props = { isNewUser: true, diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/users_table.tsx b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/users_table.tsx index 3dc5560a9eab..3d29c0b7f9a7 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/users_table.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/users_table.tsx @@ -66,7 +66,7 @@ export const UsersTable: React.FC = ({ handleDeleteMapping, }) => { // 'accessItems' is needed because App Search has `engines` and Workplace Search has `groups`. - const users = ((singleUserRoleMappings as SharedUser[]).map((user) => ({ + const users = (singleUserRoleMappings as SharedUser[]).map((user) => ({ username: user.elasticsearchUser.username, email: user.elasticsearchUser.email, enabled: user.elasticsearchUser.enabled, @@ -74,7 +74,7 @@ export const UsersTable: React.FC = ({ id: user.roleMapping.id, accessItems: (user.roleMapping as SharedRoleMapping)[accessItemKey], invitation: user.invitation, - })) as unknown) as Users; + })) as unknown as Users; const [items, setItems] = useState([] as Users); diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/table_pagination/index.ts b/x-pack/plugins/enterprise_search/public/applications/shared/table_pagination/index.ts index fb94a88fd0ce..ce6bb29c9601 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/table_pagination/index.ts +++ b/x-pack/plugins/enterprise_search/public/applications/shared/table_pagination/index.ts @@ -22,11 +22,11 @@ export const convertMetaToPagination = (meta: Meta) => ({ interface EuiBasicTableOnChange { page: { index: number }; } -export const handlePageChange = (paginationCallback: Function) => ({ - page: { index }, -}: EuiBasicTableOnChange) => { - paginationCallback(index + 1); -}; +export const handlePageChange = + (paginationCallback: Function) => + ({ page: { index } }: EuiBasicTableOnChange) => { + paginationCallback(index + 1); + }; /** * Helper for updating Kea `meta` state without mutating nested objs diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/tables/inline_editable_table/action_column.tsx b/x-pack/plugins/enterprise_search/public/applications/shared/tables/inline_editable_table/action_column.tsx index 1ba84a2fa43a..ec52b18adf64 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/tables/inline_editable_table/action_column.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/shared/tables/inline_editable_table/action_column.tsx @@ -41,12 +41,10 @@ export const ActionColumn = ({ lastItemWarning, uneditableItems, }: ActionColumnProps) => { - const { doesEditingItemValueContainEmptyProperty, formErrors, isEditingUnsavedItem } = useValues( - InlineEditableTableLogic - ); - const { editExistingItem, deleteItem, doneEditing, saveExistingItem, saveNewItem } = useActions( - InlineEditableTableLogic - ); + const { doesEditingItemValueContainEmptyProperty, formErrors, isEditingUnsavedItem } = + useValues(InlineEditableTableLogic); + const { editExistingItem, deleteItem, doneEditing, saveExistingItem, saveNewItem } = + useActions(InlineEditableTableLogic); if (uneditableItems?.includes(item)) { return null; diff --git a/x-pack/plugins/enterprise_search/public/applications/test_helpers/shallow_with_i18n.tsx b/x-pack/plugins/enterprise_search/public/applications/test_helpers/shallow_with_i18n.tsx index 012780437416..7eb10c710a34 100644 --- a/x-pack/plugins/enterprise_search/public/applications/test_helpers/shallow_with_i18n.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/test_helpers/shallow_with_i18n.tsx @@ -12,11 +12,13 @@ import { shallow, mount, ReactWrapper } from 'enzyme'; import { I18nProvider, __IntlProvider } from '@kbn/i18n/react'; // Use fake component to extract `intl` property to use in tests. -const { intl } = (mount( - -
-
-).find('IntlProvider') as ReactWrapper<{}, {}, __IntlProvider>) +const { intl } = ( + mount( + +
+
+ ).find('IntlProvider') as ReactWrapper<{}, {}, __IntlProvider> +) .instance() .getChildContext(); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/utils/read_uploaded_file_as_base64.test.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/utils/read_uploaded_file_as_base64.test.ts index 9f612a7432ec..2aedbbb798f5 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/utils/read_uploaded_file_as_base64.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/utils/read_uploaded_file_as_base64.test.ts @@ -15,7 +15,7 @@ describe('readUploadedFileAsBase64', () => { }); it('throws an error if the file cannot be read', async () => { - const badFile = ('causes an error' as unknown) as File; + const badFile = 'causes an error' as unknown as File; await expect(readUploadedFileAsBase64(badFile)).rejects.toThrow(); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/account_settings/account_settings.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/account_settings/account_settings.tsx index 313d3ffa59d4..f2b3e99eca7c 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/account_settings/account_settings.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/account_settings/account_settings.tsx @@ -24,9 +24,10 @@ export const AccountSettings: React.FC = () => { }, [security.authc]); const PersonalInfo = useMemo(() => security!.uiApi!.components.getPersonalInfo, [security.uiApi]); - const ChangePassword = useMemo(() => security!.uiApi!.components.getChangePassword, [ - security.uiApi, - ]); + const ChangePassword = useMemo( + () => security!.uiApi!.components.getChangePassword, + [security.uiApi] + ); if (!currentUser) { return null; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_list.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_list.tsx index 32161046bdd5..08e002ee432a 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_list.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_list.tsx @@ -46,9 +46,8 @@ import { } from './constants'; export const AddSourceList: React.FC = () => { - const { contentSources, dataLoading, availableSources, configuredSources } = useValues( - SourcesLogic - ); + const { contentSources, dataLoading, availableSources, configuredSources } = + useValues(SourcesLogic); const { initializeSources, resetSourcesState } = useActions(SourcesLogic); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.test.ts index 93cbbef07f7d..5ff3964b8f83 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.test.ts @@ -569,9 +569,7 @@ describe('AddSourceLogic', () => { expect(clearFlashMessages).toHaveBeenCalled(); expect(AddSourceLogic.values.buttonLoading).toEqual(true); - expect( - http.put - ).toHaveBeenCalledWith( + expect(http.put).toHaveBeenCalledWith( `/internal/workplace_search/org/settings/connectors/${sourceConfigData.serviceType}`, { body: JSON.stringify(params) } ); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.ts index 300b2aa6a10a..6f09cbb15c7d 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.ts @@ -62,11 +62,7 @@ export interface OauthParams { export interface AddSourceActions { initializeAddSource: (addSourceProps: AddSourceProps) => { addSourceProps: AddSourceProps }; - setAddSourceProps: ({ - addSourceProps, - }: { - addSourceProps: AddSourceProps; - }) => { + setAddSourceProps: ({ addSourceProps }: { addSourceProps: AddSourceProps }) => { addSourceProps: AddSourceProps; }; setAddSourceStep(addSourceCurrentStep: AddSourceSteps): AddSourceSteps; @@ -532,13 +528,8 @@ export const AddSourceLogic = kea = ({ name, onFormCreated, header }) => { const [formLoading, setFormLoading] = useState(false); - const { - getPreContentSourceConfigData, - setSelectedGithubOrganizations, - createContentSource, - } = useActions(AddSourceLogic); + const { getPreContentSourceConfigData, setSelectedGithubOrganizations, createContentSource } = + useActions(AddSourceLogic); const { currentServiceType, githubOrganizations, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/connect_instance.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/connect_instance.tsx index 8a632dfe1295..5428e63a101b 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/connect_instance.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/connect_instance.tsx @@ -82,9 +82,8 @@ export const ConnectInstance: React.FC = ({ setSourceIndexPermissionsValue, } = useActions(AddSourceLogic); - const { loginValue, passwordValue, indexPermissionsValue, subdomainValue } = useValues( - AddSourceLogic - ); + const { loginValue, passwordValue, indexPermissionsValue, subdomainValue } = + useValues(AddSourceLogic); const { isOrganization } = useValues(AppLogic); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/reauthenticate.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/reauthenticate.tsx index fa604ef758a4..f6c34a3eec4c 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/reauthenticate.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/reauthenticate.tsx @@ -30,7 +30,7 @@ interface ReauthenticateProps { export const Reauthenticate: React.FC = ({ name, header }) => { const { search } = useLocation() as Location; - const { sourceId } = (parseQueryParams(search) as unknown) as SourceQueryParams; + const { sourceId } = parseQueryParams(search) as unknown as SourceQueryParams; const [formLoading, setFormLoading] = useState(false); const { getSourceReConnectData } = useActions(AddSourceLogic); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/save_config.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/save_config.tsx index 053a3b6b0e6b..3320f43ed771 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/save_config.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/save_config.tsx @@ -67,13 +67,8 @@ export const SaveConfig: React.FC = ({ const { setClientIdValue, setClientSecretValue, setBaseUrlValue } = useActions(AddSourceLogic); - const { - sourceConfigData, - buttonLoading, - clientIdValue, - clientSecretValue, - baseUrlValue, - } = useValues(AddSourceLogic); + const { sourceConfigData, buttonLoading, clientIdValue, clientSecretValue, baseUrlValue } = + useValues(AddSourceLogic); const { accountContextOnly, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/display_settings.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/display_settings.tsx index ae47e20026b6..c5836dc939f2 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/display_settings.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/display_settings.tsx @@ -44,9 +44,8 @@ interface DisplaySettingsProps { } export const DisplaySettings: React.FC = ({ tabId }) => { - const { initializeDisplaySettings, setServerData, handleSelectedTabChanged } = useActions( - DisplaySettingsLogic - ); + const { initializeDisplaySettings, setServerData, handleSelectedTabChanged } = + useActions(DisplaySettingsLogic); const { dataLoading, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/field_editor_modal.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/field_editor_modal.tsx index 132adedb829a..794b54eb59f3 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/field_editor_modal.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/field_editor_modal.tsx @@ -36,9 +36,8 @@ import { DisplaySettingsLogic } from './display_settings_logic'; const emptyField = { fieldName: '', label: '' }; export const FieldEditorModal: React.FC = () => { - const { toggleFieldEditorModal, addDetailField, updateDetailField } = useActions( - DisplaySettingsLogic - ); + const { toggleFieldEditorModal, addDetailField, updateDetailField } = + useActions(DisplaySettingsLogic); const { searchResultConfig: { detailFields }, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/result_detail.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/result_detail.tsx index 6832f075476e..df80a454cc6f 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/result_detail.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/result_detail.tsx @@ -34,12 +34,8 @@ import { DisplaySettingsLogic } from './display_settings_logic'; import { ExampleResultDetailCard } from './example_result_detail_card'; export const ResultDetail: React.FC = () => { - const { - toggleFieldEditorModal, - setDetailFields, - openEditDetailField, - removeDetailField, - } = useActions(DisplaySettingsLogic); + const { toggleFieldEditorModal, setDetailFields, openEditDetailField, removeDetailField } = + useActions(DisplaySettingsLogic); const { searchResultConfig: { detailFields }, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.test.ts index 549ffe0546d7..af9d85237335 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.test.ts @@ -40,12 +40,8 @@ import { SchemaLogic, dataTypeOptions } from './schema_logic'; describe('SchemaLogic', () => { const { http } = mockHttpValues; - const { - clearFlashMessages, - flashAPIErrors, - flashSuccessToast, - setErrorMessage, - } = mockFlashMessageHelpers; + const { clearFlashMessages, flashAPIErrors, flashSuccessToast, setErrorMessage } = + mockFlashMessageHelpers; const { mount } = new LogicMounter(SchemaLogic); const defaultValues = { diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.ts index 173f5df162ca..d664197afaa2 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.ts @@ -44,13 +44,10 @@ interface SchemaActions { onSchemaSetSuccess(schemaProps: SchemaResponseProps): SchemaResponseProps; onSchemaSetFormErrors(errors: string[]): string[]; updateNewFieldType(newFieldType: SchemaType): SchemaType; - onFieldUpdate({ - schema, - formUnchanged, - }: { + onFieldUpdate({ schema, formUnchanged }: { schema: Schema; formUnchanged: boolean }): { schema: Schema; formUnchanged: boolean; - }): { schema: Schema; formUnchanged: boolean }; + }; onIndexingComplete(numDocumentsWithErrors: number): number; resetMostRecentIndexJob(emptyReindexJob: IndexJob): IndexJob; setFieldName(rawFieldName: string): string; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_added.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_added.tsx index 77b393105048..c4f97eb71845 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_added.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_added.tsx @@ -26,7 +26,7 @@ import { AddSourceLogic, OauthParams } from './add_source/add_source_logic'; */ export const SourceAdded: React.FC = () => { const { search } = useLocation() as Location; - const params = (parseQueryParams(search) as unknown) as OauthParams; + const params = parseQueryParams(search) as unknown as OauthParams; const state = JSON.parse(params.state); const isOrganization = state.context !== 'account'; const { setChromeIsVisible } = useValues(KibanaLogic); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_content.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_content.tsx index 78d4d36cf099..fdeb32573047 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_content.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_content.tsx @@ -59,9 +59,8 @@ const MAX_LENGTH = 28; export const SourceContent: React.FC = () => { const [searchTerm, setSearchTerm] = useState(''); - const { setActivePage, searchContentSourceDocuments, setContentFilterValue } = useActions( - SourceLogic - ); + const { setActivePage, searchContentSourceDocuments, setContentFilterValue } = + useActions(SourceLogic); const { contentSource: { id, serviceType, urlField, titleField, urlFieldIsLinkable, isFederatedSource }, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/private_sources.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/private_sources.tsx index 83e690fdb2a9..c9f55ff65656 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/private_sources.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/private_sources.tsx @@ -46,9 +46,8 @@ export const PrivateSources: React.FC = () => { return resetSourcesState; }, []); - const { dataLoading, contentSources, serviceTypes, privateContentSources } = useValues( - SourcesLogic - ); + const { dataLoading, contentSources, serviceTypes, privateContentSources } = + useValues(SourcesLogic); const { account: { canCreatePrivateSources, groups }, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/source_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/source_logic.test.ts index 3c926e13fe52..0d8d5684c4a4 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/source_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/source_logic.test.ts @@ -26,12 +26,8 @@ import { SourceLogic } from './source_logic'; describe('SourceLogic', () => { const { http } = mockHttpValues; - const { - clearFlashMessages, - flashAPIErrors, - flashSuccessToast, - setErrorMessage, - } = mockFlashMessageHelpers; + const { clearFlashMessages, flashAPIErrors, flashSuccessToast, setErrorMessage } = + mockFlashMessageHelpers; const { navigateToUrl } = mockKibanaValues; const { mount, getListeners } = new LogicMounter(SourceLogic); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_source_prioritization.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_source_prioritization.tsx index 76549ba1e96d..615e7b22b343 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_source_prioritization.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_source_prioritization.tsx @@ -71,9 +71,8 @@ const PRIORITY_TABLE_HEADER = i18n.translate( ); export const GroupSourcePrioritization: React.FC = () => { - const { updatePriority, saveGroupSourcePrioritization, showOrgSourcesModal } = useActions( - GroupLogic - ); + const { updatePriority, saveGroupSourcePrioritization, showOrgSourcesModal } = + useActions(GroupLogic); const { group: { contentSources = [], name: groupName }, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_logic.test.ts index 79b253dd6430..6f811ce36429 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_logic.test.ts @@ -24,12 +24,8 @@ describe('GroupLogic', () => { const { mount } = new LogicMounter(GroupLogic); const { http } = mockHttpValues; const { navigateToUrl } = mockKibanaValues; - const { - clearFlashMessages, - flashAPIErrors, - flashSuccessToast, - setQueuedErrorMessage, - } = mockFlashMessageHelpers; + const { clearFlashMessages, flashAPIErrors, flashSuccessToast, setQueuedErrorMessage } = + mockFlashMessageHelpers; const group = groups[0]; const sourceIds = ['123', '124']; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/oauth_authorize/oauth_authorize.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/oauth_authorize/oauth_authorize.tsx index 972f1951d47b..5c3114ae3199 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/oauth_authorize/oauth_authorize.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/oauth_authorize/oauth_authorize.tsx @@ -48,9 +48,8 @@ import { OAuthAuthorizeLogic } from './oauth_authorize_logic'; export const OAuthAuthorize: React.FC = () => { const { search } = useLocation() as Location; - const { initializeOAuthPreAuth, allowOAuthAuthorization, denyOAuthAuthorization } = useActions( - OAuthAuthorizeLogic - ); + const { initializeOAuthPreAuth, allowOAuthAuthorization, denyOAuthAuthorization } = + useActions(OAuthAuthorizeLogic); const { buttonLoading, dataLoading, cachedPreAuth, hasError } = useValues(OAuthAuthorizeLogic); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/organization_stats.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/organization_stats.tsx index 676ae99b02d1..00ad69fbdf37 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/organization_stats.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/organization_stats.tsx @@ -20,9 +20,8 @@ import { OverviewLogic } from './overview_logic'; import { StatisticCard } from './statistic_card'; export const OrganizationStats: React.FC = () => { - const { sourcesCount, pendingInvitationsCount, accountsCount, privateSourcesCount } = useValues( - OverviewLogic - ); + const { sourcesCount, pendingInvitationsCount, accountsCount, privateSourcesCount } = + useValues(OverviewLogic); return ( { it('handles group checkbox click', async () => { const wrapper = shallow(); await waitFor(() => - ((wrapper.find(EuiComboBox).props() as unknown) as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - }).onChange([{ label: groups[0].name, value: groups[0].name }]) + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ label: groups[0].name, value: groups[0].name }]) ); wrapper.update(); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/group_assignment_selector.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/group_assignment_selector.tsx index b53b092eced2..5d8ef7ababc8 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/group_assignment_selector.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/group_assignment_selector.tsx @@ -25,13 +25,11 @@ import { import { RoleMappingsLogic } from './role_mappings_logic'; export const GroupAssignmentSelector: React.FC = () => { - const { handleAllGroupsSelectionChange, handleGroupSelectionChange } = useActions( - RoleMappingsLogic - ); + const { handleAllGroupsSelectionChange, handleGroupSelectionChange } = + useActions(RoleMappingsLogic); - const { includeInAllGroups, availableGroups, selectedGroups, selectedOptions } = useValues( - RoleMappingsLogic - ); + const { includeInAllGroups, availableGroups, selectedGroups, selectedOptions } = + useValues(RoleMappingsLogic); const hasGroupAssignment = selectedGroups.size > 0 || includeInAllGroups; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings_logic.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings_logic.ts index 55f82a07bf40..29103aa0c39a 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings_logic.ts @@ -47,11 +47,9 @@ interface RoleMappingsActions extends RoleMappingsBaseActions { setDefaultGroup(availableGroups: RoleGroup[]): { availableGroups: RoleGroup[] }; setRoleMapping(roleMapping: WSRoleMapping): { roleMapping: WSRoleMapping }; setSingleUserRoleMapping(data?: UserMapping): { singleUserRoleMapping: UserMapping }; - setRoleMappings({ - roleMappings, - }: { + setRoleMappings({ roleMappings }: { roleMappings: WSRoleMapping[] }): { roleMappings: WSRoleMapping[]; - }): { roleMappings: WSRoleMapping[] }; + }; setRoleMappingsData(data: RoleMappingsServerDetails): RoleMappingsServerDetails; handleAllGroupsSelectionChange(selected: boolean): { selected: boolean }; handleGroupSelectionChange(groupIds: string[]): { groupIds: string[] }; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/user.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/user.tsx index 6447f43e6ed4..33785b4a4ce0 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/user.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/user.tsx @@ -24,7 +24,7 @@ import { Role } from '../../types'; import { GroupAssignmentSelector } from './group_assignment_selector'; import { RoleMappingsLogic } from './role_mappings_logic'; -const roleTypes = (['admin', 'user'] as unknown) as Role[]; +const roleTypes = ['admin', 'user'] as unknown as Role[]; export const User: React.FC = () => { const { diff --git a/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.test.ts b/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.test.ts index b5a8e205e5e1..3f2a038d8bff 100644 --- a/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.test.ts +++ b/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.test.ts @@ -114,7 +114,7 @@ describe('callEnterpriseSearchConfigAPI', () => { }); it('calls the config API endpoint', async () => { - ((fetch as unknown) as jest.Mock).mockImplementationOnce((url: string) => { + (fetch as unknown as jest.Mock).mockImplementationOnce((url: string) => { expect(url).toEqual('http://localhost:3002/api/ent/v2/internal/client_config'); return Promise.resolve(new Response(JSON.stringify(mockResponse))); }); @@ -130,7 +130,7 @@ describe('callEnterpriseSearchConfigAPI', () => { }); it('falls back without error when data is unavailable', async () => { - ((fetch as unknown) as jest.Mock).mockReturnValueOnce(Promise.resolve(new Response('{}'))); + (fetch as unknown as jest.Mock).mockReturnValueOnce(Promise.resolve(new Response('{}'))); expect(await callEnterpriseSearchConfigAPI(mockDependencies)).toEqual({ access: { @@ -198,13 +198,13 @@ describe('callEnterpriseSearchConfigAPI', () => { }); it('handles server errors', async () => { - ((fetch as unknown) as jest.Mock).mockReturnValueOnce(Promise.reject('500')); + (fetch as unknown as jest.Mock).mockReturnValueOnce(Promise.reject('500')); expect(await callEnterpriseSearchConfigAPI(mockDependencies)).toEqual({}); expect(mockDependencies.log.error).toHaveBeenCalledWith( 'Could not perform access check to Enterprise Search: 500' ); - ((fetch as unknown) as jest.Mock).mockReturnValueOnce(Promise.resolve('Bad Data')); + (fetch as unknown as jest.Mock).mockReturnValueOnce(Promise.resolve('Bad Data')); expect(await callEnterpriseSearchConfigAPI(mockDependencies)).toEqual({}); expect(mockDependencies.log.error).toHaveBeenCalledWith( 'Could not perform access check to Enterprise Search: TypeError: response.json is not a function' @@ -222,7 +222,7 @@ describe('callEnterpriseSearchConfigAPI', () => { ); // Timeout - ((fetch as unknown) as jest.Mock).mockImplementationOnce(async () => { + (fetch as unknown as jest.Mock).mockImplementationOnce(async () => { jest.advanceTimersByTime(250); return Promise.reject({ name: 'AbortError' }); }); diff --git a/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.ts b/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.ts index ba3a2e6a6480..146b06e4d9a4 100644 --- a/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.ts +++ b/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.ts @@ -124,10 +124,10 @@ export const callEnterpriseSearchConfigAPI = async ({ id: data?.current_user?.workplace_search?.account?.id, groups: data?.current_user?.workplace_search?.account?.groups || [], isAdmin: !!data?.current_user?.workplace_search?.account?.is_admin, - canCreatePrivateSources: !!data?.current_user?.workplace_search?.account - ?.can_create_private_sources, - viewedOnboardingPage: !!data?.current_user?.workplace_search?.account - ?.viewed_onboarding_page, + canCreatePrivateSources: + !!data?.current_user?.workplace_search?.account?.can_create_private_sources, + viewedOnboardingPage: + !!data?.current_user?.workplace_search?.account?.viewed_onboarding_page, }, }, }; diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.test.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.test.ts index db554d1cec93..018ab433536b 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.test.ts @@ -60,8 +60,7 @@ describe('crawler crawl rules routes', () => { jest.clearAllMocks(); mockRouter = new MockRouter({ method: 'put', - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', }); registerCrawlerCrawlRulesRoutes({ @@ -105,8 +104,7 @@ describe('crawler crawl rules routes', () => { jest.clearAllMocks(); mockRouter = new MockRouter({ method: 'delete', - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', }); registerCrawlerCrawlRulesRoutes({ diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.ts index a360129b0752..7c82c73db726 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.ts @@ -38,8 +38,7 @@ export function registerCrawlerCrawlRulesRoutes({ router.put( { - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', validate: { params: schema.object({ engineName: schema.string(), @@ -64,8 +63,7 @@ export function registerCrawlerCrawlRulesRoutes({ router.delete( { - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', validate: { params: schema.object({ engineName: schema.string(), diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.test.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.test.ts index d59a8e32045e..6fb7e9940087 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.test.ts @@ -58,8 +58,7 @@ describe('crawler entry point routes', () => { jest.clearAllMocks(); mockRouter = new MockRouter({ method: 'put', - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', }); registerCrawlerEntryPointRoutes({ @@ -100,8 +99,7 @@ describe('crawler entry point routes', () => { jest.clearAllMocks(); mockRouter = new MockRouter({ method: 'delete', - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', }); registerCrawlerEntryPointRoutes({ diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.ts index 224a79bbf6cb..a6d6fdb24b41 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.ts @@ -36,8 +36,7 @@ export function registerCrawlerEntryPointRoutes({ router.put( { - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', validate: { params: schema.object({ engineName: schema.string(), @@ -59,8 +58,7 @@ export function registerCrawlerEntryPointRoutes({ router.delete( { - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', validate: { params: schema.object({ engineName: schema.string(), diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.test.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.test.ts index 88fef87e6047..a37a8311093c 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.test.ts @@ -58,8 +58,7 @@ describe('crawler sitemap routes', () => { jest.clearAllMocks(); mockRouter = new MockRouter({ method: 'put', - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', }); registerCrawlerSitemapRoutes({ @@ -100,8 +99,7 @@ describe('crawler sitemap routes', () => { jest.clearAllMocks(); mockRouter = new MockRouter({ method: 'delete', - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', }); registerCrawlerSitemapRoutes({ diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.ts index c3ae90349b95..b63473888eec 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.ts @@ -36,8 +36,7 @@ export function registerCrawlerSitemapRoutes({ router.put( { - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', validate: { params: schema.object({ engineName: schema.string(), @@ -59,8 +58,7 @@ export function registerCrawlerSitemapRoutes({ router.delete( { - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', validate: { params: schema.object({ engineName: schema.string(), 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 1f58592ea44f..c19bb4fb916a 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 @@ -310,7 +310,7 @@ function fakeEvent(overrides = {}) { function FakeRequest(): KibanaRequest { const savedObjectGetter = jest.fn(); - return ({ + return { headers: {}, getBasePath: () => '', path: '/', @@ -324,5 +324,5 @@ function FakeRequest(): KibanaRequest { }, }, getSavedObjectsClient: () => savedObjectGetter, - } as unknown) as KibanaRequest; + } as unknown as KibanaRequest; } diff --git a/x-pack/plugins/event_log/server/event_log_start_service.test.ts b/x-pack/plugins/event_log/server/event_log_start_service.test.ts index 0815673d546b..1534623100f5 100644 --- a/x-pack/plugins/event_log/server/event_log_start_service.test.ts +++ b/x-pack/plugins/event_log/server/event_log_start_service.test.ts @@ -44,7 +44,7 @@ describe('EventLogClientService', () => { function fakeRequest(): KibanaRequest { const savedObjectsClient = savedObjectsClientMock.create(); - return ({ + return { headers: {}, getBasePath: () => '', path: '/', @@ -58,5 +58,5 @@ function fakeRequest(): KibanaRequest { }, }, getSavedObjectsClient: () => savedObjectsClient, - } as unknown) as KibanaRequest; + } as unknown as KibanaRequest; } diff --git a/x-pack/plugins/event_log/server/event_logger.test.ts b/x-pack/plugins/event_log/server/event_logger.test.ts index 9dcfa37ae76b..d90fd93c6004 100644 --- a/x-pack/plugins/event_log/server/event_logger.test.ts +++ b/x-pack/plugins/event_log/server/event_logger.test.ts @@ -188,7 +188,7 @@ describe('EventLogger', () => { service.registerProviderActions('provider', ['action-a']); eventLogger = service.getLogger({}); - eventLogger.logEvent(({ event: { PROVIDER: 'provider' } } as unknown) as IEvent); + eventLogger.logEvent({ event: { PROVIDER: 'provider' } } as unknown as IEvent); let message = await waitForLogMessage(systemLogger); expect(message).toMatch(/invalid event logged.*provider.*undefined.*/); diff --git a/x-pack/plugins/event_log/server/routes/_mock_handler_arguments.ts b/x-pack/plugins/event_log/server/routes/_mock_handler_arguments.ts index 7563359e2dd1..3cd8e5eaae2b 100644 --- a/x-pack/plugins/event_log/server/routes/_mock_handler_arguments.ts +++ b/x-pack/plugins/event_log/server/routes/_mock_handler_arguments.ts @@ -18,13 +18,13 @@ export function mockHandlerArguments( res?: Array> ): [RequestHandlerContext, KibanaRequest, KibanaResponseFactory] { return [ - ({ + { eventLog: { getEventLogClient() { return eventLogClient; }, }, - } as unknown) as RequestHandlerContext, + } as unknown as RequestHandlerContext, req as KibanaRequest, mockResponseFactory(res), ]; @@ -39,7 +39,7 @@ export const mockResponseFactory = (resToMock: Array { - return ({ + return { registerProvider: jest.fn(), registerDefaultProvider: jest.fn(), getProvidersClient: jest.fn(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; }; export const savedObjectProviderRegistryMock = { diff --git a/x-pack/plugins/event_log/server/saved_object_provider_registry.test.ts b/x-pack/plugins/event_log/server/saved_object_provider_registry.test.ts index c9a7d4f85515..d3b4ec4648b9 100644 --- a/x-pack/plugins/event_log/server/saved_object_provider_registry.test.ts +++ b/x-pack/plugins/event_log/server/saved_object_provider_registry.test.ts @@ -83,7 +83,7 @@ describe('SavedObjectProviderRegistry', () => { function fakeRequest(): KibanaRequest { const savedObjectsClient = savedObjectsClientMock.create(); - return ({ + return { headers: {}, getBasePath: () => '', path: '/', @@ -97,5 +97,5 @@ function fakeRequest(): KibanaRequest { }, }, getSavedObjectsClient: () => savedObjectsClient, - } as unknown) as KibanaRequest; + } as unknown as KibanaRequest; } diff --git a/x-pack/plugins/features/server/feature_privilege_iterator/sub_feature_privilege_iterator.ts b/x-pack/plugins/features/server/feature_privilege_iterator/sub_feature_privilege_iterator.ts index 4e4364333883..8dffd553bfe1 100644 --- a/x-pack/plugins/features/server/feature_privilege_iterator/sub_feature_privilege_iterator.ts +++ b/x-pack/plugins/features/server/feature_privilege_iterator/sub_feature_privilege_iterator.ts @@ -19,17 +19,18 @@ export type SubFeaturePrivilegeIterator = ( licenseHasAtLeast: (licenseType: LicenseType) => boolean | undefined ) => IterableIterator; -const subFeaturePrivilegeIterator: SubFeaturePrivilegeIterator = function* subFeaturePrivilegeIterator( - feature: KibanaFeature, - licenseHasAtLeast: (licenseType: LicenseType) => boolean | undefined -): IterableIterator { - for (const subFeature of feature.subFeatures) { - for (const group of subFeature.privilegeGroups) { - yield* group.privileges.filter( - (privilege) => !privilege.minimumLicense || licenseHasAtLeast(privilege.minimumLicense) - ); +const subFeaturePrivilegeIterator: SubFeaturePrivilegeIterator = + function* subFeaturePrivilegeIterator( + feature: KibanaFeature, + licenseHasAtLeast: (licenseType: LicenseType) => boolean | undefined + ): IterableIterator { + for (const subFeature of feature.subFeatures) { + for (const group of subFeature.privilegeGroups) { + yield* group.privileges.filter( + (privilege) => !privilege.minimumLicense || licenseHasAtLeast(privilege.minimumLicense) + ); + } } - } -}; + }; export { subFeaturePrivilegeIterator }; diff --git a/x-pack/plugins/features/server/feature_schema.ts b/x-pack/plugins/features/server/feature_schema.ts index 96d79982afcf..2694620c62d3 100644 --- a/x-pack/plugins/features/server/feature_schema.ts +++ b/x-pack/plugins/features/server/feature_schema.ts @@ -152,11 +152,10 @@ const kibanaIndependentSubFeaturePrivilegeSchema = schema.object({ ui: listOfCapabilitiesSchema, }); -const kibanaMutuallyExclusiveSubFeaturePrivilegeSchema = kibanaIndependentSubFeaturePrivilegeSchema.extends( - { +const kibanaMutuallyExclusiveSubFeaturePrivilegeSchema = + kibanaIndependentSubFeaturePrivilegeSchema.extends({ minimumLicense: schema.never(), - } -); + }); const kibanaSubFeatureSchema = schema.object({ name: schema.string(), diff --git a/x-pack/plugins/features/server/plugin.ts b/x-pack/plugins/features/server/plugin.ts index c1fbc4b8a5ed..b11c77b60e66 100644 --- a/x-pack/plugins/features/server/plugin.ts +++ b/x-pack/plugins/features/server/plugin.ts @@ -85,8 +85,8 @@ export interface PluginStartContract { * Represents Features Plugin instance that will be managed by the Kibana plugin system. */ export class FeaturesPlugin - implements - Plugin, RecursiveReadonly> { + implements Plugin, RecursiveReadonly> +{ private readonly logger: Logger; private readonly featureRegistry: FeatureRegistry = new FeatureRegistry(); private isReportingEnabled: boolean = false; diff --git a/x-pack/plugins/file_upload/public/components/json_upload_and_parse.tsx b/x-pack/plugins/file_upload/public/components/json_upload_and_parse.tsx index 28e99e7ffb18..1fd96544918c 100644 --- a/x-pack/plugins/file_upload/public/components/json_upload_and_parse.tsx +++ b/x-pack/plugins/file_upload/public/components/json_upload_and_parse.tsx @@ -100,9 +100,9 @@ export class JsonUploadAndParse extends Component { + > +{ public setup() {} public start(core: CoreStart, plugins: FileUploadStartDependencies): FileUploadStartApi { diff --git a/x-pack/plugins/file_upload/server/capabilities.test.ts b/x-pack/plugins/file_upload/server/capabilities.test.ts index 2fc666c83796..53f9da26060a 100644 --- a/x-pack/plugins/file_upload/server/capabilities.test.ts +++ b/x-pack/plugins/file_upload/server/capabilities.test.ts @@ -61,7 +61,7 @@ describe('setupCapabilities', () => { const security = securityMock.createStart(); security.authz.mode.useRbacForRequest.mockReturnValue(true); coreSetup.getStartServices.mockResolvedValue([ - (undefined as unknown) as CoreStart, + undefined as unknown as CoreStart, { security }, undefined, ]); @@ -104,7 +104,7 @@ describe('setupCapabilities', () => { const mockCheckPrivileges = jest.fn().mockResolvedValue({ hasAllRequested: false }); security.authz.checkPrivilegesDynamicallyWithRequest.mockReturnValue(mockCheckPrivileges); coreSetup.getStartServices.mockResolvedValue([ - (undefined as unknown) as CoreStart, + undefined as unknown as CoreStart, { security }, undefined, ]); @@ -146,7 +146,7 @@ describe('setupCapabilities', () => { const mockCheckPrivileges = jest.fn().mockResolvedValue({ hasAllRequested: true }); security.authz.checkPrivilegesDynamicallyWithRequest.mockReturnValue(mockCheckPrivileges); coreSetup.getStartServices.mockResolvedValue([ - (undefined as unknown) as CoreStart, + undefined as unknown as CoreStart, { security }, undefined, ]); @@ -192,7 +192,7 @@ describe('setupCapabilities', () => { .mockRejectedValue(new Error('this should not have been called')); security.authz.checkPrivilegesDynamicallyWithRequest.mockReturnValue(mockCheckPrivileges); coreSetup.getStartServices.mockResolvedValue([ - (undefined as unknown) as CoreStart, + undefined as unknown as CoreStart, { security }, undefined, ]); @@ -229,7 +229,7 @@ describe('setupCapabilities', () => { const security = securityMock.createStart(); security.authz.mode.useRbacForRequest.mockReturnValue(false); coreSetup.getStartServices.mockResolvedValue([ - (undefined as unknown) as CoreStart, + undefined as unknown as CoreStart, { security }, undefined, ]); diff --git a/x-pack/plugins/file_upload/server/routes.ts b/x-pack/plugins/file_upload/server/routes.ts index c957916e7f32..cb7c37a586b6 100644 --- a/x-pack/plugins/file_upload/server/routes.ts +++ b/x-pack/plugins/file_upload/server/routes.ts @@ -187,9 +187,8 @@ export function fileUploadRoutes(coreSetup: CoreSetup, logge }, async (context, request, response) => { try { - const { - body: indexExists, - } = await context.core.elasticsearch.client.asCurrentUser.indices.exists(request.body); + const { body: indexExists } = + await context.core.elasticsearch.client.asCurrentUser.indices.exists(request.body); return response.ok({ body: { exists: indexExists } }); } catch (e) { return response.customError(wrapError(e)); diff --git a/x-pack/plugins/fleet/common/constants/package_policy.ts b/x-pack/plugins/fleet/common/constants/package_policy.ts index f1d6f00d0577..42bbe5bb5b79 100644 --- a/x-pack/plugins/fleet/common/constants/package_policy.ts +++ b/x-pack/plugins/fleet/common/constants/package_policy.ts @@ -6,3 +6,5 @@ */ export const PACKAGE_POLICY_SAVED_OBJECT_TYPE = 'ingest-package-policies'; + +export const PACKAGE_POLICY_DEFAULT_INDEX_PRIVILEGES = ['auto_configure', 'create_doc']; diff --git a/x-pack/plugins/fleet/common/services/decode_cloud_id.ts b/x-pack/plugins/fleet/common/services/decode_cloud_id.ts index e4952e6b2235..2afc15e8f71b 100644 --- a/x-pack/plugins/fleet/common/services/decode_cloud_id.ts +++ b/x-pack/plugins/fleet/common/services/decode_cloud_id.ts @@ -6,9 +6,7 @@ */ // decodeCloudId decodes the c.id into c.esURL and c.kibURL -export function decodeCloudId( - cid: string -): +export function decodeCloudId(cid: string): | { host: string; defaultPort: string; diff --git a/x-pack/plugins/fleet/common/services/package_to_package_policy.test.ts b/x-pack/plugins/fleet/common/services/package_to_package_policy.test.ts index 0e5cab08edfb..275cf237a962 100644 --- a/x-pack/plugins/fleet/common/services/package_to_package_policy.test.ts +++ b/x-pack/plugins/fleet/common/services/package_to_package_policy.test.ts @@ -58,25 +58,25 @@ describe('Fleet - packageToPackagePolicy', () => { it('returns empty array for packages with a config template but no inputs', () => { expect( - packageToPackagePolicyInputs(({ + packageToPackagePolicyInputs({ ...mockPackage, policy_templates: [{ name: 'test_template', inputs: [] }], - } as unknown) as PackageInfo) + } as unknown as PackageInfo) ).toEqual([]); }); it('returns inputs with no streams for packages with no streams', () => { expect( - packageToPackagePolicyInputs(({ + packageToPackagePolicyInputs({ ...mockPackage, policy_templates: [{ name: 'test_template', inputs: [{ type: 'foo' }] }], - } as unknown) as PackageInfo) + } as unknown as PackageInfo) ).toEqual([{ type: 'foo', enabled: true, policy_template: 'test_template', streams: [] }]); expect( - packageToPackagePolicyInputs(({ + packageToPackagePolicyInputs({ ...mockPackage, policy_templates: [{ name: 'test_template', inputs: [{ type: 'foo' }, { type: 'bar' }] }], - } as unknown) as PackageInfo) + } as unknown as PackageInfo) ).toEqual([ { type: 'foo', enabled: true, policy_template: 'test_template', streams: [] }, { type: 'bar', enabled: true, policy_template: 'test_template', streams: [] }, @@ -85,7 +85,7 @@ describe('Fleet - packageToPackagePolicy', () => { it('returns inputs with streams for packages with streams', () => { expect( - packageToPackagePolicyInputs(({ + packageToPackagePolicyInputs({ ...mockPackage, data_streams: [ { type: 'logs', dataset: 'foo', streams: [{ input: 'foo' }] }, @@ -93,7 +93,7 @@ describe('Fleet - packageToPackagePolicy', () => { { type: 'logs', dataset: 'bar2', streams: [{ input: 'bar' }] }, ], policy_templates: [{ name: 'test_template', inputs: [{ type: 'foo' }, { type: 'bar' }] }], - } as unknown) as PackageInfo) + } as unknown as PackageInfo) ).toEqual([ { type: 'foo', @@ -127,7 +127,7 @@ describe('Fleet - packageToPackagePolicy', () => { it('returns inputs with streams configurations for packages with stream vars', () => { expect( - packageToPackagePolicyInputs(({ + packageToPackagePolicyInputs({ ...mockPackage, data_streams: [ { @@ -157,7 +157,7 @@ describe('Fleet - packageToPackagePolicy', () => { }, ], policy_templates: [{ name: 'test_template', inputs: [{ type: 'foo' }, { type: 'bar' }] }], - } as unknown) as PackageInfo) + } as unknown as PackageInfo) ).toEqual([ { type: 'foo', @@ -193,7 +193,7 @@ describe('Fleet - packageToPackagePolicy', () => { it('returns inputs with streams configurations for packages with stream and input vars', () => { expect( - packageToPackagePolicyInputs(({ + packageToPackagePolicyInputs({ ...mockPackage, data_streams: [ { @@ -268,7 +268,7 @@ describe('Fleet - packageToPackagePolicy', () => { ], }, ], - } as unknown) as PackageInfo) + } as unknown as PackageInfo) ).toEqual([ { type: 'foo', @@ -399,10 +399,10 @@ describe('Fleet - packageToPackagePolicy', () => { }); it('returns package policy with inputs', () => { - const mockPackageWithPolicyTemplates = ({ + const mockPackageWithPolicyTemplates = { ...mockPackage, policy_templates: [{ inputs: [{ type: 'foo' }] }], - } as unknown) as PackageInfo; + } as unknown as PackageInfo; expect( packageToPackagePolicy(mockPackageWithPolicyTemplates, '1', '2', 'default', 'pkgPolicy-1') @@ -424,7 +424,7 @@ describe('Fleet - packageToPackagePolicy', () => { it('returns package policy with multiple policy templates (aka has integrations', () => { expect( packageToPackagePolicy( - (AWS_PACKAGE as unknown) as PackageInfo, + AWS_PACKAGE as unknown as PackageInfo, 'some-agent-policy-id', 'some-output-id', 'default', diff --git a/x-pack/plugins/fleet/common/services/validate_package_policy.test.ts b/x-pack/plugins/fleet/common/services/validate_package_policy.test.ts index 30bd9f071feb..306d31879e0c 100644 --- a/x-pack/plugins/fleet/common/services/validate_package_policy.test.ts +++ b/x-pack/plugins/fleet/common/services/validate_package_policy.test.ts @@ -15,7 +15,7 @@ import { AWS_PACKAGE, INVALID_AWS_POLICY, VALID_AWS_POLICY } from './fixtures/aw describe('Fleet - validatePackagePolicy()', () => { describe('works for packages with single policy template (aka no integrations)', () => { - const mockPackage = ({ + const mockPackage = { name: 'mock-package', title: 'Mock package', version: '0.0.0', @@ -152,7 +152,7 @@ describe('Fleet - validatePackagePolicy()', () => { ], }, ], - } as unknown) as PackageInfo; + } as unknown as PackageInfo; const validPackagePolicy: NewPackagePolicy = { name: 'pkgPolicy1-1', @@ -544,7 +544,7 @@ describe('Fleet - validatePackagePolicy()', () => { validPackagePolicy, { ...mockPackage, - policy_templates: [({ inputs: [] } as unknown) as RegistryPolicyTemplate], + policy_templates: [{ inputs: [] } as unknown as RegistryPolicyTemplate], }, safeLoad ) @@ -562,7 +562,7 @@ describe('Fleet - validatePackagePolicy()', () => { expect( validatePackagePolicy( INVALID_AWS_POLICY as NewPackagePolicy, - (AWS_PACKAGE as unknown) as PackageInfo, + AWS_PACKAGE as unknown as PackageInfo, safeLoad ) ).toMatchSnapshot(); @@ -573,7 +573,7 @@ describe('Fleet - validatePackagePolicy()', () => { validationHasErrors( validatePackagePolicy( VALID_AWS_POLICY as NewPackagePolicy, - (AWS_PACKAGE as unknown) as PackageInfo, + AWS_PACKAGE as unknown as PackageInfo, safeLoad ) ) diff --git a/x-pack/plugins/fleet/common/types/models/epm.ts b/x-pack/plugins/fleet/common/types/models/epm.ts index bbb571f963dc..66852bc965b0 100644 --- a/x-pack/plugins/fleet/common/types/models/epm.ts +++ b/x-pack/plugins/fleet/common/types/models/epm.ts @@ -281,7 +281,6 @@ export enum RegistryDataStreamKeys { ingest_pipeline = 'ingest_pipeline', elasticsearch = 'elasticsearch', dataset_is_prefix = 'dataset_is_prefix', - permissions = 'permissions', } export interface RegistryDataStream { @@ -297,15 +296,15 @@ export interface RegistryDataStream { [RegistryDataStreamKeys.ingest_pipeline]?: string; [RegistryDataStreamKeys.elasticsearch]?: RegistryElasticsearch; [RegistryDataStreamKeys.dataset_is_prefix]?: boolean; - [RegistryDataStreamKeys.permissions]?: RegistryDataStreamPermissions; } export interface RegistryElasticsearch { + privileges?: RegistryDataStreamPrivileges; 'index_template.settings'?: estypes.IndicesIndexSettings; 'index_template.mappings'?: estypes.MappingTypeMapping; } -export interface RegistryDataStreamPermissions { +export interface RegistryDataStreamPrivileges { cluster?: string[]; indices?: string[]; } diff --git a/x-pack/plugins/fleet/common/types/models/package_policy.ts b/x-pack/plugins/fleet/common/types/models/package_policy.ts index ab977c5d67d0..aca537ae31b5 100644 --- a/x-pack/plugins/fleet/common/types/models/package_policy.ts +++ b/x-pack/plugins/fleet/common/types/models/package_policy.ts @@ -25,6 +25,11 @@ export interface NewPackagePolicyInputStream { data_stream: { dataset: string; type: string; + elasticsearch?: { + privileges?: { + indices?: string[]; + }; + }; }; vars?: PackagePolicyConfigRecord; config?: PackagePolicyConfigRecord; diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/package_policy_input_panel.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/package_policy_input_panel.tsx index bce48d3108aa..050177850818 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/package_policy_input_panel.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/package_policy_input_panel.tsx @@ -86,9 +86,10 @@ export const PackagePolicyInputPanel: React.FunctionComponent<{ const errorCount = countValidationErrors(inputValidationResults); const hasErrors = forceShowErrors && errorCount; - const hasInputStreams = useMemo(() => packageInputStreams.length > 0, [ - packageInputStreams.length, - ]); + const hasInputStreams = useMemo( + () => packageInputStreams.length > 0, + [packageInputStreams.length] + ); const inputStreams = useMemo( () => packageInputStreams diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx index 5e00bce5d6c6..a83f6902ed05 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx @@ -91,9 +91,10 @@ export const CreatePackagePolicyPage: React.FunctionComponent = () => { const { search } = useLocation(); const queryParams = useMemo(() => new URLSearchParams(search), [search]); - const queryParamsPolicyId = useMemo(() => queryParams.get('policyId') ?? undefined, [ - queryParams, - ]); + const queryParamsPolicyId = useMemo( + () => queryParams.get('policyId') ?? undefined, + [queryParams] + ); /** * Please note: policyId can come from one of two sources. The URL param (in the URL path) or diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_select_agent_policy.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_select_agent_policy.tsx index e2f5a7249ff0..63cf1a0c87b2 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_select_agent_policy.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_select_agent_policy.tsx @@ -65,9 +65,8 @@ export const StepSelectAgentPolicy: React.FunctionComponent<{ // Create new agent policy flyout state const hasWriteCapabilites = useCapabilities().write; - const [isCreateAgentPolicyFlyoutOpen, setIsCreateAgentPolicyFlyoutOpen] = useState( - false - ); + const [isCreateAgentPolicyFlyoutOpen, setIsCreateAgentPolicyFlyoutOpen] = + useState(false); // Fetch package info const { diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/details_page/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/details_page/index.tsx index 9d3fe64b6639..eec7d80b75c4 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/details_page/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/details_page/index.tsx @@ -312,7 +312,7 @@ export const AgentPolicyDetailsPage: React.FunctionComponent = () => { {content} diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx index 040070bcff7c..d887076568a6 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx @@ -97,9 +97,8 @@ export const EditPackagePolicyForm = memo<{ inputs: [], version: '', }); - const [originalPackagePolicy, setOriginalPackagePolicy] = useState< - GetOnePackagePolicyResponse['item'] - >(); + const [originalPackagePolicy, setOriginalPackagePolicy] = + useState(); const [dryRunData, setDryRunData] = useState(); const policyId = agentPolicy?.id ?? ''; @@ -110,10 +109,8 @@ export const EditPackagePolicyForm = memo<{ setIsLoadingData(true); setLoadingError(undefined); try { - const { - data: packagePolicyData, - error: packagePolicyError, - } = await sendGetOnePackagePolicy(packagePolicyId); + const { data: packagePolicyData, error: packagePolicyError } = + await sendGetOnePackagePolicy(packagePolicyId); if (packagePolicyError) { throw packagePolicyError; diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/list_page/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/list_page/index.tsx index 10859e32f008..b940086effea 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/list_page/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/list_page/index.tsx @@ -78,7 +78,11 @@ export const AgentPolicyListPage: React.FunctionComponent<{}> = () => { ); // Fetch agent policies - const { isLoading, data: agentPolicyData, resendRequest } = useGetAgentPolicies({ + const { + isLoading, + data: agentPolicyData, + resendRequest, + } = useGetAgentPolicies({ page: pagination.currentPage, perPage: pagination.pageSize, sortField: sorting?.field, diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/agent_logs.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/agent_logs.tsx index f927bdcc2e51..783a960aff12 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/agent_logs.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/agent_logs.tsx @@ -245,9 +245,10 @@ export const AgentLogsUI: React.FunctionComponent = memo( // Set absolute height on logs component (needed to render correctly in Safari) // based on available height, or 600px, whichever is greater const [logsPanelRef, { height: measuredlogPanelHeight }] = useMeasure(); - const logPanelHeight = useMemo(() => Math.max(measuredlogPanelHeight, 600), [ - measuredlogPanelHeight, - ]); + const logPanelHeight = useMemo( + () => Math.max(measuredlogPanelHeight, 600), + [measuredlogPanelHeight] + ); if (!isLogFeatureAvailable) { return ( diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/index.tsx index c138d23cce93..5411e6313ebb 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/index.tsx @@ -22,59 +22,58 @@ import { DEFAULT_LOGS_STATE, STATE_STORAGE_KEY } from './constants'; import type { AgentLogsProps, AgentLogsState } from './agent_logs'; import { AgentLogsUI, AgentLogsUrlStateHelper } from './agent_logs'; -export const AgentLogs: React.FunctionComponent< - Pick -> = memo(({ agent, agentPolicy }) => { - const stateContainer = useMemo( - () => - createStateContainer< - AgentLogsState, - { - update: PureTransition]>; - } - >( - { - ...DEFAULT_LOGS_STATE, - ...getStateFromKbnUrl(STATE_STORAGE_KEY, window.location.href, { - getFromHashQuery: false, - }), - }, - { - update: (state) => (updatedState) => ({ ...state, ...updatedState }), - } - ), - [] - ); +export const AgentLogs: React.FunctionComponent> = + memo(({ agent, agentPolicy }) => { + const stateContainer = useMemo( + () => + createStateContainer< + AgentLogsState, + { + update: PureTransition]>; + } + >( + { + ...DEFAULT_LOGS_STATE, + ...getStateFromKbnUrl(STATE_STORAGE_KEY, window.location.href, { + getFromHashQuery: false, + }), + }, + { + update: (state) => (updatedState) => ({ ...state, ...updatedState }), + } + ), + [] + ); - const AgentLogsConnected = useMemo( - () => - AgentLogsUrlStateHelper.connect((state) => ({ - state: state || DEFAULT_LOGS_STATE, - }))(AgentLogsUI), - [] - ); + const AgentLogsConnected = useMemo( + () => + AgentLogsUrlStateHelper.connect((state) => ({ + state: state || DEFAULT_LOGS_STATE, + }))(AgentLogsUI), + [] + ); - const [isSyncReady, setIsSyncReady] = useState(false); + const [isSyncReady, setIsSyncReady] = useState(false); - useEffect(() => { - const stateStorage = createKbnUrlStateStorage(); - const { start, stop } = syncState({ - storageKey: STATE_STORAGE_KEY, - stateContainer: stateContainer as INullableBaseStateContainer, - stateStorage, - }); - start(); - setIsSyncReady(true); + useEffect(() => { + const stateStorage = createKbnUrlStateStorage(); + const { start, stop } = syncState({ + storageKey: STATE_STORAGE_KEY, + stateContainer: stateContainer as INullableBaseStateContainer, + stateStorage, + }); + start(); + setIsSyncReady(true); - return () => { - stop(); - stateContainer.set(DEFAULT_LOGS_STATE); - }; - }, [stateContainer]); + return () => { + stop(); + stateContainer.set(DEFAULT_LOGS_STATE); + }; + }, [stateContainer]); - return ( - - {isSyncReady ? : null} - - ); -}); + return ( + + {isSyncReady ? : null} + + ); + }); diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/index.tsx index d2342dafca2e..f3430110ba28 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/index.tsx @@ -254,7 +254,7 @@ export const AgentDetailsPage: React.FunctionComponent = () => { {isLoading && isInitialRequest ? ( diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/index.tsx index 494541a00fc0..18a684baad60 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/index.tsx @@ -39,9 +39,10 @@ export const AgentsApp: React.FunctionComponent = () => { perPage: 1000, }); - const agentPolicies = useMemo(() => agentPoliciesRequest.data?.items || [], [ - agentPoliciesRequest.data, - ]); + const agentPolicies = useMemo( + () => agentPoliciesRequest.data?.items || [], + [agentPoliciesRequest.data] + ); const fleetStatus = useFleetStatus(); diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx index f0630f89c898..fadcbdd70c28 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx @@ -124,9 +124,11 @@ export function Detail() { semverLt(packageInfo.savedObject.attributes.version, packageInfo.latestVersion); // Fetch package info - const { data: packageInfoData, error: packageInfoError, isLoading } = useGetPackageInfoByKey( - pkgkey - ); + const { + data: packageInfoData, + error: packageInfoError, + isLoading, + } = useGetPackageInfoByKey(pkgkey); const showCustomTab = useUIExtension(packageInfoData?.response.name ?? '', 'package-detail-custom') !== undefined; diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/overview/overview.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/overview/overview.tsx index 945859ac81ff..0b477fee2ba7 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/overview/overview.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/overview/overview.tsx @@ -27,10 +27,10 @@ const LeftColumn = styled(EuiFlexItem)` `; export const OverviewPage: React.FC = memo(({ packageInfo, integrationInfo }) => { - const screenshots = useMemo(() => integrationInfo?.screenshots || packageInfo.screenshots || [], [ - integrationInfo, - packageInfo.screenshots, - ]); + const screenshots = useMemo( + () => integrationInfo?.screenshots || packageInfo.screenshots || [], + [integrationInfo, packageInfo.screenshots] + ); return ( diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/package_policies.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/package_policies.tsx index 07a61410e9a6..92b4012011fc 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/package_policies.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/package_policies.tsx @@ -84,9 +84,10 @@ export const PackagePoliciesPage = ({ name, version }: PackagePoliciesPanelProps const { search } = useLocation(); const history = useHistory(); const queryParams = useMemo(() => new URLSearchParams(search), [search]); - const agentPolicyIdFromParams = useMemo(() => queryParams.get('addAgentToPolicyId'), [ - queryParams, - ]); + const agentPolicyIdFromParams = useMemo( + () => queryParams.get('addAgentToPolicyId'), + [queryParams] + ); const [flyoutOpenForPolicyId, setFlyoutOpenForPolicyId] = useState( agentPolicyIdFromParams ); @@ -94,7 +95,11 @@ export const PackagePoliciesPage = ({ name, version }: PackagePoliciesPanelProps const getPackageInstallStatus = useGetPackageInstallStatus(); const packageInstallStatus = getPackageInstallStatus(name); const { pagination, pageSizeOptions, setPagination } = useUrlPagination(); - const { data, isLoading, resendRequest: refreshPolicies } = usePackagePoliciesWithAgentPolicy({ + const { + data, + isLoading, + resendRequest: refreshPolicies, + } = usePackagePoliciesWithAgentPolicy({ page: pagination.currentPage, perPage: pagination.pageSize, kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: ${name}`, diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/use_package_policies_with_agent_policy.ts b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/use_package_policies_with_agent_policy.ts index 33c1d3ff7730..4f6f456bf82c 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/use_package_policies_with_agent_policy.ts +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/use_package_policies_with_agent_policy.ts @@ -74,18 +74,16 @@ export const usePackagePoliciesWithAgentPolicy = ( .join(' or ')}) `; }, [packagePoliciesData]); - const { - data: agentPoliciesData, - isLoading: isLoadingAgentPolicies, - } = useConditionalRequest({ - path: agentPolicyRouteService.getListPath(), - method: 'get', - query: { - perPage: 100, - kuery: agentPoliciesFilter, - }, - shouldSendRequest: !!packagePoliciesData?.items.length, - } as SendConditionalRequestConfig); + const { data: agentPoliciesData, isLoading: isLoadingAgentPolicies } = + useConditionalRequest({ + path: agentPolicyRouteService.getListPath(), + method: 'get', + query: { + perPage: 100, + kuery: agentPoliciesFilter, + }, + shouldSendRequest: !!packagePoliciesData?.items.length, + } as SendConditionalRequestConfig); const [enrichedData, setEnrichedData] = useState(); diff --git a/x-pack/plugins/fleet/public/components/agent_policy_package_badges.tsx b/x-pack/plugins/fleet/public/components/agent_policy_package_badges.tsx index 02518945cf7a..9db4f77a02c3 100644 --- a/x-pack/plugins/fleet/public/components/agent_policy_package_badges.tsx +++ b/x-pack/plugins/fleet/public/components/agent_policy_package_badges.tsx @@ -84,33 +84,42 @@ export const AgentPolicyPackageBadges: React.FunctionComponent = ({ )} - {packages.map((pkg, idx) => { - return ( - - - - - // this collides with some EuiText (+img) CSS from the EuiIcon component - // which makes the button large, wide, and poorly layed out - // override those styles until the bug is fixed or we find a better approach - { margin: 'unset', width: '16px' } - } - /> - - {pkg.title} - - - ); - })} + + {packages.map((pkg, idx) => { + return ( + + + + + + // this collides with some EuiText (+img) CSS from the EuiIcon component + // which makes the button large, wide, and poorly layed out + // override those styles until the bug is fixed or we find a better approach + { margin: 'unset', width: '16px' } + } + /> + + {pkg.title} + + + + ); + })} + {showFleetServerWarning && ( <> diff --git a/x-pack/plugins/fleet/public/components/package_icon.tsx b/x-pack/plugins/fleet/public/components/package_icon.tsx index bb84a7905697..df0bd9864b60 100644 --- a/x-pack/plugins/fleet/public/components/package_icon.tsx +++ b/x-pack/plugins/fleet/public/components/package_icon.tsx @@ -12,9 +12,8 @@ import { EuiIcon } from '@elastic/eui'; import type { UsePackageIconType } from '../hooks'; import { usePackageIconType } from '../hooks'; -export const PackageIcon: React.FunctionComponent< - UsePackageIconType & Omit -> = ({ packageName, integrationName, version, icons, tryApi, ...euiIconProps }) => { - const iconType = usePackageIconType({ packageName, integrationName, version, icons, tryApi }); - return ; -}; +export const PackageIcon: React.FunctionComponent> = + ({ packageName, integrationName, version, icons, tryApi, ...euiIconProps }) => { + const iconType = usePackageIconType({ packageName, integrationName, version, icons, tryApi }); + return ; + }; diff --git a/x-pack/plugins/fleet/public/components/package_policy_delete_provider.tsx b/x-pack/plugins/fleet/public/components/package_policy_delete_provider.tsx index 86f064405497..e2522f40ef96 100644 --- a/x-pack/plugins/fleet/public/components/package_policy_delete_provider.tsx +++ b/x-pack/plugins/fleet/public/components/package_policy_delete_provider.tsx @@ -63,15 +63,16 @@ export const PackagePolicyDeleteProvider: React.FunctionComponent = ({ ); const deletePackagePoliciesPrompt = useMemo( - (): DeletePackagePoliciesPrompt => (packagePoliciesToDelete, onSuccess = () => undefined) => { - if (!Array.isArray(packagePoliciesToDelete) || packagePoliciesToDelete.length === 0) { - throw new Error('No package policies specified for deletion'); - } - setIsModalOpen(true); - setPackagePolicies(packagePoliciesToDelete); - fetchAgentsCount(); - onSuccessCallback.current = onSuccess; - }, + (): DeletePackagePoliciesPrompt => + (packagePoliciesToDelete, onSuccess = () => undefined) => { + if (!Array.isArray(packagePoliciesToDelete) || packagePoliciesToDelete.length === 0) { + throw new Error('No package policies specified for deletion'); + } + setIsModalOpen(true); + setPackagePolicies(packagePoliciesToDelete); + fetchAgentsCount(); + onSuccessCallback.current = onSuccess; + }, [fetchAgentsCount] ); diff --git a/x-pack/plugins/fleet/public/constants/page_paths.ts b/x-pack/plugins/fleet/public/constants/page_paths.ts index 93ef0d56b17a..e430e58d297f 100644 --- a/x-pack/plugins/fleet/public/constants/page_paths.ts +++ b/x-pack/plugins/fleet/public/constants/page_paths.ts @@ -81,10 +81,9 @@ export const INTEGRATIONS_ROUTING_PATHS = { export const pagePathGetters: { [key in StaticPage]: () => [string, string]; -} & - { - [key in DynamicPage]: (values: DynamicPagePathValues) => [string, string]; - } = { +} & { + [key in DynamicPage]: (values: DynamicPagePathValues) => [string, string]; +} = { base: () => [FLEET_BASE_PATH, '/'], overview: () => [FLEET_BASE_PATH, '/'], integrations: () => [INTEGRATIONS_BASE_PATH, '/'], diff --git a/x-pack/plugins/fleet/public/services/ui_extensions.test.ts b/x-pack/plugins/fleet/public/services/ui_extensions.test.ts index d23219c1f653..779fd28ebcd1 100644 --- a/x-pack/plugins/fleet/public/services/ui_extensions.test.ts +++ b/x-pack/plugins/fleet/public/services/ui_extensions.test.ts @@ -31,7 +31,7 @@ describe('UI Extension services', () => { it('should store an extension points', () => { const LazyCustomView = lazy(async () => { - return { default: ((() => {}) as unknown) as PackagePolicyEditExtensionComponent }; + return { default: (() => {}) as unknown as PackagePolicyEditExtensionComponent }; }); register({ view: 'package-policy-edit', @@ -48,10 +48,10 @@ describe('UI Extension services', () => { it('should throw if extension point has already registered', () => { const LazyCustomView = lazy(async () => { - return { default: ((() => {}) as unknown) as PackagePolicyEditExtensionComponent }; + return { default: (() => {}) as unknown as PackagePolicyEditExtensionComponent }; }); const LazyCustomView2 = lazy(async () => { - return { default: ((() => {}) as unknown) as PackagePolicyEditExtensionComponent }; + return { default: (() => {}) as unknown as PackagePolicyEditExtensionComponent }; }); register({ diff --git a/x-pack/plugins/fleet/public/types/ui_extensions.ts b/x-pack/plugins/fleet/public/types/ui_extensions.ts index 40e92fe86555..d365b798fe83 100644 --- a/x-pack/plugins/fleet/public/types/ui_extensions.ts +++ b/x-pack/plugins/fleet/public/types/ui_extensions.ts @@ -22,7 +22,8 @@ export interface UIExtensionsStorage { * UI Component Extension is used on the pages displaying the ability to edit an * Integration Policy */ -export type PackagePolicyEditExtensionComponent = ComponentType; +export type PackagePolicyEditExtensionComponent = + ComponentType; export interface PackagePolicyEditExtensionComponentProps { /** The current integration policy being edited */ @@ -66,7 +67,8 @@ export interface PackagePolicyEditTabsExtension { * UI Component Extension is used on the pages displaying the ability to Create an * Integration Policy */ -export type PackagePolicyCreateExtensionComponent = ComponentType; +export type PackagePolicyCreateExtensionComponent = + ComponentType; export interface PackagePolicyCreateExtensionComponentProps { /** The integration policy being created */ diff --git a/x-pack/plugins/fleet/server/collectors/agent_collectors.ts b/x-pack/plugins/fleet/server/collectors/agent_collectors.ts index 716c81573e85..43c15e603a87 100644 --- a/x-pack/plugins/fleet/server/collectors/agent_collectors.ts +++ b/x-pack/plugins/fleet/server/collectors/agent_collectors.ts @@ -37,14 +37,8 @@ export const getAgentUsage = async ( }; } - const { - total, - inactive, - online, - error, - offline, - updating, - } = await AgentService.getAgentStatusForAgentPolicy(esClient); + const { total, inactive, online, error, offline, updating } = + await AgentService.getAgentStatusForAgentPolicy(esClient); return { total_enrolled: total, healthy: online, diff --git a/x-pack/plugins/fleet/server/constants/index.ts b/x-pack/plugins/fleet/server/constants/index.ts index 28f3ea96f732..0dcd5e7f4780 100644 --- a/x-pack/plugins/fleet/server/constants/index.ts +++ b/x-pack/plugins/fleet/server/constants/index.ts @@ -49,6 +49,7 @@ export { DEFAULT_FLEET_SERVER_AGENT_POLICY, DEFAULT_OUTPUT, DEFAULT_PACKAGES, + PACKAGE_POLICY_DEFAULT_INDEX_PRIVILEGES, // Fleet Server index FLEET_SERVER_SERVERS_INDEX, ENROLLMENT_API_KEYS_INDEX, diff --git a/x-pack/plugins/fleet/server/index.test.ts b/x-pack/plugins/fleet/server/index.test.ts index 924fecc31107..659c7d2761d0 100644 --- a/x-pack/plugins/fleet/server/index.test.ts +++ b/x-pack/plugins/fleet/server/index.test.ts @@ -21,7 +21,9 @@ const applyConfigDeprecations = (settings: Record = {}) => { deprecation, path: '', })), - () => ({ message }) => deprecationMessages.push(message) + () => + ({ message }) => + deprecationMessages.push(message) ); return { messages: deprecationMessages, diff --git a/x-pack/plugins/fleet/server/plugin.ts b/x-pack/plugins/fleet/server/plugin.ts index 9991f4ee2098..6aad028666ee 100644 --- a/x-pack/plugins/fleet/server/plugin.ts +++ b/x-pack/plugins/fleet/server/plugin.ts @@ -159,7 +159,8 @@ export interface FleetStartContract { } export class FleetPlugin - implements AsyncPlugin { + implements AsyncPlugin +{ private licensing$!: Observable; private config$: Observable; private configInitialValue: FleetConfigType; diff --git a/x-pack/plugins/fleet/server/routes/agent/actions_handlers.test.ts b/x-pack/plugins/fleet/server/routes/agent/actions_handlers.test.ts index 3f300aef692f..b31cda7cbf61 100644 --- a/x-pack/plugins/fleet/server/routes/agent/actions_handlers.test.ts +++ b/x-pack/plugins/fleet/server/routes/agent/actions_handlers.test.ts @@ -73,13 +73,13 @@ describe('test actions handlers', () => { const mockRequest = httpServerMock.createKibanaRequest(postNewAgentActionRequest); - const agentAction = ({ + const agentAction = { type: 'POLICY_CHANGE', id: 'action1', sent_at: '2020-03-14T19:45:02.620Z', timestamp: '2019-01-04T14:32:03.36764-05:00', created_at: '2020-03-14T19:45:02.620Z', - } as unknown) as AgentAction; + } as unknown as AgentAction; const actionsService: ActionsService = { getAgent: jest.fn().mockReturnValueOnce({ @@ -90,7 +90,7 @@ describe('test actions handlers', () => { const postNewAgentActionHandler = postNewAgentActionHandlerBuilder(actionsService); await postNewAgentActionHandler( - ({ + { core: { savedObjects: { client: mockSavedObjectsClient, @@ -101,13 +101,13 @@ describe('test actions handlers', () => { }, }, }, - } as unknown) as RequestHandlerContext, + } as unknown as RequestHandlerContext, mockRequest, mockResponse ); - const expectedAgentActionResponse = (mockResponse.ok.mock.calls[0][0] - ?.body as unknown) as PostNewAgentActionResponse; + const expectedAgentActionResponse = mockResponse.ok.mock.calls[0][0] + ?.body as unknown as PostNewAgentActionResponse; expect(expectedAgentActionResponse.item).toEqual(agentAction); }); diff --git a/x-pack/plugins/fleet/server/routes/agent/handlers.ts b/x-pack/plugins/fleet/server/routes/agent/handlers.ts index fd4721309eeb..14b26d2c7ba8 100644 --- a/x-pack/plugins/fleet/server/routes/agent/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/agent/handlers.ts @@ -28,53 +28,51 @@ import { defaultIngestErrorHandler } from '../../errors'; import { licenseService } from '../../services'; import * as AgentService from '../../services/agents'; -export const getAgentHandler: RequestHandler< - TypeOf -> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - const esClient = context.core.elasticsearch.client.asCurrentUser; +export const getAgentHandler: RequestHandler> = + async (context, request, response) => { + const soClient = context.core.savedObjects.client; + const esClient = context.core.elasticsearch.client.asCurrentUser; + + try { + const body: GetOneAgentResponse = { + item: await AgentService.getAgentById(esClient, request.params.agentId), + }; - try { - const body: GetOneAgentResponse = { - item: await AgentService.getAgentById(esClient, request.params.agentId), - }; + return response.ok({ body }); + } catch (error) { + if (soClient.errors.isNotFoundError(error)) { + return response.notFound({ + body: { message: `Agent ${request.params.agentId} not found` }, + }); + } - return response.ok({ body }); - } catch (error) { - if (soClient.errors.isNotFoundError(error)) { - return response.notFound({ - body: { message: `Agent ${request.params.agentId} not found` }, - }); + return defaultIngestErrorHandler({ error, response }); } + }; - return defaultIngestErrorHandler({ error, response }); - } -}; +export const deleteAgentHandler: RequestHandler> = + async (context, request, response) => { + const esClient = context.core.elasticsearch.client.asCurrentUser; -export const deleteAgentHandler: RequestHandler< - TypeOf -> = async (context, request, response) => { - const esClient = context.core.elasticsearch.client.asCurrentUser; + try { + await AgentService.deleteAgent(esClient, request.params.agentId); - try { - await AgentService.deleteAgent(esClient, request.params.agentId); + const body = { + action: 'deleted', + }; - const body = { - action: 'deleted', - }; + return response.ok({ body }); + } catch (error) { + if (error.isBoom) { + return response.customError({ + statusCode: error.output.statusCode, + body: { message: `Agent ${request.params.agentId} not found` }, + }); + } - return response.ok({ body }); - } catch (error) { - if (error.isBoom) { - return response.customError({ - statusCode: error.output.statusCode, - body: { message: `Agent ${request.params.agentId} not found` }, - }); + return defaultIngestErrorHandler({ error, response }); } - - return defaultIngestErrorHandler({ error, response }); - } -}; + }; export const updateAgentHandler: RequestHandler< TypeOf, diff --git a/x-pack/plugins/fleet/server/routes/output/handler.ts b/x-pack/plugins/fleet/server/routes/output/handler.ts index ebd3d213d33c..0c56d55423e4 100644 --- a/x-pack/plugins/fleet/server/routes/output/handler.ts +++ b/x-pack/plugins/fleet/server/routes/output/handler.ts @@ -31,28 +31,27 @@ export const getOutputsHandler: RequestHandler = async (context, request, respon } }; -export const getOneOuputHandler: RequestHandler< - TypeOf -> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - try { - const output = await outputService.get(soClient, request.params.outputId); +export const getOneOuputHandler: RequestHandler> = + async (context, request, response) => { + const soClient = context.core.savedObjects.client; + try { + const output = await outputService.get(soClient, request.params.outputId); - const body: GetOneOutputResponse = { - item: output, - }; + const body: GetOneOutputResponse = { + item: output, + }; - return response.ok({ body }); - } catch (error) { - if (error.isBoom && error.output.statusCode === 404) { - return response.notFound({ - body: { message: `Output ${request.params.outputId} not found` }, - }); - } + return response.ok({ body }); + } catch (error) { + if (error.isBoom && error.output.statusCode === 404) { + return response.notFound({ + body: { message: `Output ${request.params.outputId} not found` }, + }); + } - return defaultIngestErrorHandler({ error, response }); - } -}; + return defaultIngestErrorHandler({ error, response }); + } + }; export const putOuputHandler: RequestHandler< TypeOf, diff --git a/x-pack/plugins/fleet/server/routes/package_policy/handlers.test.ts b/x-pack/plugins/fleet/server/routes/package_policy/handlers.test.ts index fb28c7e2f515..729417fa9606 100644 --- a/x-pack/plugins/fleet/server/routes/package_policy/handlers.test.ts +++ b/x-pack/plugins/fleet/server/routes/package_policy/handlers.test.ts @@ -28,51 +28,54 @@ type PackagePolicyServicePublicInterface = Omit< const packagePolicyServiceMock = packagePolicyService as jest.Mocked; -jest.mock('../../services/package_policy', (): { - packagePolicyService: jest.Mocked; -} => { - return { - packagePolicyService: { - compilePackagePolicyInputs: jest.fn((packageInfo, vars, dataInputs) => - Promise.resolve(dataInputs) - ), - buildPackagePolicyFromPackage: jest.fn(), - bulkCreate: jest.fn(), - create: jest.fn((soClient, esClient, newData) => - Promise.resolve({ - ...newData, - inputs: newData.inputs.map((input) => ({ - ...input, - streams: input.streams.map((stream) => ({ - id: stream.data_stream.dataset, - ...stream, +jest.mock( + '../../services/package_policy', + (): { + packagePolicyService: jest.Mocked; + } => { + return { + packagePolicyService: { + compilePackagePolicyInputs: jest.fn((packageInfo, vars, dataInputs) => + Promise.resolve(dataInputs) + ), + buildPackagePolicyFromPackage: jest.fn(), + bulkCreate: jest.fn(), + create: jest.fn((soClient, esClient, newData) => + Promise.resolve({ + ...newData, + inputs: newData.inputs.map((input) => ({ + ...input, + streams: input.streams.map((stream) => ({ + id: stream.data_stream.dataset, + ...stream, + })), })), - })), - id: '1', - revision: 1, - updated_at: new Date().toISOString(), - updated_by: 'elastic', - created_at: new Date().toISOString(), - created_by: 'elastic', - }) - ), - delete: jest.fn(), - get: jest.fn(), - getByIDs: jest.fn(), - list: jest.fn(), - listIds: jest.fn(), - update: jest.fn(), - // @ts-ignore - runExternalCallbacks: jest.fn((callbackType, packagePolicy, context, request) => - callbackType === 'postPackagePolicyDelete' - ? Promise.resolve(undefined) - : Promise.resolve(packagePolicy) - ), - upgrade: jest.fn(), - getUpgradeDryRunDiff: jest.fn(), - }, - }; -}); + id: '1', + revision: 1, + updated_at: new Date().toISOString(), + updated_by: 'elastic', + created_at: new Date().toISOString(), + created_by: 'elastic', + }) + ), + delete: jest.fn(), + get: jest.fn(), + getByIDs: jest.fn(), + list: jest.fn(), + listIds: jest.fn(), + update: jest.fn(), + // @ts-ignore + runExternalCallbacks: jest.fn((callbackType, packagePolicy, context, request) => + callbackType === 'postPackagePolicyDelete' + ? Promise.resolve(undefined) + : Promise.resolve(packagePolicy) + ), + upgrade: jest.fn(), + getUpgradeDryRunDiff: jest.fn(), + }, + }; + } +); jest.mock('../../services/epm/packages', () => { return { diff --git a/x-pack/plugins/fleet/server/saved_objects/index.ts b/x-pack/plugins/fleet/server/saved_objects/index.ts index 449a1984aa53..5c117909432b 100644 --- a/x-pack/plugins/fleet/server/saved_objects/index.ts +++ b/x-pack/plugins/fleet/server/saved_objects/index.ts @@ -251,6 +251,11 @@ const getSavedObjectTypes = ( properties: { dataset: { type: 'keyword' }, type: { type: 'keyword' }, + elasticsearch: { + properties: { + privileges: { type: 'flattened' }, + }, + }, }, }, vars: { type: 'flattened' }, diff --git a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_11_0.ts b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_11_0.ts index 0c7b20ed2826..c17a167184b4 100644 --- a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_11_0.ts +++ b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_11_0.ts @@ -13,9 +13,8 @@ import type { PackagePolicy } from '../../../../common'; export const migratePackagePolicyToV7110: SavedObjectMigrationFn = ( packagePolicyDoc ) => { - const updatedPackagePolicyDoc: SavedObjectUnsanitizedDoc = cloneDeep( - packagePolicyDoc - ); + const updatedPackagePolicyDoc: SavedObjectUnsanitizedDoc = + cloneDeep(packagePolicyDoc); if (packagePolicyDoc.attributes.package?.name === 'endpoint') { const input = updatedPackagePolicyDoc.attributes.inputs[0]; const popup = { diff --git a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_12_0.ts b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_12_0.ts index 9d961af74a12..4fc8c15044e8 100644 --- a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_12_0.ts +++ b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_12_0.ts @@ -13,9 +13,8 @@ import type { PackagePolicy } from '../../../../common'; export const migratePackagePolicyToV7120: SavedObjectMigrationFn = ( packagePolicyDoc ) => { - const updatedPackagePolicyDoc: SavedObjectUnsanitizedDoc = cloneDeep( - packagePolicyDoc - ); + const updatedPackagePolicyDoc: SavedObjectUnsanitizedDoc = + cloneDeep(packagePolicyDoc); if (packagePolicyDoc.attributes.package?.name === 'endpoint') { const input = updatedPackagePolicyDoc.attributes.inputs[0]; const ransomware = { diff --git a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_14_0.ts b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_14_0.ts index 2f281bcf86a9..a56ef1337514 100644 --- a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_14_0.ts +++ b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_14_0.ts @@ -14,9 +14,8 @@ export const migrateEndpointPackagePolicyToV7140: SavedObjectMigrationFn< PackagePolicy, PackagePolicy > = (packagePolicyDoc) => { - const updatedPackagePolicyDoc: SavedObjectUnsanitizedDoc = cloneDeep( - packagePolicyDoc - ); + const updatedPackagePolicyDoc: SavedObjectUnsanitizedDoc = + cloneDeep(packagePolicyDoc); if (packagePolicyDoc.attributes.package?.name === 'endpoint') { const input = updatedPackagePolicyDoc.attributes.inputs[0]; if (input && input.config) { diff --git a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_15_0.ts b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_15_0.ts index 9ccafc58989f..7f96cda58946 100644 --- a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_15_0.ts +++ b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_15_0.ts @@ -17,9 +17,8 @@ export const migratePackagePolicyToV7150: SavedObjectMigrationFn = cloneDeep( - packagePolicyDoc - ); + const updatedPackagePolicyDoc: SavedObjectUnsanitizedDoc = + cloneDeep(packagePolicyDoc); const input = updatedPackagePolicyDoc.attributes.inputs[0]; const memory = { diff --git a/x-pack/plugins/fleet/server/services/agent_policy.test.ts b/x-pack/plugins/fleet/server/services/agent_policy.test.ts index 3267b2b7e266..59e0f6fd7840 100644 --- a/x-pack/plugins/fleet/server/services/agent_policy.test.ts +++ b/x-pack/plugins/fleet/server/services/agent_policy.test.ts @@ -70,7 +70,7 @@ jest.mock('./agents'); jest.mock('./package_policy'); function getAgentPolicyUpdateMock() { - return (agentPolicyUpdateEventHandler as unknown) as jest.Mock< + return agentPolicyUpdateEventHandler as unknown as jest.Mock< typeof agentPolicyUpdateEventHandler >; } @@ -79,7 +79,7 @@ function getAgentPolicyCreateMock() { const soClient = savedObjectsClientMock.create(); soClient.create.mockImplementation(async (type, attributes) => { return { - attributes: (attributes as unknown) as NewAgentPolicy, + attributes: attributes as unknown as NewAgentPolicy, id: 'mocked', type: 'mocked', references: [], diff --git a/x-pack/plugins/fleet/server/services/agent_policy.ts b/x-pack/plugins/fleet/server/services/agent_policy.ts index 8539db05ffb5..38fb07754bdd 100644 --- a/x-pack/plugins/fleet/server/services/agent_policy.ts +++ b/x-pack/plugins/fleet/server/services/agent_policy.ts @@ -21,6 +21,7 @@ import { AGENT_POLICY_SAVED_OBJECT_TYPE, AGENT_SAVED_OBJECT_TYPE, PRECONFIGURATION_DELETION_RECORD_SAVED_OBJECT_TYPE, + PACKAGE_POLICY_DEFAULT_INDEX_PRIVILEGES, } from '../constants'; import type { PackagePolicy, @@ -617,14 +618,15 @@ class AgentPolicyService { } if (agentPolicy.package_policies && agentPolicy.package_policies.length) { - const deletedPackagePolicies: DeletePackagePoliciesResponse = await packagePolicyService.delete( - soClient, - esClient, - agentPolicy.package_policies as string[], - { - skipUnassignFromAgentPolicies: true, - } - ); + const deletedPackagePolicies: DeletePackagePoliciesResponse = + await packagePolicyService.delete( + soClient, + esClient, + agentPolicy.package_policies as string[], + { + skipUnassignFromAgentPolicies: true, + } + ); try { await packagePolicyService.runDeleteExternalCallbacks(deletedPackagePolicies); } catch (error) { @@ -677,7 +679,7 @@ class AgentPolicyService { '@timestamp': new Date().toISOString(), revision_idx: fullPolicy.revision, coordinator_idx: 0, - data: (fullPolicy as unknown) as FleetServerPolicy['data'], + data: fullPolicy as unknown as FleetServerPolicy['data'], policy_id: fullPolicy.id, default_fleet_server: policy.is_default_fleet_server === true, }; @@ -824,7 +826,7 @@ class AgentPolicyService { permissions._elastic_agent_checks.indices = [ { names, - privileges: ['auto_configure', 'create_doc'], + privileges: PACKAGE_POLICY_DEFAULT_INDEX_PRIVILEGES, }, ]; } diff --git a/x-pack/plugins/fleet/server/services/agent_policy_update.ts b/x-pack/plugins/fleet/server/services/agent_policy_update.ts index fe3a3907b9d2..9703467d84c1 100644 --- a/x-pack/plugins/fleet/server/services/agent_policy_update.ts +++ b/x-pack/plugins/fleet/server/services/agent_policy_update.ts @@ -13,7 +13,7 @@ import { unenrollForAgentPolicyId } from './agents'; import { agentPolicyService } from './agent_policy'; import { appContextService } from './app_context'; -const fakeRequest = ({ +const fakeRequest = { headers: {}, getBasePath: () => '', path: '/', @@ -26,7 +26,7 @@ const fakeRequest = ({ url: '/', }, }, -} as unknown) as KibanaRequest; +} as unknown as KibanaRequest; export async function agentPolicyUpdateEventHandler( soClient: SavedObjectsClientContract, diff --git a/x-pack/plugins/fleet/server/services/agents/crud.ts b/x-pack/plugins/fleet/server/services/agents/crud.ts index 2a69f983ec89..03647c52e05f 100644 --- a/x-pack/plugins/fleet/server/services/agents/crud.ts +++ b/x-pack/plugins/fleet/server/services/agents/crud.ts @@ -29,25 +29,29 @@ function _joinFilters(filters: Array): KueryNode try { return filters .filter((filter) => filter !== undefined) - .reduce((acc: KueryNode | undefined, kuery: string | KueryNode | undefined): - | KueryNode - | undefined => { - if (kuery === undefined) { - return acc; - } - const kueryNode: KueryNode = - typeof kuery === 'string' ? fromKueryExpression(removeSOAttributes(kuery)) : kuery; - - if (!acc) { - return kueryNode; - } - - return { - type: 'function', - function: 'and', - arguments: [acc, kueryNode], - }; - }, undefined as KueryNode | undefined); + .reduce( + ( + acc: KueryNode | undefined, + kuery: string | KueryNode | undefined + ): KueryNode | undefined => { + if (kuery === undefined) { + return acc; + } + const kueryNode: KueryNode = + typeof kuery === 'string' ? fromKueryExpression(removeSOAttributes(kuery)) : kuery; + + if (!acc) { + return kueryNode; + } + + return { + type: 'function', + function: 'and', + arguments: [acc, kueryNode], + }; + }, + undefined as KueryNode | undefined + ); } catch (err) { throw new IngestManagerError(`Kuery is malformed: ${err.message}`); } diff --git a/x-pack/plugins/fleet/server/services/agents/crud_so.ts b/x-pack/plugins/fleet/server/services/agents/crud_so.ts index 246c91bbef51..aa3cb4e4ec1a 100644 --- a/x-pack/plugins/fleet/server/services/agents/crud_so.ts +++ b/x-pack/plugins/fleet/server/services/agents/crud_so.ts @@ -25,27 +25,31 @@ const INACTIVE_AGENT_CONDITION = `NOT (${ACTIVE_AGENT_CONDITION})`; function _joinFilters(filters: Array) { return filters .filter((filter) => filter !== undefined) - .reduce((acc: KueryNode | undefined, kuery: string | KueryNode | undefined): - | KueryNode - | undefined => { - if (kuery === undefined) { - return acc; - } - const kueryNode: KueryNode = - typeof kuery === 'string' - ? fromKueryExpression(normalizeKuery(AGENT_SAVED_OBJECT_TYPE, kuery)) - : kuery; - - if (!acc) { - return kueryNode; - } - - return { - type: 'function', - function: 'and', - arguments: [acc, kueryNode], - }; - }, undefined as KueryNode | undefined); + .reduce( + ( + acc: KueryNode | undefined, + kuery: string | KueryNode | undefined + ): KueryNode | undefined => { + if (kuery === undefined) { + return acc; + } + const kueryNode: KueryNode = + typeof kuery === 'string' + ? fromKueryExpression(normalizeKuery(AGENT_SAVED_OBJECT_TYPE, kuery)) + : kuery; + + if (!acc) { + return kueryNode; + } + + return { + type: 'function', + function: 'and', + arguments: [acc, kueryNode], + }; + }, + undefined as KueryNode | undefined + ); } export async function listAgents( diff --git a/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts b/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts index b666a1678ea6..cc2357351f6d 100644 --- a/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts +++ b/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts @@ -22,7 +22,8 @@ import { escapeSearchQueryPhrase } from '../saved_object'; import { invalidateAPIKeys } from './security'; -const uuidRegex = /^\([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}\)$/; +const uuidRegex = + /^\([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}\)$/; export async function listEnrollmentApiKeys( esClient: ElasticsearchClient, diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/default_settings.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/default_settings.ts index 2dced977229e..e7fccb22566a 100644 --- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/default_settings.ts +++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/default_settings.ts @@ -53,9 +53,10 @@ export function buildDefaultSettings({ `large amount of default fields detected for index template ${templateName} in package ${packageName}, applying the first ${QUERY_DEFAULT_FIELD_LIMIT} fields` ); } - const defaultFieldNames = (defaultFields.length > QUERY_DEFAULT_FIELD_LIMIT - ? defaultFields.slice(0, QUERY_DEFAULT_FIELD_LIMIT) - : defaultFields + const defaultFieldNames = ( + defaultFields.length > QUERY_DEFAULT_FIELD_LIMIT + ? defaultFields.slice(0, QUERY_DEFAULT_FIELD_LIMIT) + : defaultFields ).map((field) => field.name); return { diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts index 6febd27286ad..34dcd5427d65 100644 --- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts +++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts @@ -50,7 +50,7 @@ describe('test transform install', () => { }); test('can install new versions and removes older version', async () => { - const previousInstallation: Installation = ({ + const previousInstallation: Installation = { installed_es: [ { id: 'metrics-endpoint.policy-0.16.0-dev.0', @@ -61,9 +61,9 @@ describe('test transform install', () => { type: ElasticsearchAssetType.transform, }, ], - } as unknown) as Installation; + } as unknown as Installation; - const currentInstallation: Installation = ({ + const currentInstallation: Installation = { installed_es: [ { id: 'metrics-endpoint.policy-0.16.0-dev.0', @@ -82,7 +82,7 @@ describe('test transform install', () => { type: ElasticsearchAssetType.transform, }, ], - } as unknown) as Installation; + } as unknown as Installation; (getAsset as jest.MockedFunction) .mockReturnValueOnce(Buffer.from('{"content": "data"}', 'utf8')) .mockReturnValueOnce(Buffer.from('{"content": "data"}', 'utf8')); @@ -91,14 +91,14 @@ describe('test transform install', () => { .mockReturnValueOnce(Promise.resolve(previousInstallation)) .mockReturnValueOnce(Promise.resolve(currentInstallation)); - (getInstallationObject as jest.MockedFunction< - typeof getInstallationObject - >).mockReturnValueOnce( - Promise.resolve(({ + ( + getInstallationObject as jest.MockedFunction + ).mockReturnValueOnce( + Promise.resolve({ attributes: { installed_es: previousInstallation.installed_es, }, - } as unknown) as SavedObject) + } as unknown as SavedObject) ); esClient.transform.getTransform.mockReturnValueOnce( @@ -115,7 +115,7 @@ describe('test transform install', () => { ); await installTransform( - ({ + { name: 'endpoint', version: '0.16.0-dev.0', data_streams: [ @@ -148,7 +148,7 @@ describe('test transform install', () => { path: 'metadata_current', }, ], - } as unknown) as RegistryPackage, + } as unknown as RegistryPackage, [ 'endpoint-0.16.0-dev.0/data_stream/policy/elasticsearch/ingest_pipeline/default.json', 'endpoint-0.16.0-dev.0/elasticsearch/transform/metadata/default.json', @@ -275,18 +275,18 @@ describe('test transform install', () => { }); test('can install new version and when no older version', async () => { - const previousInstallation: Installation = ({ + const previousInstallation: Installation = { installed_es: [], - } as unknown) as Installation; + } as unknown as Installation; - const currentInstallation: Installation = ({ + const currentInstallation: Installation = { installed_es: [ { id: 'metrics-endpoint.metadata-current-default-0.16.0-dev.0', type: ElasticsearchAssetType.transform, }, ], - } as unknown) as Installation; + } as unknown as Installation; (getAsset as jest.MockedFunction).mockReturnValueOnce( Buffer.from('{"content": "data"}', 'utf8') ); @@ -294,16 +294,16 @@ describe('test transform install', () => { .mockReturnValueOnce(Promise.resolve(previousInstallation)) .mockReturnValueOnce(Promise.resolve(currentInstallation)); - (getInstallationObject as jest.MockedFunction< - typeof getInstallationObject - >).mockReturnValueOnce( - Promise.resolve(({ + ( + getInstallationObject as jest.MockedFunction + ).mockReturnValueOnce( + Promise.resolve({ attributes: { installed_es: [] }, - } as unknown) as SavedObject) + } as unknown as SavedObject) ); await installTransform( - ({ + { name: 'endpoint', version: '0.16.0-dev.0', data_streams: [ @@ -322,7 +322,7 @@ describe('test transform install', () => { path: 'metadata_current', }, ], - } as unknown) as RegistryPackage, + } as unknown as RegistryPackage, ['endpoint-0.16.0-dev.0/elasticsearch/transform/metadata_current/default.json'], esClient, savedObjectsClient @@ -360,29 +360,29 @@ describe('test transform install', () => { }); test('can removes older version when no new install in package', async () => { - const previousInstallation: Installation = ({ + const previousInstallation: Installation = { installed_es: [ { id: 'endpoint.metadata-current-default-0.15.0-dev.0', type: ElasticsearchAssetType.transform, }, ], - } as unknown) as Installation; + } as unknown as Installation; - const currentInstallation: Installation = ({ + const currentInstallation: Installation = { installed_es: [], - } as unknown) as Installation; + } as unknown as Installation; (getInstallation as jest.MockedFunction) .mockReturnValueOnce(Promise.resolve(previousInstallation)) .mockReturnValueOnce(Promise.resolve(currentInstallation)); - (getInstallationObject as jest.MockedFunction< - typeof getInstallationObject - >).mockReturnValueOnce( - Promise.resolve(({ + ( + getInstallationObject as jest.MockedFunction + ).mockReturnValueOnce( + Promise.resolve({ attributes: { installed_es: currentInstallation.installed_es }, - } as unknown) as SavedObject) + } as unknown as SavedObject) ); esClient.transform.getTransform.mockReturnValueOnce( @@ -399,7 +399,7 @@ describe('test transform install', () => { ); await installTransform( - ({ + { name: 'endpoint', version: '0.16.0-dev.0', data_streams: [ @@ -432,7 +432,7 @@ describe('test transform install', () => { path: 'metadata_current', }, ], - } as unknown) as RegistryPackage, + } as unknown as RegistryPackage, [], esClient, savedObjectsClient @@ -489,18 +489,18 @@ describe('test transform install', () => { }); test('ignore already exists error if saved object and ES transforms are out of sync', async () => { - const previousInstallation: Installation = ({ + const previousInstallation: Installation = { installed_es: [], - } as unknown) as Installation; + } as unknown as Installation; - const currentInstallation: Installation = ({ + const currentInstallation: Installation = { installed_es: [ { id: 'metrics-endpoint.metadata-current-default-0.16.0-dev.0', type: ElasticsearchAssetType.transform, }, ], - } as unknown) as Installation; + } as unknown as Installation; (getAsset as jest.MockedFunction).mockReturnValueOnce( Buffer.from('{"content": "data"}', 'utf8') ); @@ -508,12 +508,12 @@ describe('test transform install', () => { .mockReturnValueOnce(Promise.resolve(previousInstallation)) .mockReturnValueOnce(Promise.resolve(currentInstallation)); - (getInstallationObject as jest.MockedFunction< - typeof getInstallationObject - >).mockReturnValueOnce( - Promise.resolve(({ + ( + getInstallationObject as jest.MockedFunction + ).mockReturnValueOnce( + Promise.resolve({ attributes: { installed_es: [] }, - } as unknown) as SavedObject) + } as unknown as SavedObject) ); esClient.transport.request.mockImplementationOnce(() => @@ -528,7 +528,7 @@ describe('test transform install', () => { ); await installTransform( - ({ + { name: 'endpoint', version: '0.16.0-dev.0', data_streams: [ @@ -547,7 +547,7 @@ describe('test transform install', () => { path: 'metadata_current', }, ], - } as unknown) as RegistryPackage, + } as unknown as RegistryPackage, ['endpoint-0.16.0-dev.0/elasticsearch/transform/metadata_current/default.json'], esClient, savedObjectsClient diff --git a/x-pack/plugins/fleet/server/services/fleet_server/saved_object_migrations.ts b/x-pack/plugins/fleet/server/services/fleet_server/saved_object_migrations.ts index 5c05ed7532ac..379bc8fa39bf 100644 --- a/x-pack/plugins/fleet/server/services/fleet_server/saved_object_migrations.ts +++ b/x-pack/plugins/fleet/server/services/fleet_server/saved_object_migrations.ts @@ -33,7 +33,7 @@ export async function runFleetServerMigration() { } function getInternalUserSOClient() { - const fakeRequest = ({ + const fakeRequest = { headers: {}, getBasePath: () => '', path: '/', @@ -46,7 +46,7 @@ function getInternalUserSOClient() { url: '/', }, }, - } as unknown) as KibanaRequest; + } as unknown as KibanaRequest; return appContextService.getInternalUserSOClient(fakeRequest); } @@ -74,9 +74,7 @@ async function migrateAgents() { for (const so of res.saved_objects) { try { - const { - attributes, - } = await appContextService + const { attributes } = await appContextService .getEncryptedSavedObjects() .getDecryptedAsInternalUser(AGENT_SAVED_OBJECT_TYPE, so.id); diff --git a/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.test.ts b/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.test.ts index a84118cdf1bf..9f8ac01afe6c 100644 --- a/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.test.ts +++ b/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.test.ts @@ -13,7 +13,7 @@ import type { PackagePolicy, RegistryDataStream } from '../types'; import { getPackageInfo } from './epm/packages'; import { - getDataStreamPermissions, + getDataStreamPrivileges, storedPackagePoliciesToAgentPermissions, } from './package_policies_to_agent_permissions'; @@ -380,12 +380,12 @@ describe('storedPackagePoliciesToAgentPermissions()', () => { }); }); -describe('getDataStreamPermissions()', () => { - it('returns defaults for a datastream with no permissions', () => { +describe('getDataStreamPrivileges()', () => { + it('returns defaults for a datastream with no privileges', () => { const dataStream = { type: 'logs', dataset: 'test' } as RegistryDataStream; - const permissions = getDataStreamPermissions(dataStream); + const privileges = getDataStreamPrivileges(dataStream); - expect(permissions).toMatchObject({ + expect(privileges).toMatchObject({ names: ['logs-test-*'], privileges: ['auto_configure', 'create_doc'], }); @@ -393,9 +393,9 @@ describe('getDataStreamPermissions()', () => { it('adds the namespace to the index name', () => { const dataStream = { type: 'logs', dataset: 'test' } as RegistryDataStream; - const permissions = getDataStreamPermissions(dataStream, 'namespace'); + const privileges = getDataStreamPrivileges(dataStream, 'namespace'); - expect(permissions).toMatchObject({ + expect(privileges).toMatchObject({ names: ['logs-test-namespace'], privileges: ['auto_configure', 'create_doc'], }); @@ -407,9 +407,9 @@ describe('getDataStreamPermissions()', () => { dataset: 'test', dataset_is_prefix: true, } as RegistryDataStream; - const permissions = getDataStreamPermissions(dataStream, 'namespace'); + const privileges = getDataStreamPrivileges(dataStream, 'namespace'); - expect(permissions).toMatchObject({ + expect(privileges).toMatchObject({ names: ['logs-test.*-namespace'], privileges: ['auto_configure', 'create_doc'], }); @@ -421,25 +421,27 @@ describe('getDataStreamPermissions()', () => { dataset: 'test', hidden: true, } as RegistryDataStream; - const permissions = getDataStreamPermissions(dataStream, 'namespace'); + const privileges = getDataStreamPrivileges(dataStream, 'namespace'); - expect(permissions).toMatchObject({ + expect(privileges).toMatchObject({ names: ['.logs-test-namespace'], privileges: ['auto_configure', 'create_doc'], }); }); - it('uses custom permissions if they are present in the datastream', () => { + it('uses custom privileges if they are present in the datastream', () => { const dataStream = { type: 'logs', dataset: 'test', - permissions: { indices: ['read', 'write'] }, + elasticsearch: { + privileges: { indices: ['read', 'monitor'] }, + }, } as RegistryDataStream; - const permissions = getDataStreamPermissions(dataStream, 'namespace'); + const privileges = getDataStreamPrivileges(dataStream, 'namespace'); - expect(permissions).toMatchObject({ + expect(privileges).toMatchObject({ names: ['logs-test-namespace'], - privileges: ['read', 'write'], + privileges: ['read', 'monitor'], }); }); }); diff --git a/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.ts b/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.ts index 07ad892adc65..22dcb8ac7b4c 100644 --- a/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.ts +++ b/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.ts @@ -6,9 +6,9 @@ */ import type { SavedObjectsClientContract } from 'kibana/server'; -import type { FullAgentPolicyOutputPermissions, RegistryDataStreamPermissions } from '../../common'; +import type { FullAgentPolicyOutputPermissions, RegistryDataStreamPrivileges } from '../../common'; +import { PACKAGE_POLICY_DEFAULT_INDEX_PRIVILEGES } from '../constants'; import { getPackageInfo } from '../../server/services/epm/packages'; - import type { PackagePolicy } from '../types'; export const DEFAULT_PERMISSIONS = { @@ -22,7 +22,7 @@ export const DEFAULT_PERMISSIONS = { 'synthetics-*', '.logs-endpoint.diagnostic.collection-*', ], - privileges: ['auto_configure', 'create_doc'], + privileges: PACKAGE_POLICY_DEFAULT_INDEX_PRIVILEGES, }, ], }; @@ -104,12 +104,16 @@ export async function storedPackagePoliciesToAgentPermissions( return; } - const ds = { + const ds: DataStreamMeta = { type: stream.data_stream.type, dataset: stream.compiled_stream?.data_stream?.dataset ?? stream.data_stream.dataset, }; + if (stream.data_stream.elasticsearch) { + ds.elasticsearch = stream.data_stream.elasticsearch; + } + dataStreams_.push(ds); }); @@ -121,7 +125,7 @@ export async function storedPackagePoliciesToAgentPermissions( packagePolicy.name, { indices: dataStreamsForPermissions.map((ds) => - getDataStreamPermissions(ds, packagePolicy.namespace) + getDataStreamPrivileges(ds, packagePolicy.namespace) ), }, ]; @@ -136,10 +140,12 @@ interface DataStreamMeta { dataset: string; dataset_is_prefix?: boolean; hidden?: boolean; - permissions?: RegistryDataStreamPermissions; + elasticsearch?: { + privileges?: RegistryDataStreamPrivileges; + }; } -export function getDataStreamPermissions(dataStream: DataStreamMeta, namespace: string = '*') { +export function getDataStreamPrivileges(dataStream: DataStreamMeta, namespace: string = '*') { let index = `${dataStream.type}-${dataStream.dataset}`; if (dataStream.dataset_is_prefix) { @@ -152,8 +158,12 @@ export function getDataStreamPermissions(dataStream: DataStreamMeta, namespace: index += `-${namespace}`; + const privileges = dataStream?.elasticsearch?.privileges?.indices?.length + ? dataStream.elasticsearch.privileges.indices + : PACKAGE_POLICY_DEFAULT_INDEX_PRIVILEGES; + return { names: [index], - privileges: dataStream.permissions?.indices || ['auto_configure', 'create_doc'], + privileges, }; } diff --git a/x-pack/plugins/fleet/server/services/package_policy.test.ts b/x-pack/plugins/fleet/server/services/package_policy.test.ts index 204650574e92..fe5a3030bd95 100644 --- a/x-pack/plugins/fleet/server/services/package_policy.test.ts +++ b/x-pack/plugins/fleet/server/services/package_policy.test.ts @@ -14,19 +14,25 @@ import { import type { SavedObjectsClient, SavedObjectsUpdateResponse } from 'src/core/server'; import type { KibanaRequest } from 'kibana/server'; -import type { PackageInfo, PackagePolicySOAttributes, AgentPolicySOAttributes } from '../types'; +import type { + PackageInfo, + PackagePolicySOAttributes, + AgentPolicySOAttributes, + PostPackagePolicyDeleteCallback, + RegistryDataStream, + PackagePolicyInputStream, +} from '../types'; import { createPackagePolicyMock } from '../../common/mocks'; + import type { PutPackagePolicyUpdateCallback, PostPackagePolicyCreateCallback } from '..'; import { createAppContextStartContractMock, xpackMocks } from '../mocks'; -import type { PostPackagePolicyDeleteCallback } from '../types'; - import type { DeletePackagePoliciesResponse } from '../../common'; import { IngestManagerError } from '../errors'; -import { packagePolicyService } from './package_policy'; +import { packagePolicyService, _applyIndexPrivileges } from './package_policy'; import { appContextService } from './app_context'; async function mockedGetAssetsData(_a: any, _b: any, dataset: string) { @@ -117,7 +123,7 @@ describe('Package policy service', () => { describe('compilePackagePolicyInputs', () => { it('should work with config variables from the stream', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { data_streams: [ { type: 'logs', @@ -131,7 +137,7 @@ describe('Package policy service', () => { inputs: [{ type: 'log' }], }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, {}, [ { @@ -180,7 +186,7 @@ describe('Package policy service', () => { it('should work with a two level dataset name', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { data_streams: [ { type: 'logs', @@ -194,7 +200,7 @@ describe('Package policy service', () => { inputs: [{ type: 'log' }], }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, {}, [ { @@ -232,7 +238,7 @@ describe('Package policy service', () => { it('should work with config variables at the input level', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { data_streams: [ { dataset: 'package.dataset1', @@ -246,7 +252,7 @@ describe('Package policy service', () => { inputs: [{ type: 'log' }], }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, {}, [ { @@ -295,7 +301,7 @@ describe('Package policy service', () => { it('should work with config variables at the package level', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { data_streams: [ { dataset: 'package.dataset1', @@ -309,7 +315,7 @@ describe('Package policy service', () => { inputs: [{ type: 'log' }], }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, { hosts: { value: ['localhost'], @@ -363,14 +369,14 @@ describe('Package policy service', () => { it('should work with an input with a template and no streams', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { data_streams: [], policy_templates: [ { inputs: [{ type: 'log', template_path: 'some_template_path.yml' }], }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, {}, [ { @@ -405,7 +411,7 @@ describe('Package policy service', () => { it('should work with an input with a template and streams', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { data_streams: [ { dataset: 'package.dataset1', @@ -424,7 +430,7 @@ describe('Package policy service', () => { inputs: [{ type: 'log', template_path: 'some_template_path.yml' }], }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, {}, [ { @@ -510,13 +516,13 @@ describe('Package policy service', () => { it('should work with a package without input', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { policy_templates: [ { inputs: undefined, }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, {}, [] ); @@ -526,13 +532,13 @@ describe('Package policy service', () => { it('should work with a package with a empty inputs array', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { policy_templates: [ { inputs: [], }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, {}, [] ); @@ -1069,3 +1075,119 @@ describe('Package policy service', () => { }); }); }); + +describe('_applyIndexPrivileges()', () => { + function createPackageStream(indexPrivileges?: string[]): RegistryDataStream { + const stream: RegistryDataStream = { + type: '', + dataset: '', + title: '', + release: '', + package: '', + path: '', + }; + + if (indexPrivileges) { + stream.elasticsearch = { + privileges: { + indices: indexPrivileges, + }, + }; + } + + return stream; + } + + function createInputStream( + opts: Partial = {} + ): PackagePolicyInputStream { + return { + id: '', + enabled: true, + data_stream: { + dataset: '', + type: '', + }, + ...opts, + }; + } + + beforeAll(async () => { + appContextService.start(createAppContextStartContractMock()); + }); + + it('should do nothing if packageStream has no privileges', () => { + const packageStream = createPackageStream(); + const inputStream = createInputStream(); + + const streamOut = _applyIndexPrivileges(packageStream, inputStream); + expect(streamOut).toEqual(inputStream); + }); + + it('should not apply privileges if all privileges are forbidden', () => { + const forbiddenPrivileges = ['write', 'delete', 'delete_index', 'all']; + const packageStream = createPackageStream(forbiddenPrivileges); + const inputStream = createInputStream(); + + const streamOut = _applyIndexPrivileges(packageStream, inputStream); + expect(streamOut).toEqual(inputStream); + }); + + it('should not apply privileges if all privileges are unrecognized', () => { + const unrecognizedPrivileges = ['idnotexist', 'invalidperm']; + const packageStream = createPackageStream(unrecognizedPrivileges); + const inputStream = createInputStream(); + + const streamOut = _applyIndexPrivileges(packageStream, inputStream); + expect(streamOut).toEqual(inputStream); + }); + + it('should apply privileges if all privileges are valid', () => { + const validPrivileges = [ + 'auto_configure', + 'create_doc', + 'maintenance', + 'monitor', + 'read', + 'read_cross_cluster', + ]; + + const packageStream = createPackageStream(validPrivileges); + const inputStream = createInputStream(); + const expectedStream = { + ...inputStream, + data_stream: { + ...inputStream.data_stream, + elasticsearch: { + privileges: { + indices: validPrivileges, + }, + }, + }, + }; + + const streamOut = _applyIndexPrivileges(packageStream, inputStream); + expect(streamOut).toEqual(expectedStream); + }); + + it('should only apply valid privileges when there is a mix of valid and invalid', () => { + const mixedPrivileges = ['auto_configure', 'read_cross_cluster', 'idontexist', 'delete']; + + const packageStream = createPackageStream(mixedPrivileges); + const inputStream = createInputStream(); + const expectedStream = { + ...inputStream, + data_stream: { + ...inputStream.data_stream, + elasticsearch: { + privileges: { + indices: ['auto_configure', 'read_cross_cluster'], + }, + }, + }, + }; + + const streamOut = _applyIndexPrivileges(packageStream, inputStream); + expect(streamOut).toEqual(expectedStream); + }); +}); diff --git a/x-pack/plugins/fleet/server/services/package_policy.ts b/x-pack/plugins/fleet/server/services/package_policy.ts index 598dd16b2928..c806b37f8815 100644 --- a/x-pack/plugins/fleet/server/services/package_policy.ts +++ b/x-pack/plugins/fleet/server/services/package_policy.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { omit } from 'lodash'; +import { omit, partition } from 'lodash'; import { i18n } from '@kbn/i18n'; import semverLte from 'semver/functions/lte'; import { getFlattenedObject } from '@kbn/std'; @@ -38,6 +38,7 @@ import type { ListWithKuery, ListResult, UpgradePackagePolicyDryRunResponseItem, + RegistryDataStream, } from '../../common'; import { PACKAGE_POLICY_SAVED_OBJECT_TYPE } from '../constants'; import { @@ -71,6 +72,15 @@ export type InputsOverride = Partial & { const SAVED_OBJECT_TYPE = PACKAGE_POLICY_SAVED_OBJECT_TYPE; +export const DATA_STREAM_ALLOWED_INDEX_PRIVILEGES = new Set([ + 'auto_configure', + 'create_doc', + 'maintenance', + 'monitor', + 'read', + 'read_cross_cluster', +]); + class PackagePolicyService { public async create( soClient: SavedObjectsClientContract, @@ -794,13 +804,51 @@ async function _compilePackageStreams( return await Promise.all(streamsPromises); } +// temporary export to enable testing pending refactor https://github.com/elastic/kibana/issues/112386 +export function _applyIndexPrivileges( + packageDataStream: RegistryDataStream, + stream: PackagePolicyInputStream +): PackagePolicyInputStream { + const streamOut = { ...stream }; + + const indexPrivileges = packageDataStream?.elasticsearch?.privileges?.indices; + + if (!indexPrivileges?.length) { + return streamOut; + } + + const [valid, invalid] = partition(indexPrivileges, (permission) => + DATA_STREAM_ALLOWED_INDEX_PRIVILEGES.has(permission) + ); + + if (invalid.length) { + appContextService + .getLogger() + .warn( + `Ignoring invalid or forbidden index privilege(s) in "${stream.id}" data stream: ${invalid}` + ); + } + + if (valid.length) { + stream.data_stream.elasticsearch = { + privileges: { + indices: valid, + }, + }; + } + + return streamOut; +} + async function _compilePackageStream( registryPkgInfo: RegistryPackage, pkgInfo: PackageInfo, vars: PackagePolicy['vars'], input: PackagePolicyInput, - stream: PackagePolicyInputStream + streamIn: PackagePolicyInputStream ) { + let stream = streamIn; + if (!stream.enabled) { return { ...stream, compiled_stream: undefined }; } @@ -820,6 +868,8 @@ async function _compilePackageStream( ); } + stream = _applyIndexPrivileges(packageDataStream, streamIn); + const streamFromPkg = (packageDataStream.streams || []).find( (pkgStream) => pkgStream.input === input.type ); diff --git a/x-pack/plugins/fleet/server/services/preconfiguration.test.ts b/x-pack/plugins/fleet/server/services/preconfiguration.test.ts index d374553e1db8..86fdd2f0aa80 100644 --- a/x-pack/plugins/fleet/server/services/preconfiguration.test.ts +++ b/x-pack/plugins/fleet/server/services/preconfiguration.test.ts @@ -287,50 +287,46 @@ describe('policy preconfiguration', () => { const soClient = getPutPreconfiguredPackagesMock(); const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser; - const { - policies: policiesA, - nonFatalErrors: nonFatalErrorsA, - } = await ensurePreconfiguredPackagesAndPolicies( - soClient, - esClient, - [ - { - name: 'Test policy', - namespace: 'default', - id: 'test-id', - package_policies: [], - }, - ] as PreconfiguredAgentPolicy[], - [], - mockDefaultOutput - ); + const { policies: policiesA, nonFatalErrors: nonFatalErrorsA } = + await ensurePreconfiguredPackagesAndPolicies( + soClient, + esClient, + [ + { + name: 'Test policy', + namespace: 'default', + id: 'test-id', + package_policies: [], + }, + ] as PreconfiguredAgentPolicy[], + [], + mockDefaultOutput + ); expect(policiesA.length).toEqual(1); expect(policiesA[0].id).toBe('mocked-test-id'); expect(nonFatalErrorsA.length).toBe(0); - const { - policies: policiesB, - nonFatalErrors: nonFatalErrorsB, - } = await ensurePreconfiguredPackagesAndPolicies( - soClient, - esClient, - [ - { - name: 'Test policy redo', - namespace: 'default', - id: 'test-id', - package_policies: [ - { - package: { name: 'some-uninstalled-package' }, - name: 'This package is not installed', - }, - ], - }, - ] as PreconfiguredAgentPolicy[], - [], - mockDefaultOutput - ); + const { policies: policiesB, nonFatalErrors: nonFatalErrorsB } = + await ensurePreconfiguredPackagesAndPolicies( + soClient, + esClient, + [ + { + name: 'Test policy redo', + namespace: 'default', + id: 'test-id', + package_policies: [ + { + package: { name: 'some-uninstalled-package' }, + name: 'This package is not installed', + }, + ], + }, + ] as PreconfiguredAgentPolicy[], + [], + mockDefaultOutput + ); expect(policiesB.length).toEqual(1); expect(policiesB[0].id).toBe('mocked-test-id'); @@ -352,26 +348,24 @@ describe('policy preconfiguration', () => { is_managed: true, } as PreconfiguredAgentPolicy); - const { - policies, - nonFatalErrors: nonFatalErrorsB, - } = await ensurePreconfiguredPackagesAndPolicies( - soClient, - esClient, - [ - { - name: 'Renamed Test policy', - description: 'Renamed Test policy description', - unenroll_timeout: 999, - namespace: 'default', - id: 'test-id', - is_managed: true, - package_policies: [], - }, - ] as PreconfiguredAgentPolicy[], - [], - mockDefaultOutput - ); + const { policies, nonFatalErrors: nonFatalErrorsB } = + await ensurePreconfiguredPackagesAndPolicies( + soClient, + esClient, + [ + { + name: 'Renamed Test policy', + description: 'Renamed Test policy description', + unenroll_timeout: 999, + namespace: 'default', + id: 'test-id', + is_managed: true, + package_policies: [], + }, + ] as PreconfiguredAgentPolicy[], + [], + mockDefaultOutput + ); expect(spyAgentPolicyServiceUpdate).toBeCalled(); expect(spyAgentPolicyServiceUpdate).toBeCalledWith( expect.anything(), // soClient @@ -400,16 +394,14 @@ describe('policy preconfiguration', () => { }; mockConfiguredPolicies.set('test-id', policy); - const { - policies, - nonFatalErrors: nonFatalErrorsB, - } = await ensurePreconfiguredPackagesAndPolicies( - soClient, - esClient, - [policy], - [], - mockDefaultOutput - ); + const { policies, nonFatalErrors: nonFatalErrorsB } = + await ensurePreconfiguredPackagesAndPolicies( + soClient, + esClient, + [policy], + [], + mockDefaultOutput + ); expect(spyAgentPolicyServiceUpdate).not.toBeCalled(); expect(policies.length).toEqual(1); expect(policies[0].id).toBe('test-id'); diff --git a/x-pack/plugins/fleet/server/types/models/package_policy.ts b/x-pack/plugins/fleet/server/types/models/package_policy.ts index e69e38c18728..30321bdca330 100644 --- a/x-pack/plugins/fleet/server/types/models/package_policy.ts +++ b/x-pack/plugins/fleet/server/types/models/package_policy.ts @@ -63,7 +63,19 @@ const PackagePolicyBaseSchema = { id: schema.maybe(schema.string()), // BWC < 7.11 enabled: schema.boolean(), keep_enabled: schema.maybe(schema.boolean()), - data_stream: schema.object({ dataset: schema.string(), type: schema.string() }), + data_stream: schema.object({ + dataset: schema.string(), + type: schema.string(), + elasticsearch: schema.maybe( + schema.object({ + privileges: schema.maybe( + schema.object({ + indices: schema.maybe(schema.arrayOf(schema.string())), + }) + ), + }) + ), + }), vars: schema.maybe(ConfigRecordSchema), config: schema.maybe( schema.recordOf( diff --git a/x-pack/plugins/global_search/public/plugin.ts b/x-pack/plugins/global_search/public/plugin.ts index b3a890d84f03..00f320d23b60 100644 --- a/x-pack/plugins/global_search/public/plugin.ts +++ b/x-pack/plugins/global_search/public/plugin.ts @@ -25,7 +25,8 @@ export class GlobalSearchPlugin GlobalSearchPluginStart, GlobalSearchPluginSetupDeps, GlobalSearchPluginStartDeps - > { + > +{ private readonly config: GlobalSearchClientConfigType; private licenseChecker?: ILicenseChecker; private readonly searchService = new SearchService(); diff --git a/x-pack/plugins/global_search/server/plugin.ts b/x-pack/plugins/global_search/server/plugin.ts index d7c06a92f70e..688691d8941e 100644 --- a/x-pack/plugins/global_search/server/plugin.ts +++ b/x-pack/plugins/global_search/server/plugin.ts @@ -30,7 +30,8 @@ export class GlobalSearchPlugin GlobalSearchPluginStart, GlobalSearchPluginSetupDeps, GlobalSearchPluginStartDeps - > { + > +{ private readonly config: GlobalSearchConfigType; private readonly searchService = new SearchService(); private searchServiceStart?: SearchServiceStart; diff --git a/x-pack/plugins/global_search/server/routes/integration_tests/get_searchable_types.test.ts b/x-pack/plugins/global_search/server/routes/integration_tests/get_searchable_types.test.ts index 6f495bfbd643..cd093c8009a9 100644 --- a/x-pack/plugins/global_search/server/routes/integration_tests/get_searchable_types.test.ts +++ b/x-pack/plugins/global_search/server/routes/integration_tests/get_searchable_types.test.ts @@ -30,9 +30,10 @@ describe('GET /internal/global_search/searchable_types', () => { 'globalSearch' >(pluginId, 'globalSearch', () => globalSearchHandlerContext); - const router = httpSetup.createRouter< - ReturnType - >('/'); + const router = + httpSetup.createRouter>( + '/' + ); registerInternalSearchableTypesRoute(router); diff --git a/x-pack/plugins/global_search/server/services/context.ts b/x-pack/plugins/global_search/server/services/context.ts index 454b0324ab3c..b0669f35b99b 100644 --- a/x-pack/plugins/global_search/server/services/context.ts +++ b/x-pack/plugins/global_search/server/services/context.ts @@ -14,20 +14,20 @@ export type GlobalSearchContextFactory = (request: KibanaRequest) => GlobalSearc /** * {@link GlobalSearchProviderContext | context} factory */ -export const getContextFactory = (coreStart: CoreStart) => ( - request: KibanaRequest -): GlobalSearchProviderContext => { - const soClient = coreStart.savedObjects.getScopedClient(request); - return { - core: { - savedObjects: { - client: soClient, - typeRegistry: coreStart.savedObjects.getTypeRegistry(), +export const getContextFactory = + (coreStart: CoreStart) => + (request: KibanaRequest): GlobalSearchProviderContext => { + const soClient = coreStart.savedObjects.getScopedClient(request); + return { + core: { + savedObjects: { + client: soClient, + typeRegistry: coreStart.savedObjects.getTypeRegistry(), + }, + uiSettings: { + client: coreStart.uiSettings.asScopedToClient(soClient), + }, + capabilities: from(coreStart.capabilities.resolveCapabilities(request)), }, - uiSettings: { - client: coreStart.uiSettings.asScopedToClient(soClient), - }, - capabilities: from(coreStart.capabilities.resolveCapabilities(request)), - }, + }; }; -}; diff --git a/x-pack/plugins/global_search_providers/public/plugin.ts b/x-pack/plugins/global_search_providers/public/plugin.ts index 5fd47947d1b7..89e8e9f57a3d 100644 --- a/x-pack/plugins/global_search_providers/public/plugin.ts +++ b/x-pack/plugins/global_search_providers/public/plugin.ts @@ -14,7 +14,8 @@ export interface GlobalSearchProvidersPluginSetupDeps { } export class GlobalSearchProvidersPlugin - implements Plugin<{}, {}, GlobalSearchProvidersPluginSetupDeps, {}> { + implements Plugin<{}, {}, GlobalSearchProvidersPluginSetupDeps, {}> +{ setup( { getStartServices }: CoreSetup<{}, {}>, { globalSearch }: GlobalSearchProvidersPluginSetupDeps diff --git a/x-pack/plugins/global_search_providers/public/providers/application.test.ts b/x-pack/plugins/global_search_providers/public/providers/application.test.ts index a686f416292d..aa54f3a0e5ff 100644 --- a/x-pack/plugins/global_search_providers/public/providers/application.test.ts +++ b/x-pack/plugins/global_search_providers/public/providers/application.test.ts @@ -246,9 +246,9 @@ describe('applicationResultProvider', () => { // test scheduler doesnt play well with promises. need to workaround by passing // an observable instead. Behavior with promise is asserted in previous tests of the suite - const applicationPromise = (hot('a', { + const applicationPromise = hot('a', { a: application, - }) as unknown) as Promise; + }) as unknown as Promise; const provider = createApplicationResultProvider(applicationPromise); @@ -271,9 +271,9 @@ describe('applicationResultProvider', () => { // test scheduler doesnt play well with promises. need to workaround by passing // an observable instead. Behavior with promise is asserted in previous tests of the suite - const applicationPromise = (hot('a', { + const applicationPromise = hot('a', { a: application, - }) as unknown) as Promise; + }) as unknown as Promise; const provider = createApplicationResultProvider(applicationPromise); diff --git a/x-pack/plugins/global_search_providers/server/plugin.ts b/x-pack/plugins/global_search_providers/server/plugin.ts index cf63389c45a3..dae346144bce 100644 --- a/x-pack/plugins/global_search_providers/server/plugin.ts +++ b/x-pack/plugins/global_search_providers/server/plugin.ts @@ -14,7 +14,8 @@ export interface GlobalSearchProvidersPluginSetupDeps { } export class GlobalSearchProvidersPlugin - implements Plugin<{}, {}, GlobalSearchProvidersPluginSetupDeps, {}> { + implements Plugin<{}, {}, GlobalSearchProvidersPluginSetupDeps, {}> +{ setup( { getStartServices }: CoreSetup<{}, {}>, { globalSearch }: GlobalSearchProvidersPluginSetupDeps 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 1ae556a79edc..8273d99f890c 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 @@ -101,7 +101,7 @@ describe('graph_visualization', () => { width: 2.2, }, ]; - const workspace = ({ + const workspace = { nodes, edges, selectNone: () => {}, @@ -110,7 +110,7 @@ describe('graph_visualization', () => { return !node.isSelected; }), getAllIntersections: jest.fn(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; beforeEach(() => { jest.clearAllMocks(); @@ -120,7 +120,7 @@ describe('graph_visualization', () => { expect( shallow( {}} onSetControl={() => {}} onSetMergeCandidates={() => {}} diff --git a/x-pack/plugins/graph/public/components/inspect_panel.tsx b/x-pack/plugins/graph/public/components/inspect_panel.tsx index a254d54f616e..5e5547ea341f 100644 --- a/x-pack/plugins/graph/public/components/inspect_panel.tsx +++ b/x-pack/plugins/graph/public/components/inspect_panel.tsx @@ -49,11 +49,10 @@ export const InspectPanel = ({ const onRequestClick = () => setSelectedTabId('request'); const onResponseClick = () => setSelectedTabId('response'); - const editorContent = useMemo(() => (selectedTabId === 'request' ? lastRequest : lastResponse), [ - lastRequest, - lastResponse, - selectedTabId, - ]); + const editorContent = useMemo( + () => (selectedTabId === 'request' ? lastRequest : lastResponse), + [lastRequest, lastResponse, selectedTabId] + ); if (showInspect) { return ( 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 1b76cde1a62f..9237acb4741f 100644 --- a/x-pack/plugins/graph/public/components/search_bar.test.tsx +++ b/x-pack/plugins/graph/public/components/search_bar.test.tsx @@ -77,7 +77,7 @@ describe('search_bar', () => { const defaultProps = { isLoading: false, indexPatternProvider: { - get: jest.fn(() => Promise.resolve(({ fields: [] } as unknown) as IndexPattern)), + get: jest.fn(() => Promise.resolve({ fields: [] } as unknown as IndexPattern)), }, confirmWipeWorkspace: (callback: () => void) => { callback(); @@ -169,9 +169,9 @@ describe('search_bar', () => { // pick the button component out of the tree because // it's part of a popover and thus not covered by enzyme - (instance - .find(QueryStringInput) - .prop('prepend') as ReactElement).props.children.props.onClick(); + ( + instance.find(QueryStringInput).prop('prepend') as ReactElement + ).props.children.props.onClick(); expect(openSourceModal).toHaveBeenCalled(); }); diff --git a/x-pack/plugins/graph/public/components/search_bar.tsx b/x-pack/plugins/graph/public/components/search_bar.tsx index fc7e3be3d0d3..57e9831d5a65 100644 --- a/x-pack/plugins/graph/public/components/search_bar.tsx +++ b/x-pack/plugins/graph/public/components/search_bar.tsx @@ -81,9 +81,10 @@ export function SearchBarComponent(props: SearchBarStateProps & SearchBarProps) } = props; const [query, setQuery] = useState({ language: 'kuery', query: urlQuery || '' }); - useEffect(() => setQuery((prev) => ({ language: prev.language, query: urlQuery || '' })), [ - urlQuery, - ]); + useEffect( + () => setQuery((prev) => ({ language: prev.language, query: urlQuery || '' })), + [urlQuery] + ); useEffect(() => { async function fetchPattern() { diff --git a/x-pack/plugins/graph/public/components/workspace_layout/workspace_top_nav_menu.tsx b/x-pack/plugins/graph/public/components/workspace_layout/workspace_top_nav_menu.tsx index 07e21287e5c1..dc7365672ffa 100644 --- a/x-pack/plugins/graph/public/components/workspace_layout/workspace_top_nav_menu.tsx +++ b/x-pack/plugins/graph/public/components/workspace_layout/workspace_top_nav_menu.tsx @@ -136,12 +136,12 @@ export const WorkspaceTopNavMenu = (props: WorkspaceTopNavMenuProps) => { // since settings button will be disabled only if workspace was set const workspace = props.workspace as Workspace; - const settingsObservable = (asSyncedObservable(() => ({ + const settingsObservable = asSyncedObservable(() => ({ blocklistedNodes: workspace.blocklistedNodes, unblockNode: workspace.unblockNode, unblockAll: workspace.unblockAll, canEditDrillDownUrls: props.canEditDrillDownUrls, - })) as unknown) as AsObservable['observable']; + })) as unknown as AsObservable['observable']; props.coreStart.overlays.openFlyout( toMountPoint( diff --git a/x-pack/plugins/graph/public/helpers/kql_encoder.test.ts b/x-pack/plugins/graph/public/helpers/kql_encoder.test.ts index 4cf46e18c8fa..8ef3cd44a63b 100644 --- a/x-pack/plugins/graph/public/helpers/kql_encoder.test.ts +++ b/x-pack/plugins/graph/public/helpers/kql_encoder.test.ts @@ -12,7 +12,7 @@ describe('kql_encoder', () => { let workspaceMock: jest.Mocked; beforeEach(() => { - workspaceMock = ({ + workspaceMock = { returnUnpackedGroupeds: (nodes: []) => nodes, getSelectedOrAllNodes: jest.fn(() => [ { @@ -34,7 +34,7 @@ describe('kql_encoder', () => { }, }, ]), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; }); it('should encode query as URI component', () => { diff --git a/x-pack/plugins/graph/public/helpers/use_workspace_loader.test.tsx b/x-pack/plugins/graph/public/helpers/use_workspace_loader.test.tsx index db80289d0d32..cd0857f82ab6 100644 --- a/x-pack/plugins/graph/public/helpers/use_workspace_loader.test.tsx +++ b/x-pack/plugins/graph/public/helpers/use_workspace_loader.test.tsx @@ -33,13 +33,13 @@ jest.mock('react-router-dom', () => { }; }); -const mockSavedObjectsClient = ({ +const mockSavedObjectsClient = { resolve: jest.fn().mockResolvedValue({ saved_object: { id: 10, _version: '7.15.0', attributes: { wsState: '{}' } }, outcome: 'exactMatch', }), find: jest.fn().mockResolvedValue({ title: 'test' }), -} as unknown) as SavedObjectsClientCommon; +} as unknown as SavedObjectsClientCommon; async function setup(props: UseWorkspaceLoaderProps) { const returnVal = {}; @@ -66,7 +66,7 @@ describe('use_workspace_loader', () => { it('should not redirect if outcome is exactMatch', async () => { await act(async () => { - await setup((defaultProps as unknown) as UseWorkspaceLoaderProps); + await setup(defaultProps as unknown as UseWorkspaceLoaderProps); }); expect(defaultProps.spaces.ui.redirectLegacyUrl).not.toHaveBeenCalled(); expect(defaultProps.store.dispatch).toHaveBeenCalled(); @@ -85,7 +85,7 @@ describe('use_workspace_loader', () => { }, }; await act(async () => { - await setup((props as unknown) as UseWorkspaceLoaderProps); + await setup(props as unknown as UseWorkspaceLoaderProps); }); expect(props.spaces.ui.redirectLegacyUrl).toHaveBeenCalledWith( '#/workspace/aliasTargetId?query={}', diff --git a/x-pack/plugins/graph/public/plugin.ts b/x-pack/plugins/graph/public/plugin.ts index 1c44714a2c49..a1bc8a93f7f7 100644 --- a/x-pack/plugins/graph/public/plugin.ts +++ b/x-pack/plugins/graph/public/plugin.ts @@ -49,7 +49,8 @@ export interface GraphPluginStartDependencies { } export class GraphPlugin - implements Plugin { + implements Plugin +{ private readonly appUpdater$ = new BehaviorSubject(() => ({})); constructor(private initializerContext: PluginInitializerContext) {} diff --git a/x-pack/plugins/graph/public/services/persistence/serialize.test.ts b/x-pack/plugins/graph/public/services/persistence/serialize.test.ts index 2466582bc7b2..ec52159ae10e 100644 --- a/x-pack/plugins/graph/public/services/persistence/serialize.test.ts +++ b/x-pack/plugins/graph/public/services/persistence/serialize.test.ts @@ -159,7 +159,7 @@ describe('serialize', () => { }); it('should serialize given workspace', () => { - const savedWorkspace = ({} as unknown) as GraphWorkspaceSavedObject; + const savedWorkspace = {} as unknown as GraphWorkspaceSavedObject; appStateToSavedWorkspace(savedWorkspace, appState, true); @@ -281,7 +281,7 @@ describe('serialize', () => { }); it('should not save data if set to false', () => { - const savedWorkspace = ({} as unknown) as GraphWorkspaceSavedObject; + const savedWorkspace = {} as unknown as GraphWorkspaceSavedObject; appStateToSavedWorkspace(savedWorkspace, appState, false); diff --git a/x-pack/plugins/graph/public/state_management/helpers.ts b/x-pack/plugins/graph/public/state_management/helpers.ts index 098c1e029be8..db853afc9f14 100644 --- a/x-pack/plugins/graph/public/state_management/helpers.ts +++ b/x-pack/plugins/graph/public/state_management/helpers.ts @@ -25,5 +25,7 @@ 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)); +export const matchesOne = + (...actionCreators: Array>) => + (action: AnyAction) => + actionCreators.some((actionCreator) => actionCreator.match(action)); diff --git a/x-pack/plugins/graph/public/state_management/mocks.ts b/x-pack/plugins/graph/public/state_management/mocks.ts index 189875d04b01..6f7b5dba2e4a 100644 --- a/x-pack/plugins/graph/public/state_management/mocks.ts +++ b/x-pack/plugins/graph/public/state_management/mocks.ts @@ -40,48 +40,48 @@ export function createMockGraphStore({ mockedDepsOverwrites?: Partial>; initialStateOverwrites?: Partial; }): MockedGraphEnvironment { - const workspaceMock = ({ + const workspaceMock = { runLayout: jest.fn(), nodes: [], edges: [], options: {}, blocklistedNodes: [], - } as unknown) as Workspace; + } as unknown as Workspace; const mockedDeps: jest.Mocked = { basePath: '', addBasePath: jest.fn((url: string) => url), changeUrl: jest.fn(), - chrome: ({ + chrome: { setBreadcrumbs: jest.fn(), - } as unknown) as ChromeStart, + } as unknown as ChromeStart, createWorkspace: jest.fn(), getWorkspace: jest.fn(() => workspaceMock), indexPatternProvider: { get: jest.fn(() => - Promise.resolve(({ id: '123', title: 'test-pattern' } as unknown) as IndexPattern) + Promise.resolve({ id: '123', title: 'test-pattern' } as unknown as IndexPattern) ), }, I18nContext: jest .fn() .mockImplementation(({ children }: { children: React.ReactNode }) => children), - notifications: ({ + notifications: { toasts: { addDanger: jest.fn(), addSuccess: jest.fn(), }, - } as unknown) as NotificationsStart, + } as unknown as NotificationsStart, http: {} as HttpStart, notifyReact: jest.fn(), savePolicy: 'configAndData', showSaveModal: jest.fn(), - overlays: ({ + overlays: { openModal: jest.fn(), - } as unknown) as OverlayStart, - savedObjectsClient: ({ + } as unknown as OverlayStart, + savedObjectsClient: { find: jest.fn(), get: jest.fn(), - } as unknown) as SavedObjectsClientContract, + } as unknown as SavedObjectsClientContract, handleSearchQueryError: jest.fn(), ...mockedDepsOverwrites, }; 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 01b1a9296b0b..736270e53a79 100644 --- a/x-pack/plugins/graph/public/state_management/url_templates.ts +++ b/x-pack/plugins/graph/public/state_management/url_templates.ts @@ -23,9 +23,8 @@ import { matchesOne } from './helpers'; const actionCreator = actionCreatorFactory('x-pack/graph/urlTemplates'); export const loadTemplates = actionCreator('LOAD_TEMPLATES'); -export const saveTemplate = actionCreator<{ index: number; template: UrlTemplate }>( - 'SAVE_TEMPLATE' -); +export const saveTemplate = + actionCreator<{ index: number; template: UrlTemplate }>('SAVE_TEMPLATE'); export const removeTemplate = actionCreator('REMOVE_TEMPLATE'); export type UrlTemplatesState = UrlTemplate[]; diff --git a/x-pack/plugins/graph/server/sample_data/ecommerce.ts b/x-pack/plugins/graph/server/sample_data/ecommerce.ts index e8383ea542db..36e125864600 100644 --- a/x-pack/plugins/graph/server/sample_data/ecommerce.ts +++ b/x-pack/plugins/graph/server/sample_data/ecommerce.ts @@ -335,8 +335,7 @@ const wsState: any = { ], urlTemplates: [ { - url: - '/app/discover#/?_a=(columns%3A!(_source)%2Cindex%3Aff959d40-b880-11e8-a6d9-e546fe2bba5f%2Cinterval%3Aauto%2Cquery%3A(language%3Akuery%2Cquery%3A{{gquery}})%2Csort%3A!(_score%2Cdesc))', + url: '/app/discover#/?_a=(columns%3A!(_source)%2Cindex%3Aff959d40-b880-11e8-a6d9-e546fe2bba5f%2Cinterval%3Aauto%2Cquery%3A(language%3Akuery%2Cquery%3A{{gquery}})%2Csort%3A!(_score%2Cdesc))', description: 'Raw documents', isDefault: true, encoderID: 'kql-loose', diff --git a/x-pack/plugins/graph/server/sample_data/flights.ts b/x-pack/plugins/graph/server/sample_data/flights.ts index d62b4e77e325..61beacc3552f 100644 --- a/x-pack/plugins/graph/server/sample_data/flights.ts +++ b/x-pack/plugins/graph/server/sample_data/flights.ts @@ -1589,8 +1589,7 @@ const wsState: any = { ], urlTemplates: [ { - url: - '/app/discover#/?_a=(columns%3A!(_source)%2Cindex%3Ad3d7af60-4c81-11e8-b3d7-01146121b73d%2Cinterval%3Aauto%2Cquery%3A(language%3Akuery%2Cquery%3A{{gquery}})%2Csort%3A!(_score%2Cdesc))', + url: '/app/discover#/?_a=(columns%3A!(_source)%2Cindex%3Ad3d7af60-4c81-11e8-b3d7-01146121b73d%2Cinterval%3Aauto%2Cquery%3A(language%3Akuery%2Cquery%3A{{gquery}})%2Csort%3A!(_score%2Cdesc))', description: 'Raw documents', isDefault: true, encoderID: 'kql-loose', diff --git a/x-pack/plugins/graph/server/sample_data/logs.ts b/x-pack/plugins/graph/server/sample_data/logs.ts index bd9b3a5c3509..d3d9c18a309e 100644 --- a/x-pack/plugins/graph/server/sample_data/logs.ts +++ b/x-pack/plugins/graph/server/sample_data/logs.ts @@ -176,8 +176,7 @@ const wsState: any = { 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.50 Safari/534.24', color: '#CE0060', field: 'agent.keyword', - term: - 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.50 Safari/534.24', + term: 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.50 Safari/534.24', parent: null, size: 15, }, @@ -407,8 +406,7 @@ const wsState: any = { ], urlTemplates: [ { - url: - '/app/discover#/?_a=(columns%3A!(_source)%2Cindex%3A%2790943e30-9a47-11e8-b64d-95841ca0b247%27%2Cinterval%3Aauto%2Cquery%3A(language%3Akuery%2Cquery%3A{{gquery}})%2Csort%3A!(_score%2Cdesc))', + url: '/app/discover#/?_a=(columns%3A!(_source)%2Cindex%3A%2790943e30-9a47-11e8-b64d-95841ca0b247%27%2Cinterval%3Aauto%2Cquery%3A(language%3Akuery%2Cquery%3A{{gquery}})%2Csort%3A!(_score%2Cdesc))', description: 'Raw documents', isDefault: true, encoderID: 'kql-loose', diff --git a/x-pack/plugins/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts b/x-pack/plugins/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts index 7483e266a1ac..1f2927436d4a 100644 --- a/x-pack/plugins/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts +++ b/x-pack/plugins/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts @@ -35,9 +35,10 @@ export function registerGrokSimulateRoute(framework: KibanaFramework) { async (requestContext, request, response) => { try { const grokdebuggerRequest = GrokdebuggerRequest.fromDownstreamJSON(request.body); - const simulateResponseFromES = await requestContext.core.elasticsearch.client.asCurrentUser.ingest.simulate( - { body: grokdebuggerRequest.upstreamJSON } - ); + const simulateResponseFromES = + await requestContext.core.elasticsearch.client.asCurrentUser.ingest.simulate({ + body: grokdebuggerRequest.upstreamJSON, + }); const grokdebuggerResponse = GrokdebuggerResponse.fromUpstreamJSON( simulateResponseFromES.body ); diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/constants.ts b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/constants.ts index 90fff3a18735..f57f351ae083 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/constants.ts +++ b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/constants.ts @@ -181,7 +181,7 @@ export const POLICY_WITH_NODE_ROLE_ALLOCATION: PolicyFromES = { name: POLICY_NAME, }; -export const POLICY_WITH_KNOWN_AND_UNKNOWN_FIELDS = ({ +export const POLICY_WITH_KNOWN_AND_UNKNOWN_FIELDS = { version: 1, modified_date: Date.now().toString(), policy: { @@ -219,7 +219,7 @@ export const POLICY_WITH_KNOWN_AND_UNKNOWN_FIELDS = ({ name: POLICY_NAME, }, name: POLICY_NAME, -} as any) as PolicyFromES; +} as any as PolicyFromES; export const getGeneratedPolicies = (): PolicyFromES[] => { const policy = { diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/errors_actions.ts b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/errors_actions.ts index 7acc6a3e2f26..34d07d4a36ff 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/errors_actions.ts +++ b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/errors_actions.ts @@ -17,17 +17,15 @@ const createWaitForValidationAction = (testBed: TestBed) => () => { component.update(); }; -const createExpectMessagesAction = (testBed: TestBed) => ( - expectedMessages: string[], - phase?: Phase -) => { - const { form } = testBed; - if (phase) { - expect(form.getErrorsMessages(`${phase}-phase`)).toEqual(expectedMessages); - } else { - expect(form.getErrorsMessages()).toEqual(expectedMessages); - } -}; +const createExpectMessagesAction = + (testBed: TestBed) => (expectedMessages: string[], phase?: Phase) => { + const { form } = testBed; + if (phase) { + expect(form.getErrorsMessages(`${phase}-phase`)).toEqual(expectedMessages); + } else { + expect(form.getErrorsMessages()).toEqual(expectedMessages); + } + }; export const createErrorsActions = (testBed: TestBed) => { const { exists } = testBed; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/forcemerge_actions.ts b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/forcemerge_actions.ts index 400f3d2070e6..f2a27aba9ec5 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/forcemerge_actions.ts +++ b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/forcemerge_actions.ts @@ -11,15 +11,14 @@ import { Phase } from '../../../../common/types'; import { createFormToggleAction } from './form_toggle_action'; import { createFormSetValueAction } from './form_set_value_action'; -const createFormCheckboxAction = (testBed: TestBed, dataTestSubject: string) => async ( - checked: boolean -) => { - const { form, component } = testBed; - await act(async () => { - form.selectCheckBox(dataTestSubject, checked); - }); - component.update(); -}; +const createFormCheckboxAction = + (testBed: TestBed, dataTestSubject: string) => async (checked: boolean) => { + const { form, component } = testBed; + await act(async () => { + form.selectCheckBox(dataTestSubject, checked); + }); + component.update(); + }; export const createForceMergeActions = (testBed: TestBed, phase: Phase) => { const { exists } = testBed; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/form_toggle_and_set_value_action.ts b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/form_toggle_and_set_value_action.ts index 643e0f23a9de..b3510466b4b9 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/form_toggle_and_set_value_action.ts +++ b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/form_toggle_and_set_value_action.ts @@ -9,14 +9,11 @@ import { TestBed } from '@kbn/test/jest'; import { createFormToggleAction } from './form_toggle_action'; import { createFormSetValueAction } from './form_set_value_action'; -export const createFormToggleAndSetValueAction = ( - testBed: TestBed, - toggleSelector: string, - inputSelector: string -) => async (value: string) => { - const { exists } = testBed; - if (!exists(inputSelector)) { - await createFormToggleAction(testBed, toggleSelector)(); - } - await createFormSetValueAction(testBed, inputSelector)(value); -}; +export const createFormToggleAndSetValueAction = + (testBed: TestBed, toggleSelector: string, inputSelector: string) => async (value: string) => { + const { exists } = testBed; + if (!exists(inputSelector)) { + await createFormToggleAction(testBed, toggleSelector)(); + } + await createFormSetValueAction(testBed, inputSelector)(value); + }; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/rollover_actions.ts b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/rollover_actions.ts index 798b74e40055..93a1b959ec96 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/rollover_actions.ts +++ b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/rollover_actions.ts @@ -10,29 +10,27 @@ import { TestBed } from '@kbn/test/jest'; import { createFormToggleAction } from './form_toggle_action'; import { createFormSetValueAction } from './form_set_value_action'; -const createSetPrimaryShardSizeAction = (testBed: TestBed) => async ( - value: string, - units?: string -) => { - const { find, component } = testBed; +const createSetPrimaryShardSizeAction = + (testBed: TestBed) => async (value: string, units?: string) => { + const { find, component } = testBed; - await act(async () => { - find('hot-selectedMaxPrimaryShardSize').simulate('change', { target: { value } }); - }); - component.update(); - - if (units) { - act(() => { - find('hot-selectedMaxPrimaryShardSize.show-filters-button').simulate('click'); + await act(async () => { + find('hot-selectedMaxPrimaryShardSize').simulate('change', { target: { value } }); }); component.update(); - act(() => { - find(`hot-selectedMaxPrimaryShardSize.filter-option-${units}`).simulate('click'); - }); - component.update(); - } -}; + if (units) { + act(() => { + find('hot-selectedMaxPrimaryShardSize.show-filters-button').simulate('click'); + }); + component.update(); + + act(() => { + find(`hot-selectedMaxPrimaryShardSize.filter-option-${units}`).simulate('click'); + }); + component.update(); + } + }; const createSetMaxAgeAction = (testBed: TestBed) => async (value: string, units?: string) => { const { find, component } = testBed; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/policy_table.test.tsx b/x-pack/plugins/index_lifecycle_management/__jest__/policy_table.test.tsx index 820f8393d933..cf25b1c335ae 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/policy_table.test.tsx +++ b/x-pack/plugins/index_lifecycle_management/__jest__/policy_table.test.tsx @@ -137,7 +137,7 @@ describe('policy table', () => { test('filters based on content of search input', () => { const rendered = mountWithIntl(component); const searchInput = rendered.find('.euiFieldSearch').first(); - ((searchInput.instance() as unknown) as HTMLInputElement).value = 'testy0'; + (searchInput.instance() as unknown as HTMLInputElement).value = 'testy0'; searchInput.simulate('keyup', { key: 'Enter', keyCode: 13, which: 13 }); rendered.update(); snapshot(getPolicyNames(rendered)); diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/data_tier_allocation_field/components/data_tier_allocation.tsx b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/data_tier_allocation_field/components/data_tier_allocation.tsx index 1eeb32d84f67..6ca0324d8972 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/data_tier_allocation_field/components/data_tier_allocation.tsx +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/data_tier_allocation_field/components/data_tier_allocation.tsx @@ -161,13 +161,8 @@ const getSelectOptions = (phase: PhaseWithAllocation, disableDataTierOption: boo ].filter(Boolean) as SelectOptions[]; export const DataTierAllocation: FunctionComponent = (props) => { - const { - phase, - hasNodeAttributes, - isCloudEnabled, - isUsingDeprecatedDataRoleConfig, - isLoading, - } = props; + const { phase, hasNodeAttributes, isCloudEnabled, isUsingDeprecatedDataRoleConfig, isLoading } = + props; /** * On Cloud we want to disable the data tier allocation option when we detect that we are not diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/min_age_field/min_age_field.tsx b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/min_age_field/min_age_field.tsx index ad92ef2d4447..2c42d76415db 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/min_age_field/min_age_field.tsx +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/min_age_field/min_age_field.tsx @@ -86,9 +86,8 @@ export const MinAgeField: FunctionComponent = ({ phase }): React.ReactEle const { isUsingRollover } = useConfiguration(); const globalFields = useGlobalFields(); - const { setValue: setMillisecondValue } = globalFields[ - `${phase}MinAgeMilliSeconds` as 'coldMinAgeMilliSeconds' - ]; + const { setValue: setMillisecondValue } = + globalFields[`${phase}MinAgeMilliSeconds` as 'coldMinAgeMilliSeconds']; const [formData] = useFormData({ watch: [minAgeValuePath, minAgeUnitPath] }); const minAgeValue = get(formData, minAgeValuePath); const minAgeUnit = get(formData, minAgeUnitPath); @@ -153,9 +152,8 @@ export const MinAgeField: FunctionComponent = ({ phase }): React.ReactEle {(unitField) => { - const { isInvalid: isUnitFieldInvalid } = getFieldValidityAndErrorMessage( - unitField - ); + const { isInvalid: isUnitFieldInvalid } = + getFieldValidityAndErrorMessage(unitField); const icon = ( <> {/* This element is rendered for testing purposes only */} @@ -167,11 +165,10 @@ export const MinAgeField: FunctionComponent = ({ phase }): React.ReactEle /> ); - const selectAppendValue: Array< - string | React.ReactElement - > = isUsingRollover - ? [i18nTexts.minAgeUnitFieldSuffix, icon] - : [i18nTexts.minAgeUnitFieldSuffix]; + const selectAppendValue: Array = + isUsingRollover + ? [i18nTexts.minAgeUnitFieldSuffix, icon] + : [i18nTexts.minAgeUnitFieldSuffix]; return ( (fieldPath: string): boolean => - fieldPath.startsWith(`phases.${phase}`) || fieldPath.startsWith(`_meta.${phase}`); +const isXPhaseField = + (phase: keyof Phases) => + (fieldPath: string): boolean => + fieldPath.startsWith(`phases.${phase}`) || fieldPath.startsWith(`_meta.${phase}`); const isHotPhaseField = isXPhaseField('hot'); const isWarmPhaseField = isXPhaseField('warm'); diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/deserializer.ts b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/deserializer.ts index ddb21dba9015..dc3714bdaf8d 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/deserializer.ts +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/deserializer.ts @@ -14,133 +14,133 @@ import { getDefaultRepository } from '../lib'; import { FormInternal } from '../types'; import { CLOUD_DEFAULT_REPO } from '../constants'; -export const createDeserializer = (isCloudEnabled: boolean) => ( - policy: SerializedPolicy -): FormInternal => { - const { - phases: { hot, warm, cold, frozen, delete: deletePhase }, - } = policy; +export const createDeserializer = + (isCloudEnabled: boolean) => + (policy: SerializedPolicy): FormInternal => { + const { + phases: { hot, warm, cold, frozen, delete: deletePhase }, + } = policy; - let defaultRepository = getDefaultRepository([ - hot?.actions.searchable_snapshot, - cold?.actions.searchable_snapshot, - frozen?.actions.searchable_snapshot, - ]); + let defaultRepository = getDefaultRepository([ + hot?.actions.searchable_snapshot, + cold?.actions.searchable_snapshot, + frozen?.actions.searchable_snapshot, + ]); - if (!defaultRepository && isCloudEnabled) { - defaultRepository = CLOUD_DEFAULT_REPO; - } + if (!defaultRepository && isCloudEnabled) { + defaultRepository = CLOUD_DEFAULT_REPO; + } - const _meta: FormInternal['_meta'] = { - hot: { - isUsingDefaultRollover: isUsingDefaultRollover(policy), - customRollover: { - enabled: Boolean(hot?.actions?.rollover), + const _meta: FormInternal['_meta'] = { + hot: { + isUsingDefaultRollover: isUsingDefaultRollover(policy), + customRollover: { + enabled: Boolean(hot?.actions?.rollover), + }, + bestCompression: hot?.actions?.forcemerge?.index_codec === 'best_compression', + readonlyEnabled: Boolean(hot?.actions?.readonly), }, - bestCompression: hot?.actions?.forcemerge?.index_codec === 'best_compression', - readonlyEnabled: Boolean(hot?.actions?.readonly), - }, - warm: { - enabled: Boolean(warm), - warmPhaseOnRollover: warm === undefined ? true : Boolean(warm.min_age === '0ms'), - bestCompression: warm?.actions?.forcemerge?.index_codec === 'best_compression', - dataTierAllocationType: determineDataTierAllocationType(warm?.actions), - readonlyEnabled: Boolean(warm?.actions?.readonly), - minAgeToMilliSeconds: -1, - }, - cold: { - enabled: Boolean(cold), - dataTierAllocationType: determineDataTierAllocationType(cold?.actions), - freezeEnabled: Boolean(cold?.actions?.freeze), - readonlyEnabled: Boolean(cold?.actions?.readonly), - minAgeToMilliSeconds: -1, - }, - frozen: { - enabled: Boolean(frozen), - dataTierAllocationType: determineDataTierAllocationType(frozen?.actions), - freezeEnabled: Boolean(frozen?.actions?.freeze), - minAgeToMilliSeconds: -1, - }, - delete: { - enabled: Boolean(deletePhase), - minAgeToMilliSeconds: -1, - }, - searchableSnapshot: { - repository: defaultRepository, - }, - }; + warm: { + enabled: Boolean(warm), + warmPhaseOnRollover: warm === undefined ? true : Boolean(warm.min_age === '0ms'), + bestCompression: warm?.actions?.forcemerge?.index_codec === 'best_compression', + dataTierAllocationType: determineDataTierAllocationType(warm?.actions), + readonlyEnabled: Boolean(warm?.actions?.readonly), + minAgeToMilliSeconds: -1, + }, + cold: { + enabled: Boolean(cold), + dataTierAllocationType: determineDataTierAllocationType(cold?.actions), + freezeEnabled: Boolean(cold?.actions?.freeze), + readonlyEnabled: Boolean(cold?.actions?.readonly), + minAgeToMilliSeconds: -1, + }, + frozen: { + enabled: Boolean(frozen), + dataTierAllocationType: determineDataTierAllocationType(frozen?.actions), + freezeEnabled: Boolean(frozen?.actions?.freeze), + minAgeToMilliSeconds: -1, + }, + delete: { + enabled: Boolean(deletePhase), + minAgeToMilliSeconds: -1, + }, + searchableSnapshot: { + repository: defaultRepository, + }, + }; - return produce( - { - ...policy, - _meta, - }, - (draft: FormInternal) => { - if (draft.phases.hot?.actions?.rollover) { - if (draft.phases.hot.actions.rollover.max_size) { - const maxSize = splitSizeAndUnits(draft.phases.hot.actions.rollover.max_size); - draft.phases.hot.actions.rollover.max_size = maxSize.size; - draft._meta.hot.customRollover.maxStorageSizeUnit = maxSize.units; - } + return produce( + { + ...policy, + _meta, + }, + (draft: FormInternal) => { + if (draft.phases.hot?.actions?.rollover) { + if (draft.phases.hot.actions.rollover.max_size) { + const maxSize = splitSizeAndUnits(draft.phases.hot.actions.rollover.max_size); + draft.phases.hot.actions.rollover.max_size = maxSize.size; + draft._meta.hot.customRollover.maxStorageSizeUnit = maxSize.units; + } - if (draft.phases.hot.actions.rollover.max_primary_shard_size) { - const maxPrimaryShardSize = splitSizeAndUnits( - draft.phases.hot.actions.rollover.max_primary_shard_size - ); - draft.phases.hot.actions.rollover.max_primary_shard_size = maxPrimaryShardSize.size; - draft._meta.hot.customRollover.maxPrimaryShardSizeUnit = maxPrimaryShardSize.units; - } + if (draft.phases.hot.actions.rollover.max_primary_shard_size) { + const maxPrimaryShardSize = splitSizeAndUnits( + draft.phases.hot.actions.rollover.max_primary_shard_size + ); + draft.phases.hot.actions.rollover.max_primary_shard_size = maxPrimaryShardSize.size; + draft._meta.hot.customRollover.maxPrimaryShardSizeUnit = maxPrimaryShardSize.units; + } - if (draft.phases.hot.actions.rollover.max_age) { - const maxAge = splitSizeAndUnits(draft.phases.hot.actions.rollover.max_age); - draft.phases.hot.actions.rollover.max_age = maxAge.size; - draft._meta.hot.customRollover.maxAgeUnit = maxAge.units; + if (draft.phases.hot.actions.rollover.max_age) { + const maxAge = splitSizeAndUnits(draft.phases.hot.actions.rollover.max_age); + draft.phases.hot.actions.rollover.max_age = maxAge.size; + draft._meta.hot.customRollover.maxAgeUnit = maxAge.units; + } } - } - if (draft.phases.warm) { - if (draft.phases.warm.actions?.allocate?.require) { - Object.entries(draft.phases.warm.actions.allocate.require).forEach((entry) => { - draft._meta.warm.allocationNodeAttribute = entry.join(':'); - }); - } + if (draft.phases.warm) { + if (draft.phases.warm.actions?.allocate?.require) { + Object.entries(draft.phases.warm.actions.allocate.require).forEach((entry) => { + draft._meta.warm.allocationNodeAttribute = entry.join(':'); + }); + } - if (draft.phases.warm.min_age) { - const minAge = splitSizeAndUnits(draft.phases.warm.min_age); - draft.phases.warm.min_age = minAge.size; - draft._meta.warm.minAgeUnit = minAge.units; + if (draft.phases.warm.min_age) { + const minAge = splitSizeAndUnits(draft.phases.warm.min_age); + draft.phases.warm.min_age = minAge.size; + draft._meta.warm.minAgeUnit = minAge.units; + } } - } - if (draft.phases.cold) { - if (draft.phases.cold.actions?.allocate?.require) { - Object.entries(draft.phases.cold.actions.allocate.require).forEach((entry) => { - draft._meta.cold.allocationNodeAttribute = entry.join(':'); - }); - } + if (draft.phases.cold) { + if (draft.phases.cold.actions?.allocate?.require) { + Object.entries(draft.phases.cold.actions.allocate.require).forEach((entry) => { + draft._meta.cold.allocationNodeAttribute = entry.join(':'); + }); + } - if (draft.phases.cold.min_age) { - const minAge = splitSizeAndUnits(draft.phases.cold.min_age); - draft.phases.cold.min_age = minAge.size; - draft._meta.cold.minAgeUnit = minAge.units; + if (draft.phases.cold.min_age) { + const minAge = splitSizeAndUnits(draft.phases.cold.min_age); + draft.phases.cold.min_age = minAge.size; + draft._meta.cold.minAgeUnit = minAge.units; + } } - } - if (draft.phases.frozen) { - if (draft.phases.frozen.min_age) { - const minAge = splitSizeAndUnits(draft.phases.frozen.min_age); - draft.phases.frozen.min_age = minAge.size; - draft._meta.frozen.minAgeUnit = minAge.units; + if (draft.phases.frozen) { + if (draft.phases.frozen.min_age) { + const minAge = splitSizeAndUnits(draft.phases.frozen.min_age); + draft.phases.frozen.min_age = minAge.size; + draft._meta.frozen.minAgeUnit = minAge.units; + } } - } - if (draft.phases.delete) { - if (draft.phases.delete.min_age) { - const minAge = splitSizeAndUnits(draft.phases.delete.min_age); - draft.phases.delete.min_age = minAge.size; - draft._meta.delete.minAgeUnit = minAge.units; + if (draft.phases.delete) { + if (draft.phases.delete.min_age) { + const minAge = splitSizeAndUnits(draft.phases.delete.min_age); + draft.phases.delete.min_age = minAge.size; + draft._meta.delete.minAgeUnit = minAge.units; + } } } - } - ); -}; + ); + }; diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/global_fields_context.tsx b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/global_fields_context.tsx index 94b804c1ce53..5834fe5b9ea7 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/global_fields_context.tsx +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/global_fields_context.tsx @@ -26,29 +26,27 @@ type GlobalFields = { const GlobalFieldsContext = createContext(null); -export const globalFields: Record< - keyof GlobalFields, - { path: string; config?: FieldConfig } -> = { - deleteEnabled: { - path: '_meta.delete.enabled', - }, - searchableSnapshotRepo: { - path: '_meta.searchableSnapshot.repository', - }, - warmMinAgeMilliSeconds: { - path: '_meta.warm.minAgeToMilliSeconds', - }, - coldMinAgeMilliSeconds: { - path: '_meta.cold.minAgeToMilliSeconds', - }, - frozenMinAgeMilliSeconds: { - path: '_meta.frozen.minAgeToMilliSeconds', - }, - deleteMinAgeMilliSeconds: { - path: '_meta.delete.minAgeToMilliSeconds', - }, -}; +export const globalFields: Record }> = + { + deleteEnabled: { + path: '_meta.delete.enabled', + }, + searchableSnapshotRepo: { + path: '_meta.searchableSnapshot.repository', + }, + warmMinAgeMilliSeconds: { + path: '_meta.warm.minAgeToMilliSeconds', + }, + coldMinAgeMilliSeconds: { + path: '_meta.cold.minAgeToMilliSeconds', + }, + frozenMinAgeMilliSeconds: { + path: '_meta.frozen.minAgeToMilliSeconds', + }, + deleteMinAgeMilliSeconds: { + path: '_meta.delete.minAgeToMilliSeconds', + }, + }; export const GlobalFieldsProvider: FunctionComponent = ({ children }) => { return ( diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/serializer/serializer.ts b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/serializer/serializer.ts index 2a7d21cce03b..cf81468dd2b4 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/serializer/serializer.ts +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/serializer/serializer.ts @@ -16,312 +16,312 @@ import { FormInternal } from '../../types'; import { serializeMigrateAndAllocateActions } from './serialize_migrate_and_allocate_actions'; -export const createSerializer = (originalPolicy?: SerializedPolicy) => ( - data: FormInternal -): SerializedPolicy => { - const { _meta, ...updatedPolicy } = data; - - updatedPolicy.phases = { hot: { actions: {} }, ...updatedPolicy.phases }; - - return produce(originalPolicy ?? defaultPolicy, (draft) => { - // Copy over all updated fields - merge(draft, updatedPolicy); - - /** - * Important shared values for serialization - */ - const isUsingRollover = Boolean( - _meta.hot?.isUsingDefaultRollover || _meta.hot?.customRollover.enabled - ); - - // Next copy over all meta fields and delete any fields that have been removed - // by fields exposed in the form. It is very important that we do not delete - // data that the form does not control! E.g., unfollow action in hot phase. - - /** - * HOT PHASE SERIALIZATION - */ - if (draft.phases.hot) { - draft.phases.hot.min_age = draft.phases.hot.min_age ?? '0ms'; - } - - if (draft.phases.hot?.actions) { - const hotPhaseActions = draft.phases.hot.actions; +export const createSerializer = + (originalPolicy?: SerializedPolicy) => + (data: FormInternal): SerializedPolicy => { + const { _meta, ...updatedPolicy } = data; + + updatedPolicy.phases = { hot: { actions: {} }, ...updatedPolicy.phases }; + + return produce(originalPolicy ?? defaultPolicy, (draft) => { + // Copy over all updated fields + merge(draft, updatedPolicy); /** - * HOT PHASE ROLLOVER + * Important shared values for serialization */ - if (isUsingRollover) { - if (_meta.hot?.isUsingDefaultRollover) { - hotPhaseActions.rollover = cloneDeep(defaultRolloverAction); - } else { - // Rollover may not exist if editing an existing policy with initially no rollover configured - if (!hotPhaseActions.rollover) { - hotPhaseActions.rollover = {}; - } + const isUsingRollover = Boolean( + _meta.hot?.isUsingDefaultRollover || _meta.hot?.customRollover.enabled + ); - // We are using user-defined, custom rollover settings. - if (updatedPolicy.phases.hot!.actions.rollover?.max_age) { - hotPhaseActions.rollover.max_age = `${hotPhaseActions.rollover.max_age}${_meta.hot?.customRollover.maxAgeUnit}`; + // Next copy over all meta fields and delete any fields that have been removed + // by fields exposed in the form. It is very important that we do not delete + // data that the form does not control! E.g., unfollow action in hot phase. + + /** + * HOT PHASE SERIALIZATION + */ + if (draft.phases.hot) { + draft.phases.hot.min_age = draft.phases.hot.min_age ?? '0ms'; + } + + if (draft.phases.hot?.actions) { + const hotPhaseActions = draft.phases.hot.actions; + + /** + * HOT PHASE ROLLOVER + */ + if (isUsingRollover) { + if (_meta.hot?.isUsingDefaultRollover) { + hotPhaseActions.rollover = cloneDeep(defaultRolloverAction); } else { - delete hotPhaseActions.rollover.max_age; + // Rollover may not exist if editing an existing policy with initially no rollover configured + if (!hotPhaseActions.rollover) { + hotPhaseActions.rollover = {}; + } + + // We are using user-defined, custom rollover settings. + if (updatedPolicy.phases.hot!.actions.rollover?.max_age) { + hotPhaseActions.rollover.max_age = `${hotPhaseActions.rollover.max_age}${_meta.hot?.customRollover.maxAgeUnit}`; + } else { + delete hotPhaseActions.rollover.max_age; + } + + if (typeof updatedPolicy.phases.hot!.actions.rollover?.max_docs !== 'number') { + delete hotPhaseActions.rollover.max_docs; + } + + if (updatedPolicy.phases.hot!.actions.rollover?.max_primary_shard_size) { + hotPhaseActions.rollover.max_primary_shard_size = `${hotPhaseActions.rollover.max_primary_shard_size}${_meta.hot?.customRollover.maxPrimaryShardSizeUnit}`; + } else { + delete hotPhaseActions.rollover.max_primary_shard_size; + } + + if (updatedPolicy.phases.hot!.actions.rollover?.max_size) { + hotPhaseActions.rollover.max_size = `${hotPhaseActions.rollover.max_size}${_meta.hot?.customRollover.maxStorageSizeUnit}`; + } else { + delete hotPhaseActions.rollover.max_size; + } } - if (typeof updatedPolicy.phases.hot!.actions.rollover?.max_docs !== 'number') { - delete hotPhaseActions.rollover.max_docs; + /** + * HOT PHASE FORCEMERGE + */ + if (!updatedPolicy.phases.hot!.actions?.forcemerge) { + delete hotPhaseActions.forcemerge; + } else if (_meta.hot?.bestCompression) { + hotPhaseActions.forcemerge!.index_codec = 'best_compression'; + } else { + delete hotPhaseActions.forcemerge!.index_codec; } - if (updatedPolicy.phases.hot!.actions.rollover?.max_primary_shard_size) { - hotPhaseActions.rollover.max_primary_shard_size = `${hotPhaseActions.rollover.max_primary_shard_size}${_meta.hot?.customRollover.maxPrimaryShardSizeUnit}`; - } else { - delete hotPhaseActions.rollover.max_primary_shard_size; + if (_meta.hot?.bestCompression && hotPhaseActions.forcemerge) { + hotPhaseActions.forcemerge.index_codec = 'best_compression'; } - if (updatedPolicy.phases.hot!.actions.rollover?.max_size) { - hotPhaseActions.rollover.max_size = `${hotPhaseActions.rollover.max_size}${_meta.hot?.customRollover.maxStorageSizeUnit}`; + /** + * HOT PHASE READ-ONLY + */ + if (_meta.hot?.readonlyEnabled) { + hotPhaseActions.readonly = hotPhaseActions.readonly ?? {}; } else { - delete hotPhaseActions.rollover.max_size; + delete hotPhaseActions.readonly; } + } else { + delete hotPhaseActions.rollover; + delete hotPhaseActions.forcemerge; + delete hotPhaseActions.readonly; } /** - * HOT PHASE FORCEMERGE + * HOT PHASE SET PRIORITY */ - if (!updatedPolicy.phases.hot!.actions?.forcemerge) { - delete hotPhaseActions.forcemerge; - } else if (_meta.hot?.bestCompression) { - hotPhaseActions.forcemerge!.index_codec = 'best_compression'; - } else { - delete hotPhaseActions.forcemerge!.index_codec; + if (!updatedPolicy.phases.hot!.actions?.set_priority) { + delete hotPhaseActions.set_priority; } - if (_meta.hot?.bestCompression && hotPhaseActions.forcemerge) { - hotPhaseActions.forcemerge.index_codec = 'best_compression'; + /** + * HOT PHASE SHRINK + */ + if (!updatedPolicy.phases.hot?.actions?.shrink) { + delete hotPhaseActions.shrink; } /** - * HOT PHASE READ-ONLY + * HOT PHASE SEARCHABLE SNAPSHOT */ - if (_meta.hot?.readonlyEnabled) { - hotPhaseActions.readonly = hotPhaseActions.readonly ?? {}; + if (updatedPolicy.phases.hot!.actions?.searchable_snapshot) { + hotPhaseActions.searchable_snapshot = { + ...hotPhaseActions.searchable_snapshot, + snapshot_repository: _meta.searchableSnapshot.repository, + }; } else { - delete hotPhaseActions.readonly; + delete hotPhaseActions.searchable_snapshot; } - } else { - delete hotPhaseActions.rollover; - delete hotPhaseActions.forcemerge; - delete hotPhaseActions.readonly; } /** - * HOT PHASE SET PRIORITY + * WARM PHASE SERIALIZATION */ - if (!updatedPolicy.phases.hot!.actions?.set_priority) { - delete hotPhaseActions.set_priority; - } + if (_meta.warm.enabled) { + draft.phases.warm!.actions = draft.phases.warm?.actions ?? {}; + const warmPhase = draft.phases.warm!; - /** - * HOT PHASE SHRINK - */ - if (!updatedPolicy.phases.hot?.actions?.shrink) { - delete hotPhaseActions.shrink; - } + /** + * WARM PHASE MIN AGE + * + */ + if (updatedPolicy.phases.warm?.min_age) { + warmPhase.min_age = `${updatedPolicy.phases.warm!.min_age}${_meta.warm.minAgeUnit}`; + } - /** - * HOT PHASE SEARCHABLE SNAPSHOT - */ - if (updatedPolicy.phases.hot!.actions?.searchable_snapshot) { - hotPhaseActions.searchable_snapshot = { - ...hotPhaseActions.searchable_snapshot, - snapshot_repository: _meta.searchableSnapshot.repository, - }; - } else { - delete hotPhaseActions.searchable_snapshot; - } - } + /** + * WARM PHASE DATA ALLOCATION + */ + warmPhase.actions = serializeMigrateAndAllocateActions( + _meta.warm, + warmPhase.actions, + originalPolicy?.phases.warm?.actions, + updatedPolicy.phases.warm?.actions?.allocate?.number_of_replicas + ); - /** - * WARM PHASE SERIALIZATION - */ - if (_meta.warm.enabled) { - draft.phases.warm!.actions = draft.phases.warm?.actions ?? {}; - const warmPhase = draft.phases.warm!; + /** + * WARM PHASE FORCEMERGE + */ + if (!updatedPolicy.phases.warm?.actions?.forcemerge) { + delete warmPhase.actions.forcemerge; + } else if (_meta.warm.bestCompression) { + warmPhase.actions.forcemerge!.index_codec = 'best_compression'; + } else { + delete warmPhase.actions.forcemerge!.index_codec; + } - /** - * WARM PHASE MIN AGE - * - */ - if (updatedPolicy.phases.warm?.min_age) { - warmPhase.min_age = `${updatedPolicy.phases.warm!.min_age}${_meta.warm.minAgeUnit}`; - } + /** + * WARM PHASE READ ONLY + */ + if (_meta.warm.readonlyEnabled) { + warmPhase.actions.readonly = warmPhase.actions.readonly ?? {}; + } else { + delete warmPhase.actions.readonly; + } - /** - * WARM PHASE DATA ALLOCATION - */ - warmPhase.actions = serializeMigrateAndAllocateActions( - _meta.warm, - warmPhase.actions, - originalPolicy?.phases.warm?.actions, - updatedPolicy.phases.warm?.actions?.allocate?.number_of_replicas - ); + /** + * WARM PHASE SET PRIORITY + */ + if (!updatedPolicy.phases.warm?.actions?.set_priority) { + delete warmPhase.actions.set_priority; + } - /** - * WARM PHASE FORCEMERGE - */ - if (!updatedPolicy.phases.warm?.actions?.forcemerge) { - delete warmPhase.actions.forcemerge; - } else if (_meta.warm.bestCompression) { - warmPhase.actions.forcemerge!.index_codec = 'best_compression'; + /** + * WARM PHASE SHRINK + */ + if (!updatedPolicy.phases.warm?.actions?.shrink) { + delete warmPhase.actions.shrink; + } } else { - delete warmPhase.actions.forcemerge!.index_codec; + delete draft.phases.warm; } /** - * WARM PHASE READ ONLY + * COLD PHASE SERIALIZATION */ - if (_meta.warm.readonlyEnabled) { - warmPhase.actions.readonly = warmPhase.actions.readonly ?? {}; - } else { - delete warmPhase.actions.readonly; - } + if (_meta.cold.enabled) { + draft.phases.cold!.actions = draft.phases.cold?.actions ?? {}; + const coldPhase = draft.phases.cold!; - /** - * WARM PHASE SET PRIORITY - */ - if (!updatedPolicy.phases.warm?.actions?.set_priority) { - delete warmPhase.actions.set_priority; - } + /** + * COLD PHASE MIN AGE + */ + if (updatedPolicy.phases.cold?.min_age) { + coldPhase.min_age = `${updatedPolicy.phases.cold!.min_age}${_meta.cold.minAgeUnit}`; + } - /** - * WARM PHASE SHRINK - */ - if (!updatedPolicy.phases.warm?.actions?.shrink) { - delete warmPhase.actions.shrink; - } - } else { - delete draft.phases.warm; - } + /** + * COLD PHASE DATA ALLOCATION + */ + coldPhase.actions = serializeMigrateAndAllocateActions( + _meta.cold, + coldPhase.actions, + originalPolicy?.phases.cold?.actions, + updatedPolicy.phases.cold?.actions?.allocate?.number_of_replicas + ); - /** - * COLD PHASE SERIALIZATION - */ - if (_meta.cold.enabled) { - draft.phases.cold!.actions = draft.phases.cold?.actions ?? {}; - const coldPhase = draft.phases.cold!; + /** + * COLD PHASE FREEZE + */ + if (_meta.cold.freezeEnabled) { + coldPhase.actions.freeze = coldPhase.actions.freeze ?? {}; + } else { + delete coldPhase.actions.freeze; + } - /** - * COLD PHASE MIN AGE - */ - if (updatedPolicy.phases.cold?.min_age) { - coldPhase.min_age = `${updatedPolicy.phases.cold!.min_age}${_meta.cold.minAgeUnit}`; - } + /** + * COLD PHASE READ ONLY + */ + if (_meta.cold.readonlyEnabled) { + coldPhase.actions.readonly = coldPhase.actions.readonly ?? {}; + } else { + delete coldPhase.actions.readonly; + } - /** - * COLD PHASE DATA ALLOCATION - */ - coldPhase.actions = serializeMigrateAndAllocateActions( - _meta.cold, - coldPhase.actions, - originalPolicy?.phases.cold?.actions, - updatedPolicy.phases.cold?.actions?.allocate?.number_of_replicas - ); + /** + * COLD PHASE SET PRIORITY + */ + if (!updatedPolicy.phases.cold?.actions?.set_priority) { + delete coldPhase.actions.set_priority; + } - /** - * COLD PHASE FREEZE - */ - if (_meta.cold.freezeEnabled) { - coldPhase.actions.freeze = coldPhase.actions.freeze ?? {}; + /** + * COLD PHASE SEARCHABLE SNAPSHOT + */ + if (updatedPolicy.phases.cold?.actions?.searchable_snapshot) { + coldPhase.actions.searchable_snapshot = { + ...coldPhase.actions.searchable_snapshot, + snapshot_repository: _meta.searchableSnapshot.repository, + }; + } else { + delete coldPhase.actions.searchable_snapshot; + } } else { - delete coldPhase.actions.freeze; + delete draft.phases.cold; } /** - * COLD PHASE READ ONLY + * FROZEN PHASE SERIALIZATION */ - if (_meta.cold.readonlyEnabled) { - coldPhase.actions.readonly = coldPhase.actions.readonly ?? {}; - } else { - delete coldPhase.actions.readonly; - } + if (_meta.frozen?.enabled) { + draft.phases.frozen!.actions = draft.phases.frozen?.actions ?? {}; + const frozenPhase = draft.phases.frozen!; - /** - * COLD PHASE SET PRIORITY - */ - if (!updatedPolicy.phases.cold?.actions?.set_priority) { - delete coldPhase.actions.set_priority; - } + /** + * FROZEN PHASE MIN AGE + */ + if (updatedPolicy.phases.frozen?.min_age) { + frozenPhase.min_age = `${updatedPolicy.phases.frozen!.min_age}${_meta.frozen.minAgeUnit}`; + } - /** - * COLD PHASE SEARCHABLE SNAPSHOT - */ - if (updatedPolicy.phases.cold?.actions?.searchable_snapshot) { - coldPhase.actions.searchable_snapshot = { - ...coldPhase.actions.searchable_snapshot, - snapshot_repository: _meta.searchableSnapshot.repository, - }; + /** + * FROZEN PHASE SEARCHABLE SNAPSHOT + */ + if (updatedPolicy.phases.frozen?.actions?.searchable_snapshot) { + frozenPhase.actions.searchable_snapshot = { + ...frozenPhase.actions.searchable_snapshot, + snapshot_repository: _meta.searchableSnapshot.repository, + }; + } else { + delete frozenPhase.actions.searchable_snapshot; + } } else { - delete coldPhase.actions.searchable_snapshot; - } - } else { - delete draft.phases.cold; - } - - /** - * FROZEN PHASE SERIALIZATION - */ - if (_meta.frozen?.enabled) { - draft.phases.frozen!.actions = draft.phases.frozen?.actions ?? {}; - const frozenPhase = draft.phases.frozen!; - - /** - * FROZEN PHASE MIN AGE - */ - if (updatedPolicy.phases.frozen?.min_age) { - frozenPhase.min_age = `${updatedPolicy.phases.frozen!.min_age}${_meta.frozen.minAgeUnit}`; + delete draft.phases.frozen; } /** - * FROZEN PHASE SEARCHABLE SNAPSHOT + * DELETE PHASE SERIALIZATION */ - if (updatedPolicy.phases.frozen?.actions?.searchable_snapshot) { - frozenPhase.actions.searchable_snapshot = { - ...frozenPhase.actions.searchable_snapshot, - snapshot_repository: _meta.searchableSnapshot.repository, - }; - } else { - delete frozenPhase.actions.searchable_snapshot; - } - } else { - delete draft.phases.frozen; - } - - /** - * DELETE PHASE SERIALIZATION - */ - if (_meta.delete.enabled) { - const deletePhase = draft.phases.delete!; + if (_meta.delete.enabled) { + const deletePhase = draft.phases.delete!; - /** - * DELETE PHASE DELETE - */ - deletePhase.actions = deletePhase.actions ?? {}; - deletePhase.actions.delete = deletePhase.actions.delete ?? {}; + /** + * DELETE PHASE DELETE + */ + deletePhase.actions = deletePhase.actions ?? {}; + deletePhase.actions.delete = deletePhase.actions.delete ?? {}; - /** - * DELETE PHASE MIN AGE - */ - if (updatedPolicy.phases.delete?.min_age) { - deletePhase.min_age = `${updatedPolicy.phases.delete!.min_age}${_meta.delete.minAgeUnit}`; - } + /** + * DELETE PHASE MIN AGE + */ + if (updatedPolicy.phases.delete?.min_age) { + deletePhase.min_age = `${updatedPolicy.phases.delete!.min_age}${_meta.delete.minAgeUnit}`; + } - /** - * DELETE PHASE WAIT FOR SNAPSHOT - */ - if (!updatedPolicy.phases.delete?.actions?.wait_for_snapshot) { - delete deletePhase.actions.wait_for_snapshot; + /** + * DELETE PHASE WAIT FOR SNAPSHOT + */ + if (!updatedPolicy.phases.delete?.actions?.wait_for_snapshot) { + delete deletePhase.actions.wait_for_snapshot; + } + } else { + delete draft.phases.delete; } - } else { - delete draft.phases.delete; - } - }); -}; + }); + }; diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/validations.ts b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/validations.ts index db43faf6cef1..efa6af4f61d0 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/validations.ts +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/validations.ts @@ -164,110 +164,108 @@ export const createPolicyNameValidations = ({ * For example, the user can't define '5 days' for cold phase if the * warm phase is set to '10 days'. */ -export const minAgeGreaterThanPreviousPhase = (phase: PhaseWithTiming) => ({ - formData, -}: { - formData: Record; -}) => { - if (phase === 'warm') { - return; - } +export const minAgeGreaterThanPreviousPhase = + (phase: PhaseWithTiming) => + ({ formData }: { formData: Record }) => { + if (phase === 'warm') { + return; + } - const getValueFor = (_phase: PhaseWithTiming) => { - const milli = formData[`_meta.${_phase}.minAgeToMilliSeconds`]; + const getValueFor = (_phase: PhaseWithTiming) => { + const milli = formData[`_meta.${_phase}.minAgeToMilliSeconds`]; - const esFormat = - milli >= 0 - ? formData[`phases.${_phase}.min_age`] + formData[`_meta.${_phase}.minAgeUnit`] - : undefined; + const esFormat = + milli >= 0 + ? formData[`phases.${_phase}.min_age`] + formData[`_meta.${_phase}.minAgeUnit`] + : undefined; - return { - milli, - esFormat, + return { + milli, + esFormat, + }; }; - }; - const minAgeValues = { - warm: getValueFor('warm'), - cold: getValueFor('cold'), - frozen: getValueFor('frozen'), - delete: getValueFor('delete'), - }; + const minAgeValues = { + warm: getValueFor('warm'), + cold: getValueFor('cold'), + frozen: getValueFor('frozen'), + delete: getValueFor('delete'), + }; - const i18nErrors = { - greaterThanWarmPhase: i18n.translate( - 'xpack.indexLifecycleMgmt.editPolicy.minAgeSmallerThanWarmPhaseError', - { - defaultMessage: 'Must be greater or equal than the warm phase value ({value})', - values: { - value: minAgeValues.warm.esFormat, - }, - } - ), - greaterThanColdPhase: i18n.translate( - 'xpack.indexLifecycleMgmt.editPolicy.minAgeSmallerThanColdPhaseError', - { - defaultMessage: 'Must be greater or equal than the cold phase value ({value})', - values: { - value: minAgeValues.cold.esFormat, - }, - } - ), - greaterThanFrozenPhase: i18n.translate( - 'xpack.indexLifecycleMgmt.editPolicy.minAgeSmallerThanFrozenPhaseError', - { - defaultMessage: 'Must be greater or equal than the frozen phase value ({value})', - values: { - value: minAgeValues.frozen.esFormat, - }, - } - ), - }; + const i18nErrors = { + greaterThanWarmPhase: i18n.translate( + 'xpack.indexLifecycleMgmt.editPolicy.minAgeSmallerThanWarmPhaseError', + { + defaultMessage: 'Must be greater or equal than the warm phase value ({value})', + values: { + value: minAgeValues.warm.esFormat, + }, + } + ), + greaterThanColdPhase: i18n.translate( + 'xpack.indexLifecycleMgmt.editPolicy.minAgeSmallerThanColdPhaseError', + { + defaultMessage: 'Must be greater or equal than the cold phase value ({value})', + values: { + value: minAgeValues.cold.esFormat, + }, + } + ), + greaterThanFrozenPhase: i18n.translate( + 'xpack.indexLifecycleMgmt.editPolicy.minAgeSmallerThanFrozenPhaseError', + { + defaultMessage: 'Must be greater or equal than the frozen phase value ({value})', + values: { + value: minAgeValues.frozen.esFormat, + }, + } + ), + }; - if (phase === 'cold') { - if (minAgeValues.warm.milli >= 0 && minAgeValues.cold.milli < minAgeValues.warm.milli) { - return { - message: i18nErrors.greaterThanWarmPhase, - }; + if (phase === 'cold') { + if (minAgeValues.warm.milli >= 0 && minAgeValues.cold.milli < minAgeValues.warm.milli) { + return { + message: i18nErrors.greaterThanWarmPhase, + }; + } + return; } - return; - } - if (phase === 'frozen') { - if (minAgeValues.cold.milli >= 0 && minAgeValues.frozen.milli < minAgeValues.cold.milli) { - return { - message: i18nErrors.greaterThanColdPhase, - }; - } else if ( - minAgeValues.warm.milli >= 0 && - minAgeValues.frozen.milli < minAgeValues.warm.milli - ) { - return { - message: i18nErrors.greaterThanWarmPhase, - }; + if (phase === 'frozen') { + if (minAgeValues.cold.milli >= 0 && minAgeValues.frozen.milli < minAgeValues.cold.milli) { + return { + message: i18nErrors.greaterThanColdPhase, + }; + } else if ( + minAgeValues.warm.milli >= 0 && + minAgeValues.frozen.milli < minAgeValues.warm.milli + ) { + return { + message: i18nErrors.greaterThanWarmPhase, + }; + } + return; } - return; - } - if (phase === 'delete') { - if (minAgeValues.frozen.milli >= 0 && minAgeValues.delete.milli < minAgeValues.frozen.milli) { - return { - message: i18nErrors.greaterThanFrozenPhase, - }; - } else if ( - minAgeValues.cold.milli >= 0 && - minAgeValues.delete.milli < minAgeValues.cold.milli - ) { - return { - message: i18nErrors.greaterThanColdPhase, - }; - } else if ( - minAgeValues.warm.milli >= 0 && - minAgeValues.delete.milli < minAgeValues.warm.milli - ) { - return { - message: i18nErrors.greaterThanWarmPhase, - }; + if (phase === 'delete') { + if (minAgeValues.frozen.milli >= 0 && minAgeValues.delete.milli < minAgeValues.frozen.milli) { + return { + message: i18nErrors.greaterThanFrozenPhase, + }; + } else if ( + minAgeValues.cold.milli >= 0 && + minAgeValues.delete.milli < minAgeValues.cold.milli + ) { + return { + message: i18nErrors.greaterThanColdPhase, + }; + } else if ( + minAgeValues.warm.milli >= 0 && + minAgeValues.delete.milli < minAgeValues.warm.milli + ) { + return { + message: i18nErrors.greaterThanWarmPhase, + }; + } } - } -}; + }; diff --git a/x-pack/plugins/index_lifecycle_management/public/plugin.tsx b/x-pack/plugins/index_lifecycle_management/public/plugin.tsx index 339d7a4d7db9..bc0981529c34 100644 --- a/x-pack/plugins/index_lifecycle_management/public/plugin.tsx +++ b/x-pack/plugins/index_lifecycle_management/public/plugin.tsx @@ -20,7 +20,8 @@ import { ClientConfigType, SetupDependencies, StartDependencies } from './types' import { IlmLocatorDefinition } from './locator'; export class IndexLifecycleManagementPlugin - implements Plugin { + implements Plugin +{ constructor(private readonly initializerContext: PluginInitializerContext) {} private breadcrumbService = new BreadcrumbService(); diff --git a/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/__jest__/fixtures.ts b/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/__jest__/fixtures.ts index fe8d685dc2e0..0ebed383e261 100644 --- a/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/__jest__/fixtures.ts +++ b/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/__jest__/fixtures.ts @@ -127,8 +127,7 @@ export const cloudNodeSettingsWithLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -137,8 +136,7 @@ export const cloudNodeSettingsWithLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -354,8 +352,7 @@ export const cloudNodeSettingsWithLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -364,8 +361,7 @@ export const cloudNodeSettingsWithLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -580,8 +576,7 @@ export const cloudNodeSettingsWithLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -590,8 +585,7 @@ export const cloudNodeSettingsWithLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -806,8 +800,7 @@ export const cloudNodeSettingsWithLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -816,8 +809,7 @@ export const cloudNodeSettingsWithLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -1032,8 +1024,7 @@ export const cloudNodeSettingsWithLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -1042,8 +1033,7 @@ export const cloudNodeSettingsWithLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -1269,8 +1259,7 @@ export const cloudNodeSettingsWithoutLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -1279,8 +1268,7 @@ export const cloudNodeSettingsWithoutLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -1496,8 +1484,7 @@ export const cloudNodeSettingsWithoutLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -1506,8 +1493,7 @@ export const cloudNodeSettingsWithoutLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -1722,8 +1708,7 @@ export const cloudNodeSettingsWithoutLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -1732,8 +1717,7 @@ export const cloudNodeSettingsWithoutLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -1948,8 +1932,7 @@ export const cloudNodeSettingsWithoutLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -1958,8 +1941,7 @@ export const cloudNodeSettingsWithoutLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -2174,8 +2156,7 @@ export const cloudNodeSettingsWithoutLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -2184,8 +2165,7 @@ export const cloudNodeSettingsWithoutLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, diff --git a/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/register_list_route.ts b/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/register_list_route.ts index accd8993abc6..314b206d6ea6 100644 --- a/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/register_list_route.ts +++ b/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/register_list_route.ts @@ -88,15 +88,14 @@ export function registerListRoute({ { path: addBasePath('/nodes/list'), validate: false }, license.guardApiRoute(async (context, request, response) => { try { - const settingsResponse = await context.core.elasticsearch.client.asCurrentUser.transport.request( - { + const settingsResponse = + await context.core.elasticsearch.client.asCurrentUser.transport.request({ method: 'GET', path: '/_nodes/settings', querystring: { format: 'json', }, - } - ); + }); const body: ListNodesRouteResponse = convertSettingsIntoLists( settingsResponse.body as Settings, disallowedNodeAttributes diff --git a/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx index 9023a5ac53a9..7ce81fa47df9 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx +++ b/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx @@ -66,19 +66,19 @@ export const setupEnvironment = () => { }; }; -export const WithAppDependencies = (Comp: any, overridingDependencies: any = {}) => ( - props: any -) => { - const mergedDependencies = merge({}, appDependencies, overridingDependencies); - return ( - - - - - - - - - - ); -}; +export const WithAppDependencies = + (Comp: any, overridingDependencies: any = {}) => + (props: any) => { + const mergedDependencies = merge({}, appDependencies, overridingDependencies); + return ( + + + + + + + + + + ); + }; diff --git a/x-pack/plugins/index_management/__jest__/client_integration/home/data_streams_tab.test.ts b/x-pack/plugins/index_management/__jest__/client_integration/home/data_streams_tab.test.ts index 8e114b059694..7c4d2573bdec 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/home/data_streams_tab.test.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/home/data_streams_tab.test.ts @@ -348,11 +348,8 @@ describe('Data Streams tab', () => { describe('when there are special characters', () => { beforeEach(async () => { - const { - setLoadIndicesResponse, - setLoadDataStreamsResponse, - setLoadDataStreamResponse, - } = httpRequestsMockHelpers; + const { setLoadIndicesResponse, setLoadDataStreamsResponse, setLoadDataStreamResponse } = + httpRequestsMockHelpers; setLoadIndicesResponse([ createDataStreamBackingIndex('data-stream-index', '%dataStream'), diff --git a/x-pack/plugins/index_management/common/lib/template_serialization.ts b/x-pack/plugins/index_management/common/lib/template_serialization.ts index 3e6698ac5713..ce49c32cd827 100644 --- a/x-pack/plugins/index_management/common/lib/template_serialization.ts +++ b/x-pack/plugins/index_management/common/lib/template_serialization.ts @@ -16,15 +16,8 @@ import { const hasEntries = (data: object = {}) => Object.entries(data).length > 0; export function serializeTemplate(templateDeserialized: TemplateDeserialized): TemplateSerialized { - const { - version, - priority, - indexPatterns, - template, - composedOf, - dataStream, - _meta, - } = templateDeserialized; + const { version, priority, indexPatterns, template, composedOf, dataStream, _meta } = + templateDeserialized; return { version, @@ -86,10 +79,8 @@ export function deserializeTemplateList( cloudManagedTemplatePrefix?: string ): TemplateListItem[] { return indexTemplates.map(({ name, index_template: templateSerialized }) => { - const { - template: { mappings, settings, aliases } = {}, - ...deserializedTemplate - } = deserializeTemplate({ name, ...templateSerialized }, cloudManagedTemplatePrefix); + const { template: { mappings, settings, aliases } = {}, ...deserializedTemplate } = + deserializeTemplate({ name, ...templateSerialized }, cloudManagedTemplatePrefix); return { ...deserializedTemplate, @@ -150,10 +141,8 @@ export function deserializeLegacyTemplateList( cloudManagedTemplatePrefix?: string ): TemplateListItem[] { return Object.entries(indexTemplatesByName).map(([name, templateSerialized]) => { - const { - template: { mappings, settings, aliases } = {}, - ...deserializedTemplate - } = deserializeLegacyTemplate({ name, ...templateSerialized }, cloudManagedTemplatePrefix); + const { template: { mappings, settings, aliases } = {}, ...deserializedTemplate } = + deserializeLegacyTemplate({ name, ...templateSerialized }, cloudManagedTemplatePrefix); return { ...deserializedTemplate, diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/setup_environment.tsx index ece377b0ee2c..d532eaaba892 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/setup_environment.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/setup_environment.tsx @@ -33,7 +33,7 @@ const appDependencies = { } as any; export const componentTemplatesDependencies = { - httpClient: (mockHttpClient as unknown) as HttpSetup, + httpClient: mockHttpClient as unknown as HttpSetup, apiBasePath: API_BASE_PATH, trackMetric: () => {}, docLinks: docLinksServiceMock.createStartContract(), @@ -51,15 +51,16 @@ export const setupEnvironment = () => { }; }; -export const WithAppDependencies = (Comp: any) => (props: any) => ( - - - - - - - - - / - -); +export const WithAppDependencies = (Comp: any) => (props: any) => + ( + + + + + + + + + / + + ); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/component_template_details.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/component_template_details.tsx index 06a5e8b5c27d..6dbf1b15174e 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/component_template_details.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/component_template_details.tsx @@ -55,9 +55,11 @@ export const ComponentTemplateDetailsFlyoutContent: React.FunctionComponent('summary'); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list.tsx index 77668f7d5507..6ff7c5826459 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list.tsx @@ -42,10 +42,8 @@ export const ComponentTemplateList: React.FunctionComponent = ({ componentTemplateName, history, }) => { - const { - addContent: addContentToGlobalFlyout, - removeContent: removeContentFromGlobalFlyout, - } = useGlobalFlyout(); + const { addContent: addContentToGlobalFlyout, removeContent: removeContentFromGlobalFlyout } = + useGlobalFlyout(); const { api, trackMetric, documentation } = useComponentTemplatesContext(); const { data, isLoading, error, resendRequest } = api.useLoadComponentTemplates(); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.tsx index a1e1cc555766..41be138ea9fa 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.tsx @@ -60,10 +60,8 @@ export const ComponentTemplatesSelector = ({ emptyPrompt: { text, showCreateButton } = {}, }: Props) => { const { data: components, isLoading, error } = useApi().useLoadComponentTemplates(); - const { - addContent: addContentToGlobalFlyout, - removeContent: removeContentFromGlobalFlyout, - } = useGlobalFlyout(); + const { addContent: addContentToGlobalFlyout, removeContent: removeContentFromGlobalFlyout } = + useGlobalFlyout(); const [selectedComponent, setSelectedComponent] = useState(null); const [componentsSelected, setComponentsSelected] = useState([]); const isInitialized = useRef(false); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_clone/component_template_clone.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_clone/component_template_clone.tsx index d19c500c3622..1889da7c1336 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_clone/component_template_clone.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_clone/component_template_clone.tsx @@ -24,9 +24,11 @@ export const ComponentTemplateClone: FunctionComponent { if (error && !isLoading) { diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_form/component_template_form.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_form/component_template_form.tsx index 8763bb8881ed..8d5e61c81120 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_form/component_template_form.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_form/component_template_form.tsx @@ -160,22 +160,21 @@ export const ComponentTemplateForm = ({ }; const buildComponentTemplateObject = useCallback( - (initialTemplate: ComponentTemplateDeserialized) => ( - wizardData: WizardContent - ): ComponentTemplateDeserialized => { - const outputComponentTemplate = { - ...initialTemplate, - name: wizardData.logistics.name, - version: wizardData.logistics.version, - _meta: wizardData.logistics._meta, - template: { - settings: wizardData.settings, - mappings: wizardData.mappings, - aliases: wizardData.aliases, - }, - }; - return cleanupComponentTemplateObject(outputComponentTemplate); - }, + (initialTemplate: ComponentTemplateDeserialized) => + (wizardData: WizardContent): ComponentTemplateDeserialized => { + const outputComponentTemplate = { + ...initialTemplate, + name: wizardData.logistics.name, + version: wizardData.logistics.version, + _meta: wizardData.logistics._meta, + template: { + settings: wizardData.settings, + mappings: wizardData.mappings, + aliases: wizardData.aliases, + }, + }; + return cleanupComponentTemplateObject(outputComponentTemplate); + }, [] ); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_templates_context.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_templates_context.tsx index 94f5befab61c..89b4e9074141 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_templates_context.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_templates_context.tsx @@ -42,15 +42,8 @@ export const ComponentTemplatesProvider = ({ value: Props; children: React.ReactNode; }) => { - const { - httpClient, - apiBasePath, - trackMetric, - docLinks, - toasts, - setBreadcrumbs, - getUrlForApp, - } = value; + const { httpClient, apiBasePath, trackMetric, docLinks, toasts, setBreadcrumbs, getUrlForApp } = + value; const useRequest = getUseRequest(httpClient); const sendRequest = getSendRequest(httpClient); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/lib/request.ts b/x-pack/plugins/index_management/public/application/components/component_templates/lib/request.ts index a7056e27b5ca..92847bbe5dc0 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/lib/request.ts +++ b/x-pack/plugins/index_management/public/application/components/component_templates/lib/request.ts @@ -22,14 +22,14 @@ export type UseRequestHook = ( ) => UseRequestResponse; export type SendRequestHook = (config: SendRequestConfig) => Promise; -export const getUseRequest = (httpClient: HttpSetup): UseRequestHook => ( - config: UseRequestConfig -) => { - return _useRequest(httpClient, config); -}; +export const getUseRequest = + (httpClient: HttpSetup): UseRequestHook => + (config: UseRequestConfig) => { + return _useRequest(httpClient, config); + }; -export const getSendRequest = (httpClient: HttpSetup): SendRequestHook => ( - config: SendRequestConfig -) => { - return _sendRequest(httpClient, config); -}; +export const getSendRequest = + (httpClient: HttpSetup): SendRequestHook => + (config: SendRequestConfig) => { + return _sendRequest(httpClient, config); + }; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/setup_environment.tsx index efd1ec706242..7055dcc74ce7 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/setup_environment.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/setup_environment.tsx @@ -78,12 +78,13 @@ const defaultProps = { docLinks: docLinksServiceMock.createStartContract(), }; -export const WithAppDependencies = (Comp: any) => (props: any) => ( - - - - - - - -); +export const WithAppDependencies = (Comp: any) => (props: any) => + ( + + + + + + + + ); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields.tsx index 7b464a299c24..a28531ed7095 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields.tsx @@ -22,10 +22,8 @@ const { useGlobalFlyout } = GlobalFlyout; export const DocumentFields = React.memo(() => { const { fields, search, documentFields } = useMappingsState(); const dispatch = useDispatch(); - const { - addContent: addContentToGlobalFlyout, - removeContent: removeContentFromGlobalFlyout, - } = useGlobalFlyout(); + const { addContent: addContentToGlobalFlyout, removeContent: removeContentFromGlobalFlyout } = + useGlobalFlyout(); const { editor: editorType } = documentFields; const isEditing = documentFields.status === 'editingField'; 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 bb6a5aae82f1..5d5f0fc0b930 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 @@ -33,9 +33,9 @@ interface Props { const ANALYZER_OPTIONS = PARAMETERS_OPTIONS.analyzer!; // token_count requires a value for "analyzer", therefore, we cannot not allow "index_default" -const ANALYZER_OPTIONS_WITHOUT_DEFAULT = (PARAMETERS_OPTIONS.analyzer as SuperSelectOption[]).filter( - ({ value }) => value !== INDEX_DEFAULT -); +const ANALYZER_OPTIONS_WITHOUT_DEFAULT = ( + PARAMETERS_OPTIONS.analyzer as SuperSelectOption[] +).filter(({ value }) => value !== INDEX_DEFAULT); const getCustomAnalyzers = (indexSettings: IndexSettings): SelectOption[] | undefined => { const settings: IndexSettingsInterface = {}.hasOwnProperty.call(indexSettings, 'index') 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 5ce48f63f0b9..aeb4debddcd6 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 @@ -40,20 +40,20 @@ const getSuggestedFields = ( })) .sort((a, b) => (a.label > b.label ? 1 : a.label < b.label ? -1 : 0)); -const getDeserializer = (allFields: NormalizedFields['byId']): SerializerFunc => ( - value: string | object -): AliasOption[] => { - if (typeof value === 'string' && Boolean(value)) { - return [ - { - id: value, - label: allFields[value].path.join(' > '), - }, - ]; - } +const getDeserializer = + (allFields: NormalizedFields['byId']): SerializerFunc => + (value: string | object): AliasOption[] => { + if (typeof value === 'string' && Boolean(value)) { + return [ + { + id: value, + label: allFields[value].path.join(' > '), + }, + ]; + } - return []; -}; + return []; + }; interface Props { allFields: NormalizedFields['byId']; 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 1a03dec48c97..2a007e7741d4 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 @@ -74,13 +74,12 @@ const getDefaultToggleValue = (param: string, field: FieldType) => { }; export const TextType = React.memo(({ field }: Props) => { - const onIndexPrefixesChanage = (minField: FieldHook, maxField: FieldHook) => ([ - min, - max, - ]: any) => { - minField.setValue(min); - maxField.setValue(max); - }; + const onIndexPrefixesChanage = + (minField: FieldHook, maxField: FieldHook) => + ([min, max]: any) => { + minField.setValue(min); + maxField.setValue(max); + }; return ( <> diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/fields_list_item.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/fields_list_item.tsx index 35944e9b3e80..35271728266c 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/fields_list_item.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/fields_list_item.tsx @@ -135,12 +135,8 @@ function FieldListItemComponent( return null; } - const { - addMultiFieldButtonLabel, - addPropertyButtonLabel, - editButtonLabel, - deleteButtonLabel, - } = i18nTexts; + const { addMultiFieldButtonLabel, addPropertyButtonLabel, editButtonLabel, deleteButtonLabel } = + i18nTexts; return ( 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 34fbe0c48c3b..8e815e03dcf9 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 @@ -37,20 +37,22 @@ const setup = (props: any) => defaultProps: props, })(); -const openModalWithJsonContent = ({ component, find }: TestBed) => (json: any) => { - act(() => { - find('load-json-button').simulate('click'); - }); +const openModalWithJsonContent = + ({ component, find }: TestBed) => + (json: any) => { + act(() => { + find('load-json-button').simulate('click'); + }); - component.update(); + component.update(); - act(() => { - // Set the mappings to load - find('mockCodeEditor').simulate('change', { - jsonString: JSON.stringify(json), + act(() => { + // Set the mappings to load + find('mockCodeEditor').simulate('change', { + jsonString: JSON.stringify(json), + }); }); - }); -}; + }; describe('', () => { test('it should forward valid mapping definition', () => { diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/runtime_fields/runtime_fields_list.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/runtime_fields/runtime_fields_list.tsx index 387c53e3353f..13cbd8e22732 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/runtime_fields/runtime_fields_list.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/runtime_fields/runtime_fields_list.tsx @@ -34,10 +34,8 @@ export const RuntimeFieldsList = () => { const dispatch = useDispatch(); - const { - addContent: addContentToGlobalFlyout, - removeContent: removeContentFromGlobalFlyout, - } = useGlobalFlyout(); + const { addContent: addContentToGlobalFlyout, removeContent: removeContentFromGlobalFlyout } = + useGlobalFlyout(); const { value: { docLinks }, 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 2abaeb45639b..3eb2f8d6371d 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 @@ -284,9 +284,8 @@ export const validateMappings = (mappings: any = {}): MappingsValidatorResponse const { properties, dynamic_templates: dynamicTemplates, ...mappingsConfiguration } = mappings; - const { value: parsedConfiguration, errors: configurationErrors } = validateMappingsConfiguration( - mappingsConfiguration - ); + const { value: parsedConfiguration, errors: configurationErrors } = + validateMappingsConfiguration(mappingsConfiguration); const { value: parsedProperties, errors: propertiesErrors } = validateProperties(properties); const errors = [...configurationErrors, ...propertiesErrors]; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_editor.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_editor.tsx index bf5edd68668d..6f48159d62a5 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_editor.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_editor.tsx @@ -52,54 +52,51 @@ interface Props { } export const MappingsEditor = React.memo(({ onChange, value, docLinks, indexSettings }: Props) => { - const { - parsedDefaultValue, - multipleMappingsDeclared, - mappingsType, - } = useMemo(() => { - const mappingsDefinition = extractMappingsDefinition(value); - - if (mappingsDefinition === null) { - return { multipleMappingsDeclared: true }; - } + const { parsedDefaultValue, multipleMappingsDeclared, mappingsType } = + useMemo(() => { + const mappingsDefinition = extractMappingsDefinition(value); + + if (mappingsDefinition === null) { + return { multipleMappingsDeclared: true }; + } - const { - _source, - _meta, - _routing, - dynamic, - properties, - runtime, - /* eslint-disable @typescript-eslint/naming-convention */ - numeric_detection, - date_detection, - dynamic_date_formats, - dynamic_templates, - } = mappingsDefinition.mappings; - - const parsed = { - configuration: { + const { _source, _meta, _routing, dynamic, + properties, + runtime, + /* eslint-disable @typescript-eslint/naming-convention */ numeric_detection, date_detection, dynamic_date_formats, - }, - fields: properties, - templates: { dynamic_templates, - }, - runtime, - }; - - return { - parsedDefaultValue: parsed, - multipleMappingsDeclared: false, - mappingsType: mappingsDefinition.type, - }; - }, [value]); + } = mappingsDefinition.mappings; + + const parsed = { + configuration: { + _source, + _meta, + _routing, + dynamic, + numeric_detection, + date_detection, + dynamic_date_formats, + }, + fields: properties, + templates: { + dynamic_templates, + }, + runtime, + }; + + return { + parsedDefaultValue: parsed, + multipleMappingsDeclared: false, + mappingsType: mappingsDefinition.type, + }; + }, [value]); /** * Hook that will listen to: diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/use_state_listener.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/use_state_listener.tsx index cf1f9e1bc39e..7b6f4e7460e9 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/use_state_listener.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/use_state_listener.tsx @@ -42,9 +42,10 @@ export const useMappingsStateListener = ({ onChange, value, mappingsType }: Args const { fields: mappedFields, runtime: runtimeFields } = value ?? {}; const parsedFieldsDefaultValue = useMemo(() => normalize(mappedFields), [mappedFields]); - const parsedRuntimeFieldsDefaultValue = useMemo(() => normalizeRuntimeFields(runtimeFields), [ - runtimeFields, - ]); + const parsedRuntimeFieldsDefaultValue = useMemo( + () => normalizeRuntimeFields(runtimeFields), + [runtimeFields] + ); useEffect(() => { // If we are creating a new field, but haven't entered any name 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 4ccd77d275a9..a0362b440cb0 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 @@ -196,22 +196,21 @@ export const TemplateForm = ({ }; const buildTemplateObject = useCallback( - (initialTemplate: TemplateDeserialized) => ( - wizardData: WizardContent - ): TemplateDeserialized => { - const outputTemplate = { - ...wizardData.logistics, - _kbnMeta: initialTemplate._kbnMeta, - composedOf: wizardData.components, - template: { - settings: wizardData.settings, - mappings: wizardData.mappings, - aliases: wizardData.aliases, - }, - }; - - return cleanupTemplateObject(outputTemplate); - }, + (initialTemplate: TemplateDeserialized) => + (wizardData: WizardContent): TemplateDeserialized => { + const outputTemplate = { + ...wizardData.logistics, + _kbnMeta: initialTemplate._kbnMeta, + composedOf: wizardData.components, + template: { + settings: wizardData.settings, + mappings: wizardData.mappings, + aliases: wizardData.aliases, + }, + }; + + return cleanupTemplateObject(outputTemplate); + }, [] ); diff --git a/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_list.tsx b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_list.tsx index 7bd7c163837d..583d1fcb83ed 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_list.tsx +++ b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_list.tsx @@ -61,7 +61,12 @@ export const DataStreamList: React.FunctionComponent(false); const [saveError, setSaveError] = useState(null); - const { error: templateToCloneError, data: templateToClone, isLoading } = useLoadIndexTemplate( - decodedTemplateName, - isLegacy - ); + const { + error: templateToCloneError, + data: templateToClone, + isLoading, + } = useLoadIndexTemplate(decodedTemplateName, isLegacy); const onSave = async (template: TemplateDeserialized) => { setIsSaving(true); 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 75dc762b8f89..179aa73b4f0a 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 @@ -14,19 +14,21 @@ 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) => { - dispatch(clearCacheIndicesStart({ indexNames })); - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.clearCacheIndicesAction.successMessage', { - defaultMessage: 'Successfully cleared cache: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const clearCacheIndices = + ({ indexNames }) => + async (dispatch) => { + dispatch(clearCacheIndicesStart({ indexNames })); + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.clearCacheIndicesAction.successMessage', { + defaultMessage: 'Successfully cleared cache: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + }; 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 4ba2db666e00..1669d6b1b022 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 @@ -12,19 +12,21 @@ 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) => { - dispatch(closeIndicesStart({ indexNames })); - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.closeIndicesAction.successfullyClosedIndicesMessage', { - defaultMessage: 'Successfully closed: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const closeIndices = + ({ indexNames }) => + async (dispatch) => { + dispatch(closeIndicesStart({ indexNames })); + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.closeIndicesAction.successfullyClosedIndicesMessage', { + defaultMessage: 'Successfully closed: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + }; 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 d886b35879d4..307c359b0fe2 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 @@ -12,18 +12,20 @@ import { notificationService } from '../../services/notification'; import { clearRowStatus } from '../actions'; export const deleteIndicesSuccess = createAction('INDEX_MANAGEMENT_DELETE_INDICES_SUCCESS'); -export const deleteIndices = ({ indexNames }) => async (dispatch) => { - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.deleteIndicesAction.successfullyDeletedIndicesMessage', { - defaultMessage: 'Successfully deleted: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); - dispatch(deleteIndicesSuccess({ indexNames })); -}; +export const deleteIndices = + ({ indexNames }) => + async (dispatch) => { + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.deleteIndicesAction.successfullyDeletedIndicesMessage', { + defaultMessage: 'Successfully deleted: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + dispatch(deleteIndicesSuccess({ indexNames })); + }; 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 0ebb36f68311..4a82ced82eb8 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 @@ -10,27 +10,29 @@ import { loadIndexSettings as request } from '../../services'; import { notificationService } from '../../services/notification'; import { loadIndexDataSuccess } from './load_index_data'; -export const editIndexSettings = ({ indexName }) => async (dispatch) => { - let indexSettings; - try { - indexSettings = await request(indexName); - } catch (error) { - return notificationService.showDangerToast(error.message); - } - notificationService.showSuccessToast( - i18n.translate( - 'xpack.idxMgmt.editIndexSettingsAction.successfullySavedSettingsForIndicesMessage', - { - defaultMessage: 'Successfully saved settings for {indexName}', - values: { indexName }, - } - ) - ); - dispatch( - loadIndexDataSuccess({ - data: indexSettings, - panelType: 'editIndexSettings', - indexName, - }) - ); -}; +export const editIndexSettings = + ({ indexName }) => + async (dispatch) => { + let indexSettings; + try { + indexSettings = await request(indexName); + } catch (error) { + return notificationService.showDangerToast(error.message); + } + notificationService.showSuccessToast( + i18n.translate( + 'xpack.idxMgmt.editIndexSettingsAction.successfullySavedSettingsForIndicesMessage', + { + defaultMessage: 'Successfully saved settings for {indexName}', + values: { indexName }, + } + ) + ); + dispatch( + loadIndexDataSuccess({ + data: indexSettings, + panelType: 'editIndexSettings', + 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 97937f67f9ae..eda9d32d75fb 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 @@ -9,15 +9,15 @@ import { reloadIndices } from '../actions'; import { notificationService } from '../../services/notification'; import { httpService } from '../../services/http'; -export const performExtensionAction = ({ requestMethod, indexNames, successMessage }) => async ( - dispatch -) => { - try { - await requestMethod(indexNames, httpService.httpClient); - } catch (error) { - notificationService.showDangerToast(error.message); - return; - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast(successMessage); -}; +export const performExtensionAction = + ({ requestMethod, indexNames, successMessage }) => + async (dispatch) => { + try { + await requestMethod(indexNames, httpService.httpClient); + } catch (error) { + notificationService.showDangerToast(error.message); + return; + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast(successMessage); + }; 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 f3dae725947e..364b87e9f2bb 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 @@ -13,19 +13,21 @@ import { notificationService } from '../../services/notification'; export const flushIndicesStart = createAction('INDEX_MANAGEMENT_FLUSH_INDICES_START'); -export const flushIndices = ({ indexNames }) => async (dispatch) => { - dispatch(flushIndicesStart({ indexNames })); - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.flushIndicesAction.successfullyFlushedIndicesMessage', { - defaultMessage: 'Successfully flushed: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const flushIndices = + ({ indexNames }) => + async (dispatch) => { + dispatch(flushIndicesStart({ indexNames })); + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.flushIndicesAction.successfullyFlushedIndicesMessage', { + defaultMessage: 'Successfully flushed: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + }; 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 726e5a1fbed2..60f5da7d4925 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 @@ -13,19 +13,24 @@ import { notificationService } from '../../services/notification'; export const forcemergeIndicesStart = createAction('INDEX_MANAGEMENT_FORCEMERGE_INDICES_START'); -export const forcemergeIndices = ({ indexNames, maxNumSegments }) => async (dispatch) => { - dispatch(forcemergeIndicesStart({ indexNames })); - try { - await request(indexNames, maxNumSegments); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.forceMergeIndicesAction.successfullyForceMergedIndicesMessage', { - defaultMessage: 'Successfully force merged: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const forcemergeIndices = + ({ indexNames, maxNumSegments }) => + async (dispatch) => { + dispatch(forcemergeIndicesStart({ indexNames })); + try { + await request(indexNames, maxNumSegments); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate( + 'xpack.idxMgmt.forceMergeIndicesAction.successfullyForceMergedIndicesMessage', + { + defaultMessage: 'Successfully force merged: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + } + ) + ); + }; 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 f06239cc0d1b..002b0c5f00c9 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 @@ -13,19 +13,21 @@ import { notificationService } from '../../services/notification'; export const freezeIndicesStart = createAction('INDEX_MANAGEMENT_FREEZE_INDICES_START'); -export const freezeIndices = ({ indexNames }) => async (dispatch) => { - dispatch(freezeIndicesStart({ indexNames })); - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.freezeIndicesAction.successfullyFrozeIndicesMessage', { - defaultMessage: 'Successfully froze: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const freezeIndices = + ({ indexNames }) => + async (dispatch) => { + dispatch(freezeIndicesStart({ indexNames })); + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.freezeIndicesAction.successfullyFrozeIndicesMessage', { + defaultMessage: 'Successfully froze: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + }; 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 0fc37fa7cc98..18925d6d05e6 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 @@ -11,12 +11,14 @@ import { notificationService } from '../../services/notification'; export const loadIndexDataSuccess = createAction('INDEX_MANAGEMENT_LOAD_INDEX_DATA_SUCCESS'); -export const loadIndexData = ({ indexName, dataType }) => async (dispatch) => { - let data; - try { - data = await request(dataType, indexName); - } catch (error) { - notificationService.showDangerToast(error.message); - } - dispatch(loadIndexDataSuccess({ data, indexName })); -}; +export const loadIndexData = + ({ indexName, dataType }) => + async (dispatch) => { + let data; + try { + data = await request(dataType, indexName); + } catch (error) { + notificationService.showDangerToast(error.message); + } + dispatch(loadIndexDataSuccess({ data, indexName })); + }; 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 7c74f0ae870e..73a4a3350b84 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 @@ -13,19 +13,21 @@ import { notificationService } from '../../services/notification'; export const openIndicesStart = createAction('INDEX_MANAGEMENT_OPEN_INDICES_START'); -export const openIndices = ({ indexNames }) => async (dispatch) => { - dispatch(openIndicesStart({ indexNames })); - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.openIndicesAction.successfullyOpenedIndicesMessage', { - defaultMessage: 'Successfully opened: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const openIndices = + ({ indexNames }) => + async (dispatch) => { + dispatch(openIndicesStart({ indexNames })); + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.openIndicesAction.successfullyOpenedIndicesMessage', { + defaultMessage: 'Successfully opened: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + }; 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 0f1162bacc81..77944344c47c 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 @@ -13,19 +13,21 @@ 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) => { - dispatch(refreshIndicesStart({ indexNames })); - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.refreshIndicesAction.successfullyRefreshedIndicesMessage', { - defaultMessage: 'Successfully refreshed: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const refreshIndices = + ({ indexNames }) => + async (dispatch) => { + dispatch(refreshIndicesStart({ indexNames })); + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.refreshIndicesAction.successfullyRefreshedIndicesMessage', { + defaultMessage: 'Successfully refreshed: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + }; 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 9b0220e33b17..96d38c48f240 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 @@ -13,19 +13,21 @@ import { notificationService } from '../../services/notification'; export const unfreezeIndicesStart = createAction('INDEX_MANAGEMENT_UNFREEZE_INDICES_START'); -export const unfreezeIndices = ({ indexNames }) => async (dispatch) => { - dispatch(unfreezeIndicesStart({ indexNames })); - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.unfreezeIndicesAction.successfullyUnfrozeIndicesMessage', { - defaultMessage: 'Successfully unfroze: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const unfreezeIndices = + ({ indexNames }) => + async (dispatch) => { + dispatch(unfreezeIndicesStart({ indexNames })); + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.unfreezeIndicesAction.successfullyUnfrozeIndicesMessage', { + defaultMessage: 'Successfully unfroze: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + }; 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 5d2fd5353fe0..bbb251634976 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 @@ -18,24 +18,26 @@ export const updateIndexSettingsError = createAction( 'INDEX_MANAGEMENT_UPDATE_INDEX_SETTINGS_ERROR' ); -export const updateIndexSettings = ({ indexName, settings }) => async (dispatch) => { - if (Object.keys(settings).length !== 0) { - try { - const { error, message } = await request(indexName, settings); +export const updateIndexSettings = + ({ indexName, settings }) => + async (dispatch) => { + if (Object.keys(settings).length !== 0) { + try { + const { error, message } = await request(indexName, settings); - if (error) { - return dispatch(updateIndexSettingsError({ error: message })); + if (error) { + return dispatch(updateIndexSettingsError({ error: message })); + } + } catch (error) { + return dispatch(updateIndexSettingsError({ error: error.message })); } - } catch (error) { - return dispatch(updateIndexSettingsError({ error: error.message })); } - } - dispatch(updateIndexSettingsSuccess()); - dispatch(reloadIndices([indexName])); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.updateIndexSettingsAction.settingsSuccessUpdateMessage', { - defaultMessage: 'Successfully updated settings for index {indexName}', - values: { indexName }, - }) - ); -}; + dispatch(updateIndexSettingsSuccess()); + dispatch(reloadIndices([indexName])); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.updateIndexSettingsAction.settingsSuccessUpdateMessage', { + defaultMessage: 'Successfully updated settings for index {indexName}', + values: { indexName }, + }) + ); + }; diff --git a/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.test.ts b/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.test.ts index fdbf0db89e68..2c5070ab846a 100644 --- a/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.test.ts +++ b/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.test.ts @@ -19,7 +19,7 @@ const httpService = httpServiceMock.createSetupContract(); const mockedIndexDataEnricher = new IndexDataEnricher(); const mockRouteContext = ({ hasPrivileges }: { hasPrivileges: unknown }): RequestHandlerContext => { - const routeContextMock = ({ + const routeContextMock = { core: { elasticsearch: { client: { @@ -31,7 +31,7 @@ const mockRouteContext = ({ hasPrivileges }: { hasPrivileges: unknown }): Reques }, }, }, - } as unknown) as RequestHandlerContext; + } as unknown as RequestHandlerContext; return routeContextMock; }; diff --git a/x-pack/plugins/infra/common/formatters/index.ts b/x-pack/plugins/infra/common/formatters/index.ts index a4aeee808482..372df5b28ca1 100644 --- a/x-pack/plugins/infra/common/formatters/index.ts +++ b/x-pack/plugins/infra/common/formatters/index.ts @@ -25,13 +25,13 @@ export const FORMATTERS = { highPercision: formatHighPercision, }; -export const createFormatter = (format: InventoryFormatterType, template: string = '{{value}}') => ( - val: string | number -) => { - if (val == null) { - return ''; - } - const fmtFn = FORMATTERS[format]; - const value = fmtFn(Number(val)); - return template.replace(/{{value}}/g, value); -}; +export const createFormatter = + (format: InventoryFormatterType, template: string = '{{value}}') => + (val: string | number) => { + if (val == null) { + return ''; + } + const fmtFn = FORMATTERS[format]; + const value = fmtFn(Number(val)); + return template.replace(/{{value}}/g, value); + }; diff --git a/x-pack/plugins/infra/common/http_api/log_sources/patch_log_source_configuration.ts b/x-pack/plugins/infra/common/http_api/log_sources/patch_log_source_configuration.ts index 30f53bc256cd..a16f0651e7e5 100644 --- a/x-pack/plugins/infra/common/http_api/log_sources/patch_log_source_configuration.ts +++ b/x-pack/plugins/infra/common/http_api/log_sources/patch_log_source_configuration.ts @@ -44,7 +44,8 @@ export type PatchLogSourceConfigurationRequestBody = rt.TypeOf< * response */ -export const patchLogSourceConfigurationSuccessResponsePayloadRT = getLogSourceConfigurationSuccessResponsePayloadRT; +export const patchLogSourceConfigurationSuccessResponsePayloadRT = + getLogSourceConfigurationSuccessResponsePayloadRT; export type PatchLogSourceConfigurationSuccessResponsePayload = rt.TypeOf< typeof patchLogSourceConfigurationSuccessResponsePayloadRT diff --git a/x-pack/plugins/infra/common/inventory_models/create_tsvb_model.ts b/x-pack/plugins/infra/common/inventory_models/create_tsvb_model.ts index 4280ef40a824..5c9b3beb31c7 100644 --- a/x-pack/plugins/infra/common/inventory_models/create_tsvb_model.ts +++ b/x-pack/plugins/infra/common/inventory_models/create_tsvb_model.ts @@ -7,19 +7,21 @@ import { TSVBMetricModelCreator, TSVBMetricModel, TSVBSeries, InventoryMetric } from './types'; -export const createTSVBModel = ( - id: InventoryMetric, - requires: string[], - series: TSVBSeries[], - interval = '>=300s', - dropLastBucket = true -): TSVBMetricModelCreator => (timeField, indexPattern): TSVBMetricModel => ({ - id, - requires, - drop_last_bucket: dropLastBucket, - index_pattern: indexPattern, - interval, - time_field: timeField, - type: 'timeseries', - series, -}); +export const createTSVBModel = + ( + id: InventoryMetric, + requires: string[], + series: TSVBSeries[], + interval = '>=300s', + dropLastBucket = true + ): TSVBMetricModelCreator => + (timeField, indexPattern): TSVBMetricModel => ({ + id, + requires, + drop_last_bucket: dropLastBucket, + index_pattern: indexPattern, + interval, + time_field: timeField, + type: 'timeseries', + series, + }); 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 691ebec3c829..b881396963d1 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 @@ -34,9 +34,10 @@ export const MetricsAndGroupByToolbarItems = (props: Props) => { [props.metricTypes] ); - const groupByOptions = useMemo(() => props.groupByFields.map(toGroupByOpt), [ - props.groupByFields, - ]); + const groupByOptions = useMemo( + () => props.groupByFields.map(toGroupByOpt), + [props.groupByFields] + ); return ( <> diff --git a/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts b/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts index ee831d9a98eb..9c41a216c7f9 100644 --- a/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts +++ b/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts @@ -106,9 +106,9 @@ const resolveKibanaIndexPatternReference = async ( const resolveRuntimeMappings = (indexPattern: IndexPattern): estypes.MappingRuntimeFields => { const { runtimeFields } = indexPattern.getComputedFields(); - const runtimeMappingsFromIndexPattern = (Object.entries(runtimeFields) as ObjectEntries< - typeof runtimeFields - >).reduce( + const runtimeMappingsFromIndexPattern = ( + Object.entries(runtimeFields) as ObjectEntries + ).reduce( (accumulatedMappings, [runtimeFieldName, runtimeFieldSpec]) => ({ ...accumulatedMappings, [runtimeFieldName]: { diff --git a/x-pack/plugins/infra/common/runtime_types.ts b/x-pack/plugins/infra/common/runtime_types.ts index 43c1e3f52055..06df361b3de4 100644 --- a/x-pack/plugins/infra/common/runtime_types.ts +++ b/x-pack/plugins/infra/common/runtime_types.ts @@ -45,21 +45,25 @@ export const throwErrors = (createError: ErrorFactory) => (errors: Errors) => { throw createError(formatErrors(errors)); }; -export const decodeOrThrow = ( - runtimeType: Type, - createError: ErrorFactory = createPlainError -) => (inputValue: InputValue) => - pipe(runtimeType.decode(inputValue), fold(throwErrors(createError), identity)); +export const decodeOrThrow = + ( + runtimeType: Type, + createError: ErrorFactory = createPlainError + ) => + (inputValue: InputValue) => + pipe(runtimeType.decode(inputValue), fold(throwErrors(createError), identity)); type ValdidationResult = ReturnType>; -export const createValidationFunction = ( - runtimeType: Type -): RouteValidationFunction => (inputValue, { badRequest, ok }) => - pipe( - runtimeType.decode(inputValue), - fold>( - (errors: Errors) => badRequest(formatErrors(errors)), - (result: DecodedValue) => ok(result) - ) - ); +export const createValidationFunction = + ( + runtimeType: Type + ): RouteValidationFunction => + (inputValue, { badRequest, ok }) => + pipe( + runtimeType.decode(inputValue), + fold>( + (errors: Errors) => badRequest(formatErrors(errors)), + (result: DecodedValue) => ok(result) + ) + ); diff --git a/x-pack/plugins/infra/common/time/time_key.ts b/x-pack/plugins/infra/common/time/time_key.ts index 0647c6dcab42..42b14625d22a 100644 --- a/x-pack/plugins/infra/common/time/time_key.ts +++ b/x-pack/plugins/infra/common/time/time_key.ts @@ -54,10 +54,10 @@ export function compareTimeKeys( return timeComparison; } -export const compareToTimeKey = ( - keyAccessor: (value: Value) => TimeKey, - compareValues?: Comparator -) => (value: Value, key: TimeKey) => compareTimeKeys(keyAccessor(value), key, compareValues); +export const compareToTimeKey = + (keyAccessor: (value: Value) => TimeKey, compareValues?: Comparator) => + (value: Value, key: TimeKey) => + compareTimeKeys(keyAccessor(value), key, compareValues); export const getIndexAtTimeKey = ( keyAccessor: (value: Value) => TimeKey, diff --git a/x-pack/plugins/infra/common/utility_types.ts b/x-pack/plugins/infra/common/utility_types.ts index 1f26309973f0..49d60c31a71e 100644 --- a/x-pack/plugins/infra/common/utility_types.ts +++ b/x-pack/plugins/infra/common/utility_types.ts @@ -12,10 +12,9 @@ export type Pick3 = T & - { - [prop in Prop]-?: NonNullable; - }; +export type MandatoryProperty = T & { + [prop in Prop]-?: NonNullable; +}; /** * Portions of below code are derived from https://github.com/tycho01/typical diff --git a/x-pack/plugins/infra/public/alerting/common/components/metrics_alert_dropdown.tsx b/x-pack/plugins/infra/public/alerting/common/components/metrics_alert_dropdown.tsx index 5cbd1909054a..b92144d37eaa 100644 --- a/x-pack/plugins/infra/public/alerting/common/components/metrics_alert_dropdown.tsx +++ b/x-pack/plugins/infra/public/alerting/common/components/metrics_alert_dropdown.tsx @@ -26,9 +26,10 @@ export const MetricsAlertDropdown = () => { const [visibleFlyoutType, setVisibleFlyoutType] = useState(null); const uiCapabilities = useKibana().services.application?.capabilities; - const canCreateAlerts = useMemo(() => Boolean(uiCapabilities?.infrastructure?.save), [ - uiCapabilities, - ]); + const canCreateAlerts = useMemo( + () => Boolean(uiCapabilities?.infrastructure?.save), + [uiCapabilities] + ); const closeFlyout = useCallback(() => setVisibleFlyoutType(null), [setVisibleFlyoutType]); diff --git a/x-pack/plugins/infra/public/alerting/inventory/components/expression.tsx b/x-pack/plugins/infra/public/alerting/inventory/components/expression.tsx index 78005d9d87cf..f72c9d453142 100644 --- a/x-pack/plugins/infra/public/alerting/inventory/components/expression.tsx +++ b/x-pack/plugins/infra/public/alerting/inventory/components/expression.tsx @@ -119,9 +119,10 @@ export const Expressions: React.FC = (props) => { const [timeSize, setTimeSize] = useState(1); const [timeUnit, setTimeUnit] = useState('m'); - const derivedIndexPattern = useMemo(() => createDerivedIndexPattern(), [ - createDerivedIndexPattern, - ]); + const derivedIndexPattern = useMemo( + () => createDerivedIndexPattern(), + [createDerivedIndexPattern] + ); const updateParams = useCallback( (id, e: InventoryMetricConditions) => { @@ -436,16 +437,8 @@ export const ExpressionRow: React.FC = (props) => { const [isExpanded, setRowState] = useState(true); const toggleRowState = useCallback(() => setRowState(!isExpanded), [isExpanded]); - const { - children, - setAlertParams, - expression, - errors, - expressionId, - remove, - canDelete, - fields, - } = props; + const { children, setAlertParams, expression, errors, expressionId, remove, canDelete, fields } = + props; const { metric, comparator = Comparator.GT, diff --git a/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/editor.tsx b/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/editor.tsx index 4eb0f3e8645c..2664a0d6aa2b 100644 --- a/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/editor.tsx +++ b/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/editor.tsx @@ -159,175 +159,177 @@ export const SourceStatusWrapper: React.FC = ({ children }) => { ); }; -export const Editor: React.FC< - AlertTypeParamsExpressionProps -> = (props) => { - const { setAlertParams, alertParams, errors } = props; - const [hasSetDefaults, setHasSetDefaults] = useState(false); - const { sourceId, resolvedSourceConfiguration } = useLogSourceContext(); - - const { - criteria: criteriaErrors, - threshold: thresholdErrors, - timeSizeUnit: timeSizeUnitErrors, - timeWindowSize: timeWindowSizeErrors, - } = useMemo(() => decodeOrThrow(errorsRT)(errors), [errors]); - - const supportedFields = useMemo(() => { - if (resolvedSourceConfiguration?.fields) { - return resolvedSourceConfiguration.fields.filter((field) => { - return (field.type === 'string' || field.type === 'number') && field.searchable; - }); - } else { - return []; - } - }, [resolvedSourceConfiguration]); - - const groupByFields = useMemo(() => { - if (resolvedSourceConfiguration?.fields) { - return resolvedSourceConfiguration.fields.filter((field) => { - return field.type === 'string' && field.aggregatable; - }); - } else { - return []; - } - }, [resolvedSourceConfiguration]); - - const updateThreshold = useCallback( - (thresholdParams) => { - const nextThresholdParams = { ...alertParams.count, ...thresholdParams }; - setAlertParams('count', nextThresholdParams); - }, - [alertParams.count, setAlertParams] - ); - - const updateCriteria = useCallback( - (criteria: PartialCriteriaType) => { - setAlertParams('criteria', criteria); - }, - [setAlertParams] - ); - - const updateTimeSize = useCallback( - (ts: number | undefined) => { - setAlertParams('timeSize', ts); - }, - [setAlertParams] - ); - - const updateTimeUnit = useCallback( - (tu: string) => { - if (timeUnitRT.is(tu)) { - setAlertParams('timeUnit', tu); +export const Editor: React.FC> = + (props) => { + const { setAlertParams, alertParams, errors } = props; + const [hasSetDefaults, setHasSetDefaults] = useState(false); + const { sourceId, resolvedSourceConfiguration } = useLogSourceContext(); + + const { + criteria: criteriaErrors, + threshold: thresholdErrors, + timeSizeUnit: timeSizeUnitErrors, + timeWindowSize: timeWindowSizeErrors, + } = useMemo(() => decodeOrThrow(errorsRT)(errors), [errors]); + + const supportedFields = useMemo(() => { + if (resolvedSourceConfiguration?.fields) { + return resolvedSourceConfiguration.fields.filter((field) => { + return (field.type === 'string' || field.type === 'number') && field.searchable; + }); + } else { + return []; } - }, - [setAlertParams] - ); - - const updateGroupBy = useCallback( - (groups: string[]) => { - setAlertParams('groupBy', groups); - }, - [setAlertParams] - ); - - const defaultCountAlertParams = useMemo(() => createDefaultCountAlertParams(supportedFields), [ - supportedFields, - ]); - - const updateType = useCallback( - (type: ThresholdType) => { - const defaults = - type === 'count' ? defaultCountAlertParams : createDefaultRatioAlertParams(supportedFields); - // Reset properties that don't make sense switching from one context to the other - setAlertParams('count', defaults.count); - setAlertParams('criteria', defaults.criteria); - }, - [defaultCountAlertParams, setAlertParams, supportedFields] - ); + }, [resolvedSourceConfiguration]); + + const groupByFields = useMemo(() => { + if (resolvedSourceConfiguration?.fields) { + return resolvedSourceConfiguration.fields.filter((field) => { + return field.type === 'string' && field.aggregatable; + }); + } else { + return []; + } + }, [resolvedSourceConfiguration]); + + const updateThreshold = useCallback( + (thresholdParams) => { + const nextThresholdParams = { ...alertParams.count, ...thresholdParams }; + setAlertParams('count', nextThresholdParams); + }, + [alertParams.count, setAlertParams] + ); - useMount(() => { - const newAlertParams = { ...defaultCountAlertParams, ...alertParams }; - for (const [key, value] of Object.entries(newAlertParams) as ObjectEntries< - typeof newAlertParams - >) { - setAlertParams(key, value); - } - setHasSetDefaults(true); - }); + const updateCriteria = useCallback( + (criteria: PartialCriteriaType) => { + setAlertParams('criteria', criteria); + }, + [setAlertParams] + ); - const shouldShowGroupByOptimizationWarning = useMemo(() => { - const hasSetGroupBy = alertParams.groupBy && alertParams.groupBy.length > 0; - return ( - hasSetGroupBy && - alertParams.count && - !isOptimizableGroupedThreshold(alertParams.count.comparator, alertParams.count.value) + const updateTimeSize = useCallback( + (ts: number | undefined) => { + setAlertParams('timeSize', ts); + }, + [setAlertParams] ); - }, [alertParams]); - - // Wait until the alert param defaults have been set - if (!hasSetDefaults) return null; - - const criteriaComponent = alertParams.criteria ? ( - - ) : null; - return ( - <> - + const updateTimeUnit = useCallback( + (tu: string) => { + if (timeUnitRT.is(tu)) { + setAlertParams('timeUnit', tu); + } + }, + [setAlertParams] + ); - {alertParams.criteria && !isRatioAlert(alertParams.criteria) && criteriaComponent} + const updateGroupBy = useCallback( + (groups: string[]) => { + setAlertParams('groupBy', groups); + }, + [setAlertParams] + ); - + const defaultCountAlertParams = useMemo( + () => createDefaultCountAlertParams(supportedFields), + [supportedFields] + ); - + const updateType = useCallback( + (type: ThresholdType) => { + const defaults = + type === 'count' + ? defaultCountAlertParams + : createDefaultRatioAlertParams(supportedFields); + // Reset properties that don't make sense switching from one context to the other + setAlertParams('count', defaults.count); + setAlertParams('criteria', defaults.criteria); + }, + [defaultCountAlertParams, setAlertParams, supportedFields] + ); - { + const newAlertParams = { ...defaultCountAlertParams, ...alertParams }; + for (const [key, value] of Object.entries(newAlertParams) as ObjectEntries< + typeof newAlertParams + >) { + setAlertParams(key, value); + } + setHasSetDefaults(true); + }); + + const shouldShowGroupByOptimizationWarning = useMemo(() => { + const hasSetGroupBy = alertParams.groupBy && alertParams.groupBy.length > 0; + return ( + hasSetGroupBy && + alertParams.count && + !isOptimizableGroupedThreshold(alertParams.count.comparator, alertParams.count.value) + ); + }, [alertParams]); + + // Wait until the alert param defaults have been set + if (!hasSetDefaults) return null; + + const criteriaComponent = alertParams.criteria ? ( + + ) : null; - {alertParams.criteria && isRatioAlert(alertParams.criteria) && criteriaComponent} - - {shouldShowGroupByOptimizationWarning && ( - <> - - - {i18n.translate('xpack.infra.logs.alertFlyout.groupByOptimizationWarning', { - defaultMessage: - 'When setting a "group by" we highly recommend using the "{comparator}" comparator for your threshold. This can lead to significant performance improvements.', - values: { - comparator: Comparator.GT, - }, - })} - - - )} - - - - ); -}; + return ( + <> + + + {alertParams.criteria && !isRatioAlert(alertParams.criteria) && criteriaComponent} + + + + + + + + {alertParams.criteria && isRatioAlert(alertParams.criteria) && criteriaComponent} + + {shouldShowGroupByOptimizationWarning && ( + <> + + + {i18n.translate('xpack.infra.logs.alertFlyout.groupByOptimizationWarning', { + defaultMessage: + 'When setting a "group by" we highly recommend using the "{comparator}" comparator for your threshold. This can lead to significant performance improvements.', + values: { + comparator: Comparator.GT, + }, + })} + + + )} + + + + ); + }; // required for dynamic import // eslint-disable-next-line import/no-default-export diff --git a/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/hooks/use_chart_preview_data.tsx b/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/hooks/use_chart_preview_data.tsx index f97ad64adedd..42f826d09aca 100644 --- a/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/hooks/use_chart_preview_data.tsx +++ b/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/hooks/use_chart_preview_data.tsx @@ -49,9 +49,10 @@ export const useChartPreviewData = ({ sourceId, alertParams, buckets }: Options) [sourceId, http, alertParams, buckets] ); - const isLoading = useMemo(() => getChartPreviewDataRequest.state === 'pending', [ - getChartPreviewDataRequest.state, - ]); + const isLoading = useMemo( + () => getChartPreviewDataRequest.state === 'pending', + [getChartPreviewDataRequest.state] + ); return { chartPreviewData, diff --git a/x-pack/plugins/infra/public/alerting/metric_anomaly/components/expression.tsx b/x-pack/plugins/infra/public/alerting/metric_anomaly/components/expression.tsx index 9f5c47554ac5..5c821c89ad31 100644 --- a/x-pack/plugins/infra/public/alerting/metric_anomaly/components/expression.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_anomaly/components/expression.tsx @@ -66,9 +66,10 @@ export const Expression: React.FC = (props) => { toastWarning: notifications.toasts.addWarning, }); - const derivedIndexPattern = useMemo(() => createDerivedIndexPattern(), [ - createDerivedIndexPattern, - ]); + const derivedIndexPattern = useMemo( + () => createDerivedIndexPattern(), + [createDerivedIndexPattern] + ); const [influencerFieldName, updateInfluencerFieldName] = useState( alertParams.influencerFilter?.fieldName ?? 'host.name' diff --git a/x-pack/plugins/infra/public/alerting/metric_anomaly/components/influencer_filter.tsx b/x-pack/plugins/infra/public/alerting/metric_anomaly/components/influencer_filter.tsx index 34a917a77dcf..fa149ab12fd6 100644 --- a/x-pack/plugins/infra/public/alerting/metric_anomaly/components/influencer_filter.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_anomaly/components/influencer_filter.tsx @@ -35,9 +35,10 @@ export const InfluencerFilter = ({ onChangeFieldValue, derivedIndexPattern, }: Props) => { - const fieldNameOptions = useMemo(() => (nodeType === 'k8s' ? k8sFieldNames : hostFieldNames), [ - nodeType, - ]); + const fieldNameOptions = useMemo( + () => (nodeType === 'k8s' ? k8sFieldNames : hostFieldNames), + [nodeType] + ); // If initial props contain a fieldValue, assume it was passed in from loaded alertParams, // and enable the UI element @@ -52,9 +53,10 @@ export const InfluencerFilter = ({ [nodeType, onChangeFieldName] ); - const onSelectFieldName = useCallback((e) => onChangeFieldName(e.target.value), [ - onChangeFieldName, - ]); + const onSelectFieldName = useCallback( + (e) => onChangeFieldName(e.target.value), + [onChangeFieldName] + ); const onUpdateFieldValue = useCallback( (value) => { updateStoredFieldValue(value); @@ -79,32 +81,29 @@ export const InfluencerFilter = ({ [onUpdateFieldValue] ); - const affixFieldNameToQuery: CurryLoadSuggestionsType = (fn) => ( - expression, - cursorPosition, - maxSuggestions - ) => { - // Add the field name to the front of the passed-in query - const prefix = `${fieldName}:`; - // Trim whitespace to prevent AND/OR suggestions - const modifiedExpression = `${prefix}${expression}`.trim(); - // Move the cursor position forward by the length of the field name - const modifiedPosition = cursorPosition + prefix.length; - return fn(modifiedExpression, modifiedPosition, maxSuggestions, (suggestions) => - suggestions - .map((s) => ({ - ...s, - // Remove quotes from suggestions - text: s.text.replace(/\"/g, '').trim(), - // Offset the returned suggestions' cursor positions so that they can be autocompleted accurately - start: s.start - prefix.length, - end: s.end - prefix.length, - })) - // Removing quotes can lead to an already-selected suggestion still coming up in the autocomplete list, - // so filter these out - .filter((s) => !expression.startsWith(s.text)) - ); - }; + const affixFieldNameToQuery: CurryLoadSuggestionsType = + (fn) => (expression, cursorPosition, maxSuggestions) => { + // Add the field name to the front of the passed-in query + const prefix = `${fieldName}:`; + // Trim whitespace to prevent AND/OR suggestions + const modifiedExpression = `${prefix}${expression}`.trim(); + // Move the cursor position forward by the length of the field name + const modifiedPosition = cursorPosition + prefix.length; + return fn(modifiedExpression, modifiedPosition, maxSuggestions, (suggestions) => + suggestions + .map((s) => ({ + ...s, + // Remove quotes from suggestions + text: s.text.replace(/\"/g, '').trim(), + // Offset the returned suggestions' cursor positions so that they can be autocompleted accurately + start: s.start - prefix.length, + end: s.end - prefix.length, + })) + // Removing quotes can lead to an already-selected suggestion still coming up in the autocomplete list, + // so filter these out + .filter((s) => !expression.startsWith(s.text)) + ); + }; return ( = (props) => { const [timeSize, setTimeSize] = useState(1); const [timeUnit, setTimeUnit] = useState('m'); - const derivedIndexPattern = useMemo(() => createDerivedIndexPattern(), [ - createDerivedIndexPattern, - ]); + const derivedIndexPattern = useMemo( + () => createDerivedIndexPattern(), + [createDerivedIndexPattern] + ); const options = useMemo(() => { if (metadata?.currentOptions?.metrics) { 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 f6618603388d..4dd191313261 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 @@ -74,16 +74,8 @@ const StyledHealth = euiStyled(EuiHealth)` export const ExpressionRow: React.FC = (props) => { const [isExpanded, setRowState] = useState(true); const toggleRowState = useCallback(() => setRowState(!isExpanded), [isExpanded]); - const { - children, - setAlertParams, - expression, - errors, - expressionId, - remove, - fields, - canDelete, - } = props; + const { children, setAlertParams, expression, errors, expressionId, remove, fields, canDelete } = + props; const { aggType = AGGREGATION_TYPES.MAX, metric, 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 fbb883b22808..0e3e2018c963 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 @@ -265,18 +265,17 @@ const withNextSuggestionSelected = ( : 0, }); -const withSuggestionAtIndexSelected = (suggestionIndex: number) => ( - state: AutocompleteFieldState, - props: AutocompleteFieldProps -): AutocompleteFieldState => ({ - ...state, - selectedIndex: - props.suggestions.length === 0 - ? null - : suggestionIndex >= 0 && suggestionIndex < props.suggestions.length - ? suggestionIndex - : 0, -}); +const withSuggestionAtIndexSelected = + (suggestionIndex: number) => + (state: AutocompleteFieldState, props: AutocompleteFieldProps): AutocompleteFieldState => ({ + ...state, + selectedIndex: + props.suggestions.length === 0 + ? null + : suggestionIndex >= 0 && suggestionIndex < props.suggestions.length + ? suggestionIndex + : 0, + }); const withSuggestionsVisible = (state: AutocompleteFieldState) => ({ ...state, diff --git a/x-pack/plugins/infra/public/components/basic_table/row_expansion_button.tsx b/x-pack/plugins/infra/public/components/basic_table/row_expansion_button.tsx index 76e7280acd08..7b046e9f2d25 100644 --- a/x-pack/plugins/infra/public/components/basic_table/row_expansion_button.tsx +++ b/x-pack/plugins/infra/public/components/basic_table/row_expansion_button.tsx @@ -20,12 +20,10 @@ export const RowExpansionButton = ({ onCollapse: (item: Item) => void; onExpand: (item: Item) => void; }) => { - const handleClick = useCallback(() => (isExpanded ? onCollapse(item) : onExpand(item)), [ - isExpanded, - item, - onCollapse, - onExpand, - ]); + const handleClick = useCallback( + () => (isExpanded ? onCollapse(item) : onExpand(item)), + [isExpanded, item, onCollapse, onExpand] + ); return ( getFormattedTime(time, dateFormat, fallbackFormat), [ - time, - dateFormat, - fallbackFormat, - ]); + const formattedTime = useMemo( + () => getFormattedTime(time, dateFormat, fallbackFormat), + [time, dateFormat, fallbackFormat] + ); return formattedTime; }; diff --git a/x-pack/plugins/infra/public/components/log_stream/log_stream_embeddable_factory.ts b/x-pack/plugins/infra/public/components/log_stream/log_stream_embeddable_factory.ts index 1c7e8ceb28fb..15500dacf12d 100644 --- a/x-pack/plugins/infra/public/components/log_stream/log_stream_embeddable_factory.ts +++ b/x-pack/plugins/infra/public/components/log_stream/log_stream_embeddable_factory.ts @@ -19,7 +19,8 @@ import { } from './log_stream_embeddable'; export class LogStreamEmbeddableFactoryDefinition - implements EmbeddableFactoryDefinition { + implements EmbeddableFactoryDefinition +{ public readonly type = LOG_STREAM_EMBEDDABLE; constructor(private getStartServices: StartServicesAccessor) {} diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx index 969838284f1a..0ccd208cf24b 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx @@ -23,14 +23,10 @@ export const LogAnalysisModuleList: React.FC<{ onViewModuleSetup: (module: ModuleId) => void; }> = ({ onViewModuleSetup }) => { const { hasLogAnalysisSetupCapabilities } = useLogAnalysisCapabilitiesContext(); - const { - setupStatus: logEntryRateSetupStatus, - jobIds: logEntryRateJobIds, - } = useLogEntryRateModuleContext(); - const { - setupStatus: logEntryCategoriesSetupStatus, - jobIds: logEntryCategoriesJobIds, - } = useLogEntryCategoriesModuleContext(); + const { setupStatus: logEntryRateSetupStatus, jobIds: logEntryRateJobIds } = + useLogEntryRateModuleContext(); + const { setupStatus: logEntryCategoriesSetupStatus, jobIds: logEntryCategoriesJobIds } = + useLogEntryCategoriesModuleContext(); const viewLogEntryRateSetupFlyout = useCallback(() => { onViewModuleSetup('logs_ui_analysis'); diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout.tsx index 4a744eafaf5f..77ebb9084dbe 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout.tsx @@ -26,12 +26,8 @@ const FLYOUT_HEADING_ID = 'logAnalysisSetupFlyoutHeading'; export const LogAnalysisSetupFlyout: React.FC<{ allowedModules?: ModuleId[]; }> = ({ allowedModules = moduleIds }) => { - const { - closeFlyout, - flyoutView, - showModuleList, - showModuleSetup, - } = useLogAnalysisSetupFlyoutStateContext(); + const { closeFlyout, flyoutView, showModuleList, showModuleSetup } = + useLogAnalysisSetupFlyoutStateContext(); if (flyoutView.view === 'hidden') { return null; diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout_state.ts b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout_state.ts index 4f73781a07d7..8167b50ab602 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout_state.ts +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout_state.ts @@ -42,7 +42,5 @@ export const useLogAnalysisSetupFlyoutState = ({ }; }; -export const [ - LogAnalysisSetupFlyoutStateProvider, - useLogAnalysisSetupFlyoutStateContext, -] = createContainer(useLogAnalysisSetupFlyoutState); +export const [LogAnalysisSetupFlyoutStateProvider, useLogAnalysisSetupFlyoutStateContext] = + createContainer(useLogAnalysisSetupFlyoutState); 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 5ba2ddf73605..c871011d0f01 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 @@ -80,10 +80,10 @@ export const LogEntryRow = memo( const setItemIsHovered = useCallback(() => setIsHovered(true), []); const setItemIsNotHovered = useCallback(() => setIsHovered(false), []); - const openFlyout = useCallback(() => openFlyoutWithItem?.(logEntry.id), [ - openFlyoutWithItem, - logEntry.id, - ]); + const openFlyout = useCallback( + () => openFlyoutWithItem?.(logEntry.id), + [openFlyoutWithItem, logEntry.id] + ); const handleOpenViewLogInContext = useCallback(() => { openViewLogInContext?.(logEntry); 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 56c6698935b3..d1330bdb44b3 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 @@ -77,11 +77,12 @@ export const useMeasuredCharacterDimensions = (scale: TextScale) => { }, []); const CharacterDimensionsProbe = useMemo( - () => () => ( - - X - - ), + () => () => + ( + + X + + ), [measureElement, 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 123455ecab2c..7e13f8b4131f 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 @@ -300,5 +300,6 @@ const getVisibleChildren = ( }; }; -const getChildIndexBefore = bisector<[any, Rect], number>(([key, rect]) => rect.top + rect.height) - .left; +const getChildIndexBefore = bisector<[any, Rect], number>( + ([key, rect]) => rect.top + rect.height +).left; 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 26a2e19671da..db519b4c795e 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 @@ -17,9 +17,8 @@ import { useKibanaContextForPlugin } from '../../../hooks/use_kibana'; export const useLogAnalysisCapabilities = () => { const { services } = useKibanaContextForPlugin(); - const [mlCapabilities, setMlCapabilities] = useState( - initialMlCapabilities - ); + const [mlCapabilities, setMlCapabilities] = + useState(initialMlCapabilities); const [fetchMlCapabilitiesRequest, fetchMlCapabilities] = useTrackedPromise( { @@ -40,9 +39,10 @@ export const useLogAnalysisCapabilities = () => { fetchMlCapabilities(); }, [fetchMlCapabilities]); - const isLoading = useMemo(() => fetchMlCapabilitiesRequest.state === 'pending', [ - fetchMlCapabilitiesRequest.state, - ]); + const isLoading = useMemo( + () => fetchMlCapabilitiesRequest.state === 'pending', + [fetchMlCapabilitiesRequest.state] + ); const hasLogAnalysisSetupCapabilities = mlCapabilities.capabilities.canCreateJob; const hasLogAnalysisReadCapabilities = mlCapabilities.capabilities.canGetJobs; 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 a9ea7e6d6e39..d844b7439710 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 @@ -127,9 +127,10 @@ export const useLogAnalysisModule = ({ [spaceId, sourceId] ); - const isCleaningUp = useMemo(() => cleanUpModuleRequest.state === 'pending', [ - cleanUpModuleRequest.state, - ]); + const isCleaningUp = useMemo( + () => cleanUpModuleRequest.state === 'pending', + [cleanUpModuleRequest.state] + ); const cleanUpAndSetUpModule = useCallback( ( @@ -154,11 +155,10 @@ export const useLogAnalysisModule = ({ dispatchModuleStatus({ type: 'viewedResults' }); }, [dispatchModuleStatus]); - const jobIds = useMemo(() => moduleDescriptor.getJobIds(spaceId, sourceId), [ - moduleDescriptor, - spaceId, - sourceId, - ]); + const jobIds = useMemo( + () => moduleDescriptor.getJobIds(spaceId, sourceId), + [moduleDescriptor, spaceId, sourceId] + ); return { cleanUpAndSetUpModule, 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 ae58fb91b888..057580679210 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 @@ -27,33 +27,35 @@ export const useLogAnalysisModuleConfiguration = ({ }; }; -export const isJobConfigurationOutdated = ( - { bucketSpan }: ModuleDescriptor, - currentSourceConfiguration: ModuleSourceConfiguration -) => (jobSummary: JobSummary): boolean => { - if ( - !jobSummary.fullJob || - !jobSummary.fullJob.custom_settings || - !jobSummary.fullJob.datafeed_config - ) { - return false; - } +export const isJobConfigurationOutdated = + ( + { bucketSpan }: ModuleDescriptor, + currentSourceConfiguration: ModuleSourceConfiguration + ) => + (jobSummary: JobSummary): boolean => { + if ( + !jobSummary.fullJob || + !jobSummary.fullJob.custom_settings || + !jobSummary.fullJob.datafeed_config + ) { + return false; + } - const jobConfiguration = jobSummary.fullJob.custom_settings.logs_source_config; - const datafeedRuntimeMappings = jobSummary.fullJob.datafeed_config.runtime_mappings ?? {}; + const jobConfiguration = jobSummary.fullJob.custom_settings.logs_source_config; + const datafeedRuntimeMappings = jobSummary.fullJob.datafeed_config.runtime_mappings ?? {}; - return !( - jobConfiguration && - jobConfiguration.bucketSpan === bucketSpan && - jobConfiguration.indexPattern && - isSubset( - new Set(jobConfiguration.indexPattern.split(',')), - new Set(currentSourceConfiguration.indices) - ) && - jobConfiguration.timestampField === currentSourceConfiguration.timestampField && - equal(datafeedRuntimeMappings, currentSourceConfiguration.runtimeMappings) - ); -}; + return !( + jobConfiguration && + jobConfiguration.bucketSpan === bucketSpan && + jobConfiguration.indexPattern && + isSubset( + new Set(jobConfiguration.indexPattern.split(',')), + new Set(currentSourceConfiguration.indices) + ) && + jobConfiguration.timestampField === currentSourceConfiguration.timestampField && + equal(datafeedRuntimeMappings, currentSourceConfiguration.runtimeMappings) + ); + }; const isSubset = (subset: Set, superset: Set) => { return Array.from(subset).every((subsetElement) => superset.has(subsetElement)); 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 c3117c9326d1..03522fd9ce6e 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 @@ -63,151 +63,152 @@ const createInitialState = ({ setupStatus: { type: 'initializing' }, }); -const createStatusReducer = (jobTypes: JobType[]) => ( - state: StatusReducerState, - action: StatusReducerAction -): StatusReducerState => { - switch (action.type) { - case 'startedSetup': { - return { - ...state, - jobStatus: jobTypes.reduce( - (accumulatedJobStatus, jobType) => ({ - ...accumulatedJobStatus, - [jobType]: 'initializing', - }), - {} as Record - ), - setupStatus: { type: 'pending' }, - }; - } - case 'finishedSetup': { - const { datafeedSetupResults, jobSetupResults, jobSummaries, spaceId, sourceId } = action; - const nextJobStatus = jobTypes.reduce( - (accumulatedJobStatus, jobType) => ({ - ...accumulatedJobStatus, - [jobType]: - hasSuccessfullyCreatedJob(getJobId(spaceId, sourceId, jobType))(jobSetupResults) && - hasSuccessfullyStartedDatafeed(getDatafeedId(spaceId, sourceId, jobType))( - datafeedSetupResults - ) - ? 'started' - : 'failed', - }), - {} as Record - ); - const nextSetupStatus: SetupStatus = Object.values(nextJobStatus).every( - (jobState) => jobState === 'started' - ) - ? { type: 'succeeded' } - : { - type: 'failed', - reasons: [ - ...Object.values(datafeedSetupResults) - .filter(hasError) - .map((datafeed) => datafeed.error.error?.reason), - ...Object.values(jobSetupResults) - .filter(hasError) - .map((job) => job.error.error?.reason), - ], - }; - - return { - ...state, - jobStatus: nextJobStatus, - jobSummaries, - setupStatus: nextSetupStatus, - }; - } - case 'failedSetup': { - return { - ...state, - jobStatus: jobTypes.reduce( +const createStatusReducer = + (jobTypes: JobType[]) => + ( + state: StatusReducerState, + action: StatusReducerAction + ): StatusReducerState => { + switch (action.type) { + case 'startedSetup': { + return { + ...state, + jobStatus: jobTypes.reduce( + (accumulatedJobStatus, jobType) => ({ + ...accumulatedJobStatus, + [jobType]: 'initializing', + }), + {} as Record + ), + setupStatus: { type: 'pending' }, + }; + } + case 'finishedSetup': { + const { datafeedSetupResults, jobSetupResults, jobSummaries, spaceId, sourceId } = action; + const nextJobStatus = jobTypes.reduce( (accumulatedJobStatus, jobType) => ({ ...accumulatedJobStatus, - [jobType]: 'failed', + [jobType]: + hasSuccessfullyCreatedJob(getJobId(spaceId, sourceId, jobType))(jobSetupResults) && + hasSuccessfullyStartedDatafeed(getDatafeedId(spaceId, sourceId, jobType))( + datafeedSetupResults + ) + ? 'started' + : 'failed', }), {} as Record - ), - setupStatus: { type: 'failed', reasons: ['unknown'] }, - }; - } - case 'fetchingJobStatuses': { - return { - ...state, - setupStatus: - state.setupStatus.type === 'unknown' ? { type: 'initializing' } : state.setupStatus, - }; - } - case 'fetchedJobStatuses': { - const { payload: jobSummaries, spaceId, sourceId } = action; - const { setupStatus } = state; + ); + const nextSetupStatus: SetupStatus = Object.values(nextJobStatus).every( + (jobState) => jobState === 'started' + ) + ? { type: 'succeeded' } + : { + type: 'failed', + reasons: [ + ...Object.values(datafeedSetupResults) + .filter(hasError) + .map((datafeed) => datafeed.error.error?.reason), + ...Object.values(jobSetupResults) + .filter(hasError) + .map((job) => job.error.error?.reason), + ], + }; - const nextJobStatus = jobTypes.reduce( - (accumulatedJobStatus, jobType) => ({ - ...accumulatedJobStatus, - [jobType]: getJobStatus(getJobId(spaceId, sourceId, jobType))(jobSummaries), - }), - {} as Record - ); - const nextSetupStatus = getSetupStatus(nextJobStatus)(setupStatus); + return { + ...state, + jobStatus: nextJobStatus, + jobSummaries, + setupStatus: nextSetupStatus, + }; + } + case 'failedSetup': { + return { + ...state, + jobStatus: jobTypes.reduce( + (accumulatedJobStatus, jobType) => ({ + ...accumulatedJobStatus, + [jobType]: 'failed', + }), + {} as Record + ), + setupStatus: { type: 'failed', reasons: ['unknown'] }, + }; + } + case 'fetchingJobStatuses': { + return { + ...state, + setupStatus: + state.setupStatus.type === 'unknown' ? { type: 'initializing' } : state.setupStatus, + }; + } + case 'fetchedJobStatuses': { + const { payload: jobSummaries, spaceId, sourceId } = action; + const { setupStatus } = state; - return { - ...state, - jobSummaries, - jobStatus: nextJobStatus, - setupStatus: nextSetupStatus, - }; - } - case 'failedFetchingJobStatuses': { - return { - ...state, - setupStatus: { type: 'unknown' }, - jobStatus: jobTypes.reduce( + const nextJobStatus = jobTypes.reduce( (accumulatedJobStatus, jobType) => ({ ...accumulatedJobStatus, - [jobType]: 'unknown', + [jobType]: getJobStatus(getJobId(spaceId, sourceId, jobType))(jobSummaries), }), {} as Record - ), - }; - } - case 'viewedResults': { - return { - ...state, - setupStatus: { type: 'skipped', newlyCreated: true }, - }; - } - default: { - return state; + ); + const nextSetupStatus = getSetupStatus(nextJobStatus)(setupStatus); + + return { + ...state, + jobSummaries, + jobStatus: nextJobStatus, + setupStatus: nextSetupStatus, + }; + } + case 'failedFetchingJobStatuses': { + return { + ...state, + setupStatus: { type: 'unknown' }, + jobStatus: jobTypes.reduce( + (accumulatedJobStatus, jobType) => ({ + ...accumulatedJobStatus, + [jobType]: 'unknown', + }), + {} as Record + ), + }; + } + case 'viewedResults': { + return { + ...state, + setupStatus: { type: 'skipped', newlyCreated: true }, + }; + } + default: { + return state; + } } - } -}; + }; -const hasSuccessfullyCreatedJob = (jobId: string) => ( - jobSetupResponses: SetupMlModuleResponsePayload['jobs'] -) => - jobSetupResponses.filter( - (jobSetupResponse) => - jobSetupResponse.id === jobId && jobSetupResponse.success && !jobSetupResponse.error - ).length > 0; +const hasSuccessfullyCreatedJob = + (jobId: string) => (jobSetupResponses: SetupMlModuleResponsePayload['jobs']) => + jobSetupResponses.filter( + (jobSetupResponse) => + jobSetupResponse.id === jobId && jobSetupResponse.success && !jobSetupResponse.error + ).length > 0; -const hasSuccessfullyStartedDatafeed = (datafeedId: string) => ( - datafeedSetupResponses: SetupMlModuleResponsePayload['datafeeds'] -) => - datafeedSetupResponses.filter( - (datafeedSetupResponse) => - datafeedSetupResponse.id === datafeedId && - datafeedSetupResponse.success && - datafeedSetupResponse.started && - !datafeedSetupResponse.error - ).length > 0; +const hasSuccessfullyStartedDatafeed = + (datafeedId: string) => (datafeedSetupResponses: SetupMlModuleResponsePayload['datafeeds']) => + datafeedSetupResponses.filter( + (datafeedSetupResponse) => + datafeedSetupResponse.id === datafeedId && + datafeedSetupResponse.success && + datafeedSetupResponse.started && + !datafeedSetupResponse.error + ).length > 0; -const getJobStatus = (jobId: string) => (jobSummaries: FetchJobStatusResponsePayload): JobStatus => - jobSummaries - .filter((jobSummary) => jobSummary.id === jobId) - .map( - (jobSummary): JobStatus => { +const getJobStatus = + (jobId: string) => + (jobSummaries: FetchJobStatusResponsePayload): JobStatus => + jobSummaries + .filter((jobSummary) => jobSummary.id === jobId) + .map((jobSummary): JobStatus => { if (jobSummary.jobState === 'failed' || jobSummary.datafeedState === '') { return 'failed'; } else if ( @@ -230,27 +231,26 @@ const getJobStatus = (jobId: string) => (jobSummaries: FetchJobStatusResponsePay } return 'unknown'; + })[0] || 'missing'; + +const getSetupStatus = + (everyJobStatus: Record) => + (previousSetupStatus: SetupStatus): SetupStatus => + Object.entries(everyJobStatus).reduce((setupStatus, [, jobStatus]) => { + if (jobStatus === 'missing') { + return { type: 'required' }; + } else if (setupStatus.type === 'required' || setupStatus.type === 'succeeded') { + return setupStatus; + } else if (setupStatus.type === 'skipped' || isJobStatusWithResults(jobStatus)) { + return { + type: 'skipped', + // preserve newlyCreated status + newlyCreated: setupStatus.type === 'skipped' && setupStatus.newlyCreated, + }; } - )[0] || 'missing'; -const getSetupStatus = (everyJobStatus: Record) => ( - previousSetupStatus: SetupStatus -): SetupStatus => - Object.entries(everyJobStatus).reduce((setupStatus, [, jobStatus]) => { - if (jobStatus === 'missing') { - return { type: 'required' }; - } else if (setupStatus.type === 'required' || setupStatus.type === 'succeeded') { return setupStatus; - } else if (setupStatus.type === 'skipped' || isJobStatusWithResults(jobStatus)) { - return { - type: 'skipped', - // preserve newlyCreated status - newlyCreated: setupStatus.type === 'skipped' && setupStatus.newlyCreated, - }; - } - - return setupStatus; - }, previousSetupStatus); + }, previousSetupStatus); const hasError = ( value: Value diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx index 86e8e75dc3d4..99d4ab4becee 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx @@ -86,7 +86,5 @@ export const useLogEntryCategoriesModule = ({ }; }; -export const [ - LogEntryCategoriesModuleProvider, - useLogEntryCategoriesModuleContext, -] = createContainer(useLogEntryCategoriesModule); +export const [LogEntryCategoriesModuleProvider, useLogEntryCategoriesModuleContext] = + createContainer(useLogEntryCategoriesModule); diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx index 0df5d9b446db..f3e8f7e77759 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx @@ -80,6 +80,5 @@ export const useLogEntryRateModule = ({ }; }; -export const [LogEntryRateModuleProvider, useLogEntryRateModuleContext] = createContainer( - useLogEntryRateModule -); +export const [LogEntryRateModuleProvider, useLogEntryRateModuleContext] = + createContainer(useLogEntryRateModule); diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_setup.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_setup.tsx index cc1ef39de32c..603747c2d2c2 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_setup.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_setup.tsx @@ -56,6 +56,5 @@ export const useLogEntryRateSetup = () => { }; }; -export const [LogEntryRateSetupProvider, useLogEntryRateSetupContext] = createContainer( - useLogEntryRateSetup -); +export const [LogEntryRateSetupProvider, useLogEntryRateSetupContext] = + createContainer(useLogEntryRateSetup); diff --git a/x-pack/plugins/infra/public/containers/logs/log_highlights/log_highlights.tsx b/x-pack/plugins/infra/public/containers/logs/log_highlights/log_highlights.tsx index f7f6f156f78e..dab4abff3bed 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_highlights/log_highlights.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_highlights/log_highlights.tsx @@ -39,20 +39,17 @@ export const useLogHighlightsState = ({ const throttledStartTimestamp = useThrottle(startTimestamp, FETCH_THROTTLE_INTERVAL); const throttledEndTimestamp = useThrottle(endTimestamp, FETCH_THROTTLE_INTERVAL); - const { - logEntryHighlights, - logEntryHighlightsById, - loadLogEntryHighlightsRequest, - } = useLogEntryHighlights( - sourceId, - sourceVersion, - throttledStartTimestamp, - throttledEndTimestamp, - centerCursor, - size, - filterQuery, - highlightTerms - ); + const { logEntryHighlights, logEntryHighlightsById, loadLogEntryHighlightsRequest } = + useLogEntryHighlights( + sourceId, + sourceVersion, + throttledStartTimestamp, + throttledEndTimestamp, + centerCursor, + size, + filterQuery, + highlightTerms + ); const { logSummaryHighlights, loadLogSummaryHighlightsRequest } = useLogSummaryHighlights( sourceId, 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 7a36fe6aae28..59abb716f6cb 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 @@ -56,9 +56,10 @@ export const useLogSummaryHighlights = ( [sourceId, startTimestamp, endTimestamp, bucketSize, filterQuery, highlightTerms] ); - const debouncedLoadSummaryHighlights = useMemo(() => debounce(loadLogSummaryHighlights, 275), [ - loadLogSummaryHighlights, - ]); + const debouncedLoadSummaryHighlights = useMemo( + () => debounce(loadLogSummaryHighlights, 275), + [loadLogSummaryHighlights] + ); useEffect(() => { setLogSummaryHighlights([]); diff --git a/x-pack/plugins/infra/public/containers/logs/log_source/log_source.mock.ts b/x-pack/plugins/infra/public/containers/logs/log_source/log_source.mock.ts index bda1085d4461..6021c728d32a 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_source/log_source.mock.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_source/log_source.mock.ts @@ -11,56 +11,56 @@ type CreateUseLogSource = (sourceConfiguration?: { sourceId?: string }) => typeo const defaultSourceId = 'default'; -export const createUninitializedUseLogSourceMock: CreateUseLogSource = ({ - sourceId = defaultSourceId, -} = {}) => () => ({ - derivedIndexPattern: { - fields: [], - title: 'unknown', - }, - hasFailedLoading: false, - hasFailedLoadingSource: false, - hasFailedLoadingSourceStatus: false, - hasFailedResolvingSource: false, - initialize: jest.fn(), - isLoading: false, - isLoadingSourceConfiguration: false, - isLoadingSourceStatus: false, - isResolvingSourceConfiguration: false, - isUninitialized: true, - loadSource: jest.fn(), - loadSourceConfiguration: jest.fn(), - latestLoadSourceFailures: [], - resolveSourceFailureMessage: undefined, - loadSourceStatus: jest.fn(), - sourceConfiguration: undefined, - sourceId, - sourceStatus: undefined, - updateSource: jest.fn(), - resolvedSourceConfiguration: undefined, - loadResolveLogSourceConfiguration: jest.fn(), -}); +export const createUninitializedUseLogSourceMock: CreateUseLogSource = + ({ sourceId = defaultSourceId } = {}) => + () => ({ + derivedIndexPattern: { + fields: [], + title: 'unknown', + }, + hasFailedLoading: false, + hasFailedLoadingSource: false, + hasFailedLoadingSourceStatus: false, + hasFailedResolvingSource: false, + initialize: jest.fn(), + isLoading: false, + isLoadingSourceConfiguration: false, + isLoadingSourceStatus: false, + isResolvingSourceConfiguration: false, + isUninitialized: true, + loadSource: jest.fn(), + loadSourceConfiguration: jest.fn(), + latestLoadSourceFailures: [], + resolveSourceFailureMessage: undefined, + loadSourceStatus: jest.fn(), + sourceConfiguration: undefined, + sourceId, + sourceStatus: undefined, + updateSource: jest.fn(), + resolvedSourceConfiguration: undefined, + loadResolveLogSourceConfiguration: jest.fn(), + }); -export const createLoadingUseLogSourceMock: CreateUseLogSource = ({ - sourceId = defaultSourceId, -} = {}) => (args) => ({ - ...createUninitializedUseLogSourceMock({ sourceId })(args), - isLoading: true, - isLoadingSourceConfiguration: true, - isLoadingSourceStatus: true, - isResolvingSourceConfiguration: true, -}); +export const createLoadingUseLogSourceMock: CreateUseLogSource = + ({ sourceId = defaultSourceId } = {}) => + (args) => ({ + ...createUninitializedUseLogSourceMock({ sourceId })(args), + isLoading: true, + isLoadingSourceConfiguration: true, + isLoadingSourceStatus: true, + isResolvingSourceConfiguration: true, + }); -export const createLoadedUseLogSourceMock: CreateUseLogSource = ({ - sourceId = defaultSourceId, -} = {}) => (args) => ({ - ...createUninitializedUseLogSourceMock({ sourceId })(args), - sourceConfiguration: createBasicSourceConfiguration(sourceId), - sourceStatus: { - logIndexFields: [], - logIndexStatus: 'available', - }, -}); +export const createLoadedUseLogSourceMock: CreateUseLogSource = + ({ sourceId = defaultSourceId } = {}) => + (args) => ({ + ...createUninitializedUseLogSourceMock({ sourceId })(args), + sourceConfiguration: createBasicSourceConfiguration(sourceId), + sourceStatus: { + logIndexFields: [], + logIndexStatus: 'available', + }, + }); export const createBasicSourceConfiguration = (sourceId: string): LogSourceConfiguration => ({ id: sourceId, diff --git a/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_after.ts b/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_after.ts index e41bc07dfd36..ea2162cb96e3 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_after.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_after.ts @@ -88,13 +88,8 @@ export const useLogEntriesAfterResponse = flattenLogEntriesAfterSearchResponse ); - const { - cancelRequest, - isRequestRunning, - isResponsePartial, - loaded, - total, - } = useDataSearchResponseState(logEntriesAfterSearchResponse$); + const { cancelRequest, isRequestRunning, isResponsePartial, loaded, total } = + useDataSearchResponseState(logEntriesAfterSearchResponse$); return { cancelRequest, diff --git a/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_before.ts b/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_before.ts index c9a7dab16820..7d99b3069d97 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_before.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_before.ts @@ -44,34 +44,32 @@ export const useLogEntriesBeforeRequest = ({ sourceId: string; startTimestamp: number; }) => { - const { - search: fetchLogEntriesBefore, - requests$: logEntriesBeforeSearchRequests$, - } = useDataSearch({ - getRequest: useCallback( - (cursor: LogEntryBeforeCursor['before'], params: { size: number; extendTo?: number }) => { - return !!sourceId - ? { - request: { - params: logEntriesSearchRequestParamsRT.encode({ - before: cursor, - columns: columnOverrides, - endTimestamp, - highlightPhrase, - query: query as JsonObject, - size: params.size, - sourceId, - startTimestamp: params.extendTo ?? startTimestamp, - }), - }, - options: { strategy: LOG_ENTRIES_SEARCH_STRATEGY }, - } - : null; - }, - [columnOverrides, endTimestamp, highlightPhrase, query, sourceId, startTimestamp] - ), - parseResponses: parseLogEntriesBeforeSearchResponses, - }); + const { search: fetchLogEntriesBefore, requests$: logEntriesBeforeSearchRequests$ } = + useDataSearch({ + getRequest: useCallback( + (cursor: LogEntryBeforeCursor['before'], params: { size: number; extendTo?: number }) => { + return !!sourceId + ? { + request: { + params: logEntriesSearchRequestParamsRT.encode({ + before: cursor, + columns: columnOverrides, + endTimestamp, + highlightPhrase, + query: query as JsonObject, + size: params.size, + sourceId, + startTimestamp: params.extendTo ?? startTimestamp, + }), + }, + options: { strategy: LOG_ENTRIES_SEARCH_STRATEGY }, + } + : null; + }, + [columnOverrides, endTimestamp, highlightPhrase, query, sourceId, startTimestamp] + ), + parseResponses: parseLogEntriesBeforeSearchResponses, + }); return { fetchLogEntriesBefore, @@ -89,13 +87,8 @@ export const useLogEntriesBeforeResponse = { ] ); - const isUninitialized = useMemo(() => loadSourceRequest.state === 'uninitialized', [ - loadSourceRequest.state, - ]); + const isUninitialized = useMemo( + () => loadSourceRequest.state === 'uninitialized', + [loadSourceRequest.state] + ); const sourceExists = useMemo(() => (source ? !!source.version : undefined), [source]); diff --git a/x-pack/plugins/infra/public/containers/metrics_source/use_source_via_http.ts b/x-pack/plugins/infra/public/containers/metrics_source/use_source_via_http.ts index 2947f8fb0984..c7da5afd8dcd 100644 --- a/x-pack/plugins/infra/public/containers/metrics_source/use_source_via_http.ts +++ b/x-pack/plugins/infra/public/containers/metrics_source/use_source_via_http.ts @@ -47,19 +47,15 @@ export const useSourceViaHttp = ({ sourceId = 'default', fetch, toastWarning }: ); }; - const { - error, - loading, - response, - makeRequest, - } = useHTTPRequest( - `/api/metrics/source/${sourceId}`, - 'GET', - null, - decodeResponse, - fetch, - toastWarning - ); + const { error, loading, response, makeRequest } = + useHTTPRequest( + `/api/metrics/source/${sourceId}`, + 'GET', + null, + decodeResponse, + fetch, + toastWarning + ); useEffect(() => { (async () => { diff --git a/x-pack/plugins/infra/public/containers/ml/infra_ml_capabilities.tsx b/x-pack/plugins/infra/public/containers/ml/infra_ml_capabilities.tsx index 661ce8f8a253..7b9fe25cc3fa 100644 --- a/x-pack/plugins/infra/public/containers/ml/infra_ml_capabilities.tsx +++ b/x-pack/plugins/infra/public/containers/ml/infra_ml_capabilities.tsx @@ -20,9 +20,8 @@ import { useKibanaContextForPlugin } from '../../hooks/use_kibana'; export const useInfraMLCapabilities = () => { const { services } = useKibanaContextForPlugin(); - const [mlCapabilities, setMlCapabilities] = useState( - initialMlCapabilities - ); + const [mlCapabilities, setMlCapabilities] = + useState(initialMlCapabilities); const [fetchMlCapabilitiesRequest, fetchMlCapabilities] = useTrackedPromise( { @@ -46,9 +45,10 @@ export const useInfraMLCapabilities = () => { fetchMlCapabilities(); }, [fetchMlCapabilities]); - const isLoading = useMemo(() => fetchMlCapabilitiesRequest.state === 'pending', [ - fetchMlCapabilitiesRequest.state, - ]); + const isLoading = useMemo( + () => fetchMlCapabilitiesRequest.state === 'pending', + [fetchMlCapabilitiesRequest.state] + ); const hasInfraMLSetupCapabilities = mlCapabilities.capabilities.canCreateJob; const hasInfraMLReadCapabilities = mlCapabilities.capabilities.canGetJobs; @@ -63,9 +63,8 @@ export const useInfraMLCapabilities = () => { }; }; -export const [InfraMLCapabilitiesProvider, useInfraMLCapabilitiesContext] = createContainer( - useInfraMLCapabilities -); +export const [InfraMLCapabilitiesProvider, useInfraMLCapabilitiesContext] = + createContainer(useInfraMLCapabilities); const initialMlCapabilities = { capabilities: { diff --git a/x-pack/plugins/infra/public/containers/ml/infra_ml_module.tsx b/x-pack/plugins/infra/public/containers/ml/infra_ml_module.tsx index b55ae65e58e9..198a99f39485 100644 --- a/x-pack/plugins/infra/public/containers/ml/infra_ml_module.tsx +++ b/x-pack/plugins/infra/public/containers/ml/infra_ml_module.tsx @@ -104,9 +104,10 @@ export const useInfraMLModule = ({ [spaceId, sourceId] ); - const isCleaningUp = useMemo(() => cleanUpModuleRequest.state === 'pending', [ - cleanUpModuleRequest.state, - ]); + const isCleaningUp = useMemo( + () => cleanUpModuleRequest.state === 'pending', + [cleanUpModuleRequest.state] + ); const cleanUpAndSetUpModule = useCallback( ( @@ -132,11 +133,10 @@ export const useInfraMLModule = ({ dispatchModuleStatus({ type: 'viewedResults' }); }, [dispatchModuleStatus]); - const jobIds = useMemo(() => moduleDescriptor.getJobIds(spaceId, sourceId), [ - moduleDescriptor, - spaceId, - sourceId, - ]); + const jobIds = useMemo( + () => moduleDescriptor.getJobIds(spaceId, sourceId), + [moduleDescriptor, spaceId, sourceId] + ); return { cleanUpAndSetUpModule, diff --git a/x-pack/plugins/infra/public/containers/ml/infra_ml_module_configuration.ts b/x-pack/plugins/infra/public/containers/ml/infra_ml_module_configuration.ts index 3f8ebb835211..4c876c170536 100644 --- a/x-pack/plugins/infra/public/containers/ml/infra_ml_module_configuration.ts +++ b/x-pack/plugins/infra/public/containers/ml/infra_ml_module_configuration.ts @@ -26,27 +26,29 @@ export const useInfraMLModuleConfiguration = ({ }; }; -export const isJobConfigurationOutdated = ( - { bucketSpan }: ModuleDescriptor, - currentSourceConfiguration: ModuleSourceConfiguration -) => (jobSummary: JobSummary): boolean => { - if (!jobSummary.fullJob || !jobSummary.fullJob.custom_settings) { - return false; - } +export const isJobConfigurationOutdated = + ( + { bucketSpan }: ModuleDescriptor, + currentSourceConfiguration: ModuleSourceConfiguration + ) => + (jobSummary: JobSummary): boolean => { + if (!jobSummary.fullJob || !jobSummary.fullJob.custom_settings) { + return false; + } - const jobConfiguration = jobSummary.fullJob.custom_settings.metrics_source_config; + const jobConfiguration = jobSummary.fullJob.custom_settings.metrics_source_config; - return !( - jobConfiguration && - jobConfiguration.bucketSpan === bucketSpan && - jobConfiguration.indexPattern && - isSubset( - new Set(jobConfiguration.indexPattern.split(',')), - new Set(currentSourceConfiguration.indices) - ) && - jobConfiguration.timestampField === currentSourceConfiguration.timestampField - ); -}; + return !( + jobConfiguration && + jobConfiguration.bucketSpan === bucketSpan && + jobConfiguration.indexPattern && + isSubset( + new Set(jobConfiguration.indexPattern.split(',')), + new Set(currentSourceConfiguration.indices) + ) && + jobConfiguration.timestampField === currentSourceConfiguration.timestampField + ); + }; const isSubset = (subset: Set, superset: Set) => { return Array.from(subset).every((subsetElement) => superset.has(subsetElement)); diff --git a/x-pack/plugins/infra/public/containers/ml/infra_ml_module_status.tsx b/x-pack/plugins/infra/public/containers/ml/infra_ml_module_status.tsx index 4ebad85ef0fe..9bbd7720e168 100644 --- a/x-pack/plugins/infra/public/containers/ml/infra_ml_module_status.tsx +++ b/x-pack/plugins/infra/public/containers/ml/infra_ml_module_status.tsx @@ -63,153 +63,152 @@ const createInitialState = ({ setupStatus: { type: 'initializing' }, }); -const createStatusReducer = (jobTypes: JobType[]) => ( - state: StatusReducerState, - action: StatusReducerAction -): StatusReducerState => { - switch (action.type) { - case 'startedSetup': { - return { - ...state, - jobStatus: jobTypes.reduce( +const createStatusReducer = + (jobTypes: JobType[]) => + ( + state: StatusReducerState, + action: StatusReducerAction + ): StatusReducerState => { + switch (action.type) { + case 'startedSetup': { + return { + ...state, + jobStatus: jobTypes.reduce( + (accumulatedJobStatus, jobType) => ({ + ...accumulatedJobStatus, + [jobType]: 'initializing', + }), + {} as Record + ), + setupStatus: { type: 'pending' }, + }; + } + case 'finishedSetup': { + const { datafeedSetupResults, jobSetupResults, jobSummaries, spaceId, sourceId } = action; + const nextJobStatus = jobTypes.reduce( (accumulatedJobStatus, jobType) => ({ ...accumulatedJobStatus, - [jobType]: 'initializing', + [jobType]: + hasSuccessfullyCreatedJob(getJobId(spaceId, sourceId, jobType))(jobSetupResults) && + hasSuccessfullyStartedDatafeed(getDatafeedId(spaceId, sourceId, jobType))( + datafeedSetupResults + ) + ? 'started' + : 'failed', }), {} as Record - ), - setupStatus: { type: 'pending' }, - }; - } - case 'finishedSetup': { - const { datafeedSetupResults, jobSetupResults, jobSummaries, spaceId, sourceId } = action; - const nextJobStatus = jobTypes.reduce( - (accumulatedJobStatus, jobType) => ({ - ...accumulatedJobStatus, - [jobType]: - hasSuccessfullyCreatedJob(getJobId(spaceId, sourceId, jobType))(jobSetupResults) && - hasSuccessfullyStartedDatafeed(getDatafeedId(spaceId, sourceId, jobType))( - datafeedSetupResults - ) - ? 'started' - : 'failed', - }), - {} as Record - ); - const nextSetupStatus: SetupStatus = Object.values(nextJobStatus).every( - (jobState) => jobState === 'started' - ) - ? { type: 'succeeded' } - : { - type: 'failed', - reasons: [ - ...Object.values(datafeedSetupResults) - .filter(hasError) - .map((datafeed) => datafeed.error.msg), - ...Object.values(jobSetupResults) - .filter(hasError) - .map((job) => job.error.msg), - ], - }; + ); + const nextSetupStatus: SetupStatus = Object.values(nextJobStatus).every( + (jobState) => jobState === 'started' + ) + ? { type: 'succeeded' } + : { + type: 'failed', + reasons: [ + ...Object.values(datafeedSetupResults) + .filter(hasError) + .map((datafeed) => datafeed.error.msg), + ...Object.values(jobSetupResults) + .filter(hasError) + .map((job) => job.error.msg), + ], + }; - return { - ...state, - jobStatus: nextJobStatus, - jobSummaries, - setupStatus: nextSetupStatus, - }; - } - case 'failedSetup': { - return { - ...state, - jobStatus: jobTypes.reduce( + return { + ...state, + jobStatus: nextJobStatus, + jobSummaries, + setupStatus: nextSetupStatus, + }; + } + case 'failedSetup': { + return { + ...state, + jobStatus: jobTypes.reduce( + (accumulatedJobStatus, jobType) => ({ + ...accumulatedJobStatus, + [jobType]: 'failed', + }), + {} as Record + ), + setupStatus: { type: 'failed', reasons: ['unknown'] }, + }; + } + case 'fetchingJobStatuses': { + return { + ...state, + setupStatus: + state.setupStatus.type === 'unknown' ? { type: 'initializing' } : state.setupStatus, + }; + } + case 'fetchedJobStatuses': { + const { payload: jobSummaries, spaceId, sourceId } = action; + const { setupStatus } = state; + const nextJobStatus = jobTypes.reduce( (accumulatedJobStatus, jobType) => ({ ...accumulatedJobStatus, - [jobType]: 'failed', + [jobType]: getJobStatus(getJobId(spaceId, sourceId, jobType))(jobSummaries), }), {} as Record - ), - setupStatus: { type: 'failed', reasons: ['unknown'] }, - }; - } - case 'fetchingJobStatuses': { - return { - ...state, - setupStatus: - state.setupStatus.type === 'unknown' ? { type: 'initializing' } : state.setupStatus, - }; - } - case 'fetchedJobStatuses': { - const { payload: jobSummaries, spaceId, sourceId } = action; - const { setupStatus } = state; - const nextJobStatus = jobTypes.reduce( - (accumulatedJobStatus, jobType) => ({ - ...accumulatedJobStatus, - [jobType]: getJobStatus(getJobId(spaceId, sourceId, jobType))(jobSummaries), - }), - {} as Record - ); - const nextSetupStatus = getSetupStatus(nextJobStatus)(setupStatus); + ); + const nextSetupStatus = getSetupStatus(nextJobStatus)(setupStatus); - return { - ...state, - jobSummaries, - jobStatus: nextJobStatus, - setupStatus: nextSetupStatus, - }; - } - case 'failedFetchingJobStatuses': { - return { - ...state, - setupStatus: { type: 'unknown' }, - jobStatus: jobTypes.reduce( - (accumulatedJobStatus, jobType) => ({ - ...accumulatedJobStatus, - [jobType]: 'unknown', - }), - {} as Record - ), - }; - } - case 'viewedResults': { - return { - ...state, - setupStatus: { type: 'skipped', newlyCreated: true }, - }; - } - default: { - return state; + return { + ...state, + jobSummaries, + jobStatus: nextJobStatus, + setupStatus: nextSetupStatus, + }; + } + case 'failedFetchingJobStatuses': { + return { + ...state, + setupStatus: { type: 'unknown' }, + jobStatus: jobTypes.reduce( + (accumulatedJobStatus, jobType) => ({ + ...accumulatedJobStatus, + [jobType]: 'unknown', + }), + {} as Record + ), + }; + } + case 'viewedResults': { + return { + ...state, + setupStatus: { type: 'skipped', newlyCreated: true }, + }; + } + default: { + return state; + } } - } -}; + }; -const hasSuccessfullyCreatedJob = (jobId: string) => ( - jobSetupResponses: SetupMlModuleResponsePayload['jobs'] -) => - jobSetupResponses.filter( - (jobSetupResponse) => - jobSetupResponse.id === jobId && jobSetupResponse.success && !jobSetupResponse.error - ).length > 0; +const hasSuccessfullyCreatedJob = + (jobId: string) => (jobSetupResponses: SetupMlModuleResponsePayload['jobs']) => + jobSetupResponses.filter( + (jobSetupResponse) => + jobSetupResponse.id === jobId && jobSetupResponse.success && !jobSetupResponse.error + ).length > 0; -const hasSuccessfullyStartedDatafeed = (datafeedId: string) => ( - datafeedSetupResponses: SetupMlModuleResponsePayload['datafeeds'] -) => - datafeedSetupResponses.filter( - (datafeedSetupResponse) => - datafeedSetupResponse.id === datafeedId && - datafeedSetupResponse.success && - datafeedSetupResponse.started && - !datafeedSetupResponse.error - ).length > 0; +const hasSuccessfullyStartedDatafeed = + (datafeedId: string) => (datafeedSetupResponses: SetupMlModuleResponsePayload['datafeeds']) => + datafeedSetupResponses.filter( + (datafeedSetupResponse) => + datafeedSetupResponse.id === datafeedId && + datafeedSetupResponse.success && + datafeedSetupResponse.started && + !datafeedSetupResponse.error + ).length > 0; -const getJobStatus = (jobId: string) => ( - jobSummaries: FetchJobStatusResponsePayload -): JobStatus => { - return ( - jobSummaries - .filter((jobSummary) => jobSummary.id === jobId) - .map( - (jobSummary): JobStatus => { +const getJobStatus = + (jobId: string) => + (jobSummaries: FetchJobStatusResponsePayload): JobStatus => { + return ( + jobSummaries + .filter((jobSummary) => jobSummary.id === jobId) + .map((jobSummary): JobStatus => { if (jobSummary.jobState === 'failed' || jobSummary.datafeedState === '') { return 'failed'; } else if ( @@ -232,33 +231,32 @@ const getJobStatus = (jobId: string) => ( } return 'unknown'; + })[0] || 'missing' + ); + }; + +const getSetupStatus = + (everyJobStatus: Record) => + (previousSetupStatus: SetupStatus): SetupStatus => { + return Object.entries(everyJobStatus).reduce( + (setupStatus, [, jobStatus]) => { + if (jobStatus === 'missing') { + return { type: 'required' }; + } else if (setupStatus.type === 'required' || setupStatus.type === 'succeeded') { + return setupStatus; + } else if (setupStatus.type === 'skipped' || isJobStatusWithResults(jobStatus)) { + return { + type: 'skipped', + // preserve newlyCreated status + newlyCreated: setupStatus.type === 'skipped' && setupStatus.newlyCreated, + }; } - )[0] || 'missing' - ); -}; -const getSetupStatus = (everyJobStatus: Record) => ( - previousSetupStatus: SetupStatus -): SetupStatus => { - return Object.entries(everyJobStatus).reduce( - (setupStatus, [, jobStatus]) => { - if (jobStatus === 'missing') { - return { type: 'required' }; - } else if (setupStatus.type === 'required' || setupStatus.type === 'succeeded') { return setupStatus; - } else if (setupStatus.type === 'skipped' || isJobStatusWithResults(jobStatus)) { - return { - type: 'skipped', - // preserve newlyCreated status - newlyCreated: setupStatus.type === 'skipped' && setupStatus.newlyCreated, - }; - } - - return setupStatus; - }, - previousSetupStatus - ); -}; + }, + previousSetupStatus + ); + }; const hasError = ( value: Value diff --git a/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module.tsx b/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module.tsx index 2697a4223fc1..f892ab62ee3d 100644 --- a/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module.tsx +++ b/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module.tsx @@ -76,6 +76,5 @@ export const useMetricHostsModule = ({ }; }; -export const [MetricHostsModuleProvider, useMetricHostsModuleContext] = createContainer( - useMetricHostsModule -); +export const [MetricHostsModuleProvider, useMetricHostsModuleContext] = + createContainer(useMetricHostsModule); diff --git a/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module.tsx b/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module.tsx index 98edbca2166b..eadc37443481 100644 --- a/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module.tsx +++ b/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module.tsx @@ -76,6 +76,5 @@ export const useMetricK8sModule = ({ }; }; -export const [MetricK8sModuleProvider, useMetricK8sModuleContext] = createContainer( - useMetricK8sModule -); +export const [MetricK8sModuleProvider, useMetricK8sModuleContext] = + createContainer(useMetricK8sModule); diff --git a/x-pack/plugins/infra/public/containers/saved_view/saved_view.tsx b/x-pack/plugins/infra/public/containers/saved_view/saved_view.tsx index c54a2a69a994..44792019a5f9 100644 --- a/x-pack/plugins/infra/public/containers/saved_view/saved_view.tsx +++ b/x-pack/plugins/infra/public/containers/saved_view/saved_view.tsx @@ -62,9 +62,13 @@ export const useSavedView = (props: Props) => { } = useContext(Source.Context); const { viewType, defaultViewState } = props; type ViewState = typeof defaultViewState; - const { data, loading, find, error: errorOnFind, hasView } = useFindSavedObject< - SavedViewSavedObject - >(viewType); + const { + data, + loading, + find, + error: errorOnFind, + hasView, + } = useFindSavedObject>(viewType); const [urlState, setUrlState] = useUrlState({ defaultState: DEFAULT_SAVED_VIEW_STATE, decodeUrlState, @@ -75,12 +79,18 @@ export const useSavedView = (props: Props) => { const [shouldLoadDefault] = useState(props.shouldLoadDefault); const [currentView, setCurrentView] = useState | null>(null); const [loadingDefaultView, setLoadingDefaultView] = useState(null); - const { create, error: errorOnCreate, data: createdViewData, createdId } = useCreateSavedObject( - viewType - ); - const { update, error: errorOnUpdate, data: updatedViewData, updatedId } = useUpdateSavedObject( - viewType - ); + const { + create, + error: errorOnCreate, + data: createdViewData, + createdId, + } = useCreateSavedObject(viewType); + const { + update, + error: errorOnUpdate, + data: updatedViewData, + updatedId, + } = useUpdateSavedObject(viewType); const { deleteObject, deletedId } = useDeleteSavedObject(viewType); const { getObject, data: currentViewSavedObject } = useGetSavedObject(viewType); const [createError, setCreateError] = useState(null); 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 1a759950f640..f50c629d521e 100644 --- a/x-pack/plugins/infra/public/containers/with_kuery_autocompletion.tsx +++ b/x-pack/plugins/infra/public/containers/with_kuery_autocompletion.tsx @@ -61,9 +61,8 @@ class WithKueryAutocompletionComponent extends React.Component< ) => { const { indexPattern } = this.props; const language = 'kuery'; - const hasQuerySuggestions = this.props.kibana.services.data?.autocomplete.hasQuerySuggestions( - language - ); + const hasQuerySuggestions = + this.props.kibana.services.data?.autocomplete.hasQuerySuggestions(language); if (!hasQuerySuggestions) { return; diff --git a/x-pack/plugins/infra/public/hooks/use_kibana.ts b/x-pack/plugins/infra/public/hooks/use_kibana.ts index 207e08589cde..1d21f352a9ea 100644 --- a/x-pack/plugins/infra/public/hooks/use_kibana.ts +++ b/x-pack/plugins/infra/public/hooks/use_kibana.ts @@ -21,4 +21,5 @@ export const createKibanaContextForPlugin = (core: CoreStart, pluginsStart: Infr ...pluginsStart, }); -export const useKibanaContextForPlugin = useKibana as () => KibanaReactContextValue; +export const useKibanaContextForPlugin = + useKibana as () => KibanaReactContextValue; diff --git a/x-pack/plugins/infra/public/metrics_overview_fetchers.ts b/x-pack/plugins/infra/public/metrics_overview_fetchers.ts index 4f5b73d68559..57017d25ecc6 100644 --- a/x-pack/plugins/infra/public/metrics_overview_fetchers.ts +++ b/x-pack/plugins/infra/public/metrics_overview_fetchers.ts @@ -17,44 +17,43 @@ import { FetchDataParams, MetricsFetchDataResponse } from '../../observability/p import { TopNodesRequest, TopNodesResponse } from '../common/http_api/overview_api'; import { InfraClientCoreSetup } from './types'; -export const createMetricsHasData = ( - getStartServices: InfraClientCoreSetup['getStartServices'] -) => async () => { - const [coreServices] = await getStartServices(); - const { http } = coreServices; - const results = await http.get<{ hasData: boolean }>('/api/metrics/source/default/hasData'); - return results.hasData; -}; +export const createMetricsHasData = + (getStartServices: InfraClientCoreSetup['getStartServices']) => async () => { + const [coreServices] = await getStartServices(); + const { http } = coreServices; + const results = await http.get<{ hasData: boolean }>('/api/metrics/source/default/hasData'); + return results.hasData; + }; -export const createMetricsFetchData = ( - getStartServices: InfraClientCoreSetup['getStartServices'] -) => async ({ absoluteTime, bucketSize }: FetchDataParams): Promise => { - const [coreServices] = await getStartServices(); - const { http } = coreServices; +export const createMetricsFetchData = + (getStartServices: InfraClientCoreSetup['getStartServices']) => + async ({ absoluteTime, bucketSize }: FetchDataParams): Promise => { + const [coreServices] = await getStartServices(); + const { http } = coreServices; - const makeRequest = async (overrides: Partial = {}) => { - const { start, end } = absoluteTime; + const makeRequest = async (overrides: Partial = {}) => { + const { start, end } = absoluteTime; - const overviewRequest: TopNodesRequest = { - sourceId: 'default', - bucketSize, - size: 5, - timerange: { - from: start, - to: end, - }, - ...overrides, - }; - const results = await http.post('/api/metrics/overview/top', { - body: JSON.stringify(overviewRequest), - }); - return { - appLink: `/app/metrics/inventory?waffleTime=(currentTime:${end},isAutoReloading:!f)`, - series: results.series, - sort: async (by: string, direction: string) => - makeRequest({ sort: by, sortDirection: direction }), + const overviewRequest: TopNodesRequest = { + sourceId: 'default', + bucketSize, + size: 5, + timerange: { + from: start, + to: end, + }, + ...overrides, + }; + const results = await http.post('/api/metrics/overview/top', { + body: JSON.stringify(overviewRequest), + }); + return { + appLink: `/app/metrics/inventory?waffleTime=(currentTime:${end},isAutoReloading:!f)`, + series: results.series, + sort: async (by: string, direction: string) => + makeRequest({ sort: by, sortDirection: direction }), + }; }; - }; - return await makeRequest(); -}; + return await makeRequest(); + }; diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_content.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_content.tsx index bfdbe0352616..a8d98ea843c9 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_content.tsx @@ -40,9 +40,10 @@ export const LogEntryCategoriesPageContent = () => { const { fetchJobStatus, setupStatus, jobStatus } = useLogEntryCategoriesModuleContext(); const { showModuleSetup } = useLogAnalysisSetupFlyoutStateContext(); - const showCategoriesModuleSetup = useCallback(() => showModuleSetup('logs_ui_categories'), [ - showModuleSetup, - ]); + const showCategoriesModuleSetup = useCallback( + () => showModuleSetup('logs_ui_categories'), + [showModuleSetup] + ); useEffect(() => { if (hasLogAnalysisReadCapabilities) { 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 7098f457117d..bf6fe978ddae 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 @@ -40,240 +40,241 @@ interface LogEntryCategoriesResultsContentProps { pageTitle: string; } -export const LogEntryCategoriesResultsContent: React.FunctionComponent = ({ - onOpenSetup, - pageTitle, -}) => { - useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_results' }); - useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_results', delay: 15000 }); +export const LogEntryCategoriesResultsContent: React.FunctionComponent = + ({ onOpenSetup, pageTitle }) => { + useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_results' }); + useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_results', delay: 15000 }); - const { - services: { ml, http }, - } = useKibanaContextForPlugin(); + const { + services: { ml, http }, + } = useKibanaContextForPlugin(); - const { hasLogAnalysisSetupCapabilities } = useLogAnalysisCapabilitiesContext(); + const { hasLogAnalysisSetupCapabilities } = useLogAnalysisCapabilitiesContext(); - const { - fetchJobStatus, - fetchModuleDefinition, - moduleDescriptor, - setupStatus, - hasOutdatedJobConfigurations, - hasOutdatedJobDefinitions, - hasStoppedJobs, - jobIds, - categoryQualityWarnings, - sourceConfiguration: { sourceId }, - } = useLogEntryCategoriesModuleContext(); + const { + fetchJobStatus, + fetchModuleDefinition, + moduleDescriptor, + setupStatus, + hasOutdatedJobConfigurations, + hasOutdatedJobDefinitions, + hasStoppedJobs, + jobIds, + categoryQualityWarnings, + sourceConfiguration: { sourceId }, + } = useLogEntryCategoriesModuleContext(); - const { - timeRange: selectedTimeRange, - setTimeRange: setSelectedTimeRange, - autoRefresh, - setAutoRefresh, - } = useLogEntryCategoriesResultsUrlState(); + const { + timeRange: selectedTimeRange, + setTimeRange: setSelectedTimeRange, + autoRefresh, + setAutoRefresh, + } = useLogEntryCategoriesResultsUrlState(); - const [categoryQueryTimeRange, setCategoryQueryTimeRange] = useState<{ - lastChangedTime: number; - timeRange: TimeRange; - }>(() => ({ - lastChangedTime: Date.now(), - timeRange: stringToNumericTimeRange(selectedTimeRange), - })); + const [categoryQueryTimeRange, setCategoryQueryTimeRange] = useState<{ + lastChangedTime: number; + timeRange: TimeRange; + }>(() => ({ + lastChangedTime: Date.now(), + timeRange: stringToNumericTimeRange(selectedTimeRange), + })); - const [categoryQueryDatasets, setCategoryQueryDatasets] = useState([]); + const [categoryQueryDatasets, setCategoryQueryDatasets] = useState([]); - const { services } = useKibana<{}>(); + const { services } = useKibana<{}>(); - const showLoadDataErrorNotification = useCallback( - (error: Error) => { - services.notifications?.toasts.addError(error, { - title: loadDataErrorTitle, - }); - }, - [services.notifications] - ); + const showLoadDataErrorNotification = useCallback( + (error: Error) => { + services.notifications?.toasts.addError(error, { + title: loadDataErrorTitle, + }); + }, + [services.notifications] + ); - const { - getLogEntryCategoryDatasets, - getTopLogEntryCategories, - isLoadingLogEntryCategoryDatasets, - isLoadingTopLogEntryCategories, - logEntryCategoryDatasets, - topLogEntryCategories, - sortOptions, - changeSortOptions, - } = useLogEntryCategoriesResults({ - categoriesCount: 25, - endTime: categoryQueryTimeRange.timeRange.endTime, - filteredDatasets: categoryQueryDatasets, - onGetTopLogEntryCategoriesError: showLoadDataErrorNotification, - sourceId, - startTime: categoryQueryTimeRange.timeRange.startTime, - }); + const { + getLogEntryCategoryDatasets, + getTopLogEntryCategories, + isLoadingLogEntryCategoryDatasets, + isLoadingTopLogEntryCategories, + logEntryCategoryDatasets, + topLogEntryCategories, + sortOptions, + changeSortOptions, + } = useLogEntryCategoriesResults({ + categoriesCount: 25, + endTime: categoryQueryTimeRange.timeRange.endTime, + filteredDatasets: categoryQueryDatasets, + onGetTopLogEntryCategoriesError: showLoadDataErrorNotification, + sourceId, + startTime: categoryQueryTimeRange.timeRange.startTime, + }); - const handleQueryTimeRangeChange = useCallback( - ({ start: startTime, end: endTime }: { start: string; end: string }) => { - setCategoryQueryTimeRange((previousQueryParameters) => ({ - ...previousQueryParameters, - timeRange: stringToNumericTimeRange({ startTime, endTime }), - lastChangedTime: Date.now(), - })); - }, - [setCategoryQueryTimeRange] - ); + const handleQueryTimeRangeChange = useCallback( + ({ start: startTime, end: endTime }: { start: string; end: string }) => { + setCategoryQueryTimeRange((previousQueryParameters) => ({ + ...previousQueryParameters, + timeRange: stringToNumericTimeRange({ startTime, endTime }), + lastChangedTime: Date.now(), + })); + }, + [setCategoryQueryTimeRange] + ); - const handleSelectedTimeRangeChange = useCallback( - (selectedTime: { start: string; end: string; isInvalid: boolean }) => { - if (selectedTime.isInvalid) { - return; - } - setSelectedTimeRange({ - startTime: selectedTime.start, - endTime: selectedTime.end, - }); - handleQueryTimeRangeChange(selectedTime); - }, - [setSelectedTimeRange, handleQueryTimeRangeChange] - ); + const handleSelectedTimeRangeChange = useCallback( + (selectedTime: { start: string; end: string; isInvalid: boolean }) => { + if (selectedTime.isInvalid) { + return; + } + setSelectedTimeRange({ + startTime: selectedTime.start, + endTime: selectedTime.end, + }); + handleQueryTimeRangeChange(selectedTime); + }, + [setSelectedTimeRange, handleQueryTimeRangeChange] + ); - const handleAutoRefreshChange = useCallback( - ({ isPaused, refreshInterval: interval }: { isPaused: boolean; refreshInterval: number }) => { - setAutoRefresh({ - isPaused, - interval, - }); - }, - [setAutoRefresh] - ); + const handleAutoRefreshChange = useCallback( + ({ isPaused, refreshInterval: interval }: { isPaused: boolean; refreshInterval: number }) => { + setAutoRefresh({ + isPaused, + interval, + }); + }, + [setAutoRefresh] + ); - const hasResults = useMemo(() => topLogEntryCategories.length > 0, [ - topLogEntryCategories.length, - ]); + const hasResults = useMemo( + () => topLogEntryCategories.length > 0, + [topLogEntryCategories.length] + ); - const isFirstUse = useMemo( - () => - ((setupStatus.type === 'skipped' && !!setupStatus.newlyCreated) || - setupStatus.type === 'succeeded') && - !hasResults, - [hasResults, setupStatus] - ); + const isFirstUse = useMemo( + () => + ((setupStatus.type === 'skipped' && !!setupStatus.newlyCreated) || + setupStatus.type === 'succeeded') && + !hasResults, + [hasResults, setupStatus] + ); - useEffect(() => { - getTopLogEntryCategories(); - }, [ - getTopLogEntryCategories, - categoryQueryDatasets, - categoryQueryTimeRange.lastChangedTime, - sortOptions, - ]); + useEffect(() => { + getTopLogEntryCategories(); + }, [ + getTopLogEntryCategories, + categoryQueryDatasets, + categoryQueryTimeRange.lastChangedTime, + sortOptions, + ]); - useEffect(() => { - getLogEntryCategoryDatasets(); - }, [getLogEntryCategoryDatasets, categoryQueryTimeRange.lastChangedTime]); + useEffect(() => { + getLogEntryCategoryDatasets(); + }, [getLogEntryCategoryDatasets, categoryQueryTimeRange.lastChangedTime]); - useEffect(() => { - fetchModuleDefinition(); - }, [fetchModuleDefinition]); + useEffect(() => { + fetchModuleDefinition(); + }, [fetchModuleDefinition]); - useInterval(() => { - fetchJobStatus(); - }, JOB_STATUS_POLLING_INTERVAL); + useInterval(() => { + fetchJobStatus(); + }, JOB_STATUS_POLLING_INTERVAL); - useInterval( - () => { - handleQueryTimeRangeChange({ - start: selectedTimeRange.startTime, - end: selectedTimeRange.endTime, - }); - }, - autoRefresh.isPaused ? null : autoRefresh.interval - ); + useInterval( + () => { + handleQueryTimeRangeChange({ + start: selectedTimeRange.startTime, + end: selectedTimeRange.endTime, + }); + }, + autoRefresh.isPaused ? null : autoRefresh.interval + ); - const analyzeInMlLink = useMlHref(ml, http.basePath.get(), { - page: ML_PAGES.ANOMALY_EXPLORER, - pageState: { - jobIds: [jobIds['log-entry-categories-count']], - timeRange: { - from: moment(categoryQueryTimeRange.timeRange.startTime).format('YYYY-MM-DDTHH:mm:ss.SSSZ'), - to: moment(categoryQueryTimeRange.timeRange.endTime).format('YYYY-MM-DDTHH:mm:ss.SSSZ'), - mode: 'absolute', + const analyzeInMlLink = useMlHref(ml, http.basePath.get(), { + page: ML_PAGES.ANOMALY_EXPLORER, + pageState: { + jobIds: [jobIds['log-entry-categories-count']], + timeRange: { + from: moment(categoryQueryTimeRange.timeRange.startTime).format( + 'YYYY-MM-DDTHH:mm:ss.SSSZ' + ), + to: moment(categoryQueryTimeRange.timeRange.endTime).format('YYYY-MM-DDTHH:mm:ss.SSSZ'), + mode: 'absolute', + }, }, - }, - }); + }); - return ( - - , - , - ], - }} + return ( + - - - - - - - - - - - - - - - - - - - - - - ); -}; + , + , + ], + }} + > + + + + + + + + + + + + + + + + + + + + + + ); + }; const stringToNumericTimeRange = (timeRange: StringTimeRange): TimeRange => ({ startTime: moment( diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_setup_content.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_setup_content.tsx index 18adfaad03ef..c012d97dd1fc 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_setup_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_setup_content.tsx @@ -14,41 +14,40 @@ interface LogEntryCategoriesSetupContentProps { onOpenSetup: () => void; } -export const LogEntryCategoriesSetupContent: React.FunctionComponent = ({ - onOpenSetup, -}) => { - useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_setup' }); - useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_setup', delay: 15000 }); +export const LogEntryCategoriesSetupContent: React.FunctionComponent = + ({ onOpenSetup }) => { + useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_setup' }); + useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_setup', delay: 15000 }); - return ( - - - - } - body={ - -

+ return ( + -

-
- } - actions={ - - - - } - /> - ); -}; + + } + body={ + +

+ +

+
+ } + actions={ + + + + } + /> + ); + }; 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 73779af8752e..b4cfb301e040 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 @@ -18,7 +18,8 @@ import { callGetLogEntryCategoryDatasetsAPI } from './service_calls/get_log_entr import { useKibanaContextForPlugin } from '../../../hooks/use_kibana'; type TopLogEntryCategories = GetLogEntryCategoriesSuccessResponsePayload['data']['categories']; -type LogEntryCategoryDatasets = GetLogEntryCategoryDatasetsSuccessResponsePayload['data']['datasets']; +type LogEntryCategoryDatasets = + GetLogEntryCategoryDatasetsSuccessResponsePayload['data']['datasets']; export type SortOptions = CategoriesSort; export type ChangeSortOptions = (sortOptions: CategoriesSort) => void; @@ -46,10 +47,8 @@ export const useLogEntryCategoriesResults = ({ }); const { services } = useKibanaContextForPlugin(); const [topLogEntryCategories, setTopLogEntryCategories] = useState([]); - const [ - logEntryCategoryDatasets, - setLogEntryCategoryDatasets, - ] = useState([]); + const [logEntryCategoryDatasets, setLogEntryCategoryDatasets] = + useState([]); const [getTopLogEntryCategoriesRequest, getTopLogEntryCategories] = useTrackedPromise( { diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx index 2d833c87c1e2..2aac520dbc28 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx @@ -161,12 +161,14 @@ export const LogEntryRateResultsContent: React.FunctionComponent<{ const { showModuleList, showModuleSetup } = useLogAnalysisSetupFlyoutStateContext(); - const showLogEntryRateSetup = useCallback(() => showModuleSetup('logs_ui_analysis'), [ - showModuleSetup, - ]); - const showLogEntryCategoriesSetup = useCallback(() => showModuleSetup('logs_ui_categories'), [ - showModuleSetup, - ]); + const showLogEntryRateSetup = useCallback( + () => showModuleSetup('logs_ui_analysis'), + [showModuleSetup] + ); + const showLogEntryCategoriesSetup = useCallback( + () => showModuleSetup('logs_ui_categories'), + [showModuleSetup] + ); const hasAnomalyResults = logEntryAnomalies.length > 0; diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_anomalies_results.ts b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_anomalies_results.ts index 3cb0c4c89927..80123bb10e55 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_anomalies_results.ts +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_anomalies_results.ts @@ -27,7 +27,8 @@ export type FetchPreviousPage = () => void; export type ChangeSortOptions = (sortOptions: AnomaliesSort) => void; export type ChangePaginationOptions = (paginationOptions: PaginationOptions) => void; export type LogEntryAnomalies = LogEntryAnomaly[]; -type LogEntryAnomaliesDatasets = GetLogEntryAnomaliesDatasetsSuccessResponsePayload['data']['datasets']; +type LogEntryAnomaliesDatasets = + GetLogEntryAnomaliesDatasetsSuccessResponsePayload['data']['datasets']; interface PaginationCursors { previousPageCursor: PaginationCursor; nextPageCursor: PaginationCursor; @@ -285,10 +286,8 @@ export const useLogEntryAnomaliesResults = ({ ); // Anomalies datasets - const [ - logEntryAnomaliesDatasets, - setLogEntryAnomaliesDatasets, - ] = useState([]); + const [logEntryAnomaliesDatasets, setLogEntryAnomaliesDatasets] = + useState([]); const [getLogEntryAnomaliesDatasetsRequest, getLogEntryAnomaliesDatasets] = useTrackedPromise( { @@ -315,9 +314,10 @@ export const useLogEntryAnomaliesResults = ({ [endTime, sourceId, startTime] ); - const isLoadingDatasets = useMemo(() => getLogEntryAnomaliesDatasetsRequest.state === 'pending', [ - getLogEntryAnomaliesDatasetsRequest.state, - ]); + const isLoadingDatasets = useMemo( + () => getLogEntryAnomaliesDatasetsRequest.state === 'pending', + [getLogEntryAnomaliesDatasetsRequest.state] + ); const hasFailedLoadingDatasets = useMemo( () => getLogEntryAnomaliesDatasetsRequest.state === 'rejected', diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_examples.ts b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_examples.ts index 34d14de4aa94..8f6269c46c3d 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_examples.ts +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_examples.ts @@ -53,9 +53,10 @@ export const useLogEntryExamples = ({ [dataset, endTime, exampleCount, sourceId, startTime] ); - const isLoadingLogEntryExamples = useMemo(() => getLogEntryExamplesRequest.state === 'pending', [ - getLogEntryExamplesRequest.state, - ]); + const isLoadingLogEntryExamples = useMemo( + () => getLogEntryExamplesRequest.state === 'pending', + [getLogEntryExamplesRequest.state] + ); const hasFailedLoadingLogEntryExamples = useMemo( () => getLogEntryExamplesRequest.state === 'rejected', diff --git a/x-pack/plugins/infra/public/pages/logs/settings/fields_configuration_panel.tsx b/x-pack/plugins/infra/public/pages/logs/settings/fields_configuration_panel.tsx index 3f8922b1871c..d21b0b0588de 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/fields_configuration_panel.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/fields_configuration_panel.tsx @@ -118,18 +118,20 @@ export const FieldsConfigurationPanel = ({ defaultMessage="Timestamp" /> } - {...useMemo(() => getFormRowProps(timestampFieldFormElement), [ - timestampFieldFormElement, - ])} + {...useMemo( + () => getFormRowProps(timestampFieldFormElement), + [timestampFieldFormElement] + )} > getStringInputFieldProps(timestampFieldFormElement), [ - timestampFieldFormElement, - ])} + {...useMemo( + () => getStringInputFieldProps(timestampFieldFormElement), + [timestampFieldFormElement] + )} />
@@ -166,18 +168,20 @@ export const FieldsConfigurationPanel = ({ defaultMessage="Tiebreaker" /> } - {...useMemo(() => getFormRowProps(tiebreakerFieldFormElement), [ - tiebreakerFieldFormElement, - ])} + {...useMemo( + () => getFormRowProps(tiebreakerFieldFormElement), + [tiebreakerFieldFormElement] + )} > getStringInputFieldProps(tiebreakerFieldFormElement), [ - tiebreakerFieldFormElement, - ])} + {...useMemo( + () => getStringInputFieldProps(tiebreakerFieldFormElement), + [tiebreakerFieldFormElement] + )} /> diff --git a/x-pack/plugins/infra/public/pages/logs/settings/form_elements.tsx b/x-pack/plugins/infra/public/pages/logs/settings/form_elements.tsx index 90504a691cb9..8058a10bcd26 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/form_elements.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/form_elements.tsx @@ -141,10 +141,10 @@ export const useCompositeFormElement = ({ } }, [childFormElementEntries]); - const validity = useMemo(() => getCombinedValidity(formValidity, childFormElementsValidity), [ - formValidity, - childFormElementsValidity, - ]); + const validity = useMemo( + () => getCombinedValidity(formValidity, childFormElementsValidity), + [formValidity, childFormElementsValidity] + ); const resetValue = useCallback(() => { childFormElementEntries.forEach(([, formElement]) => formElement.resetValue()); @@ -180,10 +180,10 @@ const useValidity = ( value: Value, validate?: (value: Value) => Promise ) => { - const validationState = useAsync(() => validate?.(value) ?? Promise.resolve([]), [ - validate, - value, - ]); + const validationState = useAsync( + () => validate?.(value) ?? Promise.resolve([]), + [validate, value] + ); const validity = useMemo>(() => { if (validationState.loading) { @@ -236,8 +236,9 @@ export const getCombinedValidity = ( } }; -export const isFormElementForType = ( - isValue: (value: any) => value is Value -) => ( - formElement: FormElement -): formElement is FormElement => isValue(formElement.value); +export const isFormElementForType = + (isValue: (value: any) => value is Value) => + ( + formElement: FormElement + ): formElement is FormElement => + isValue(formElement.value); diff --git a/x-pack/plugins/infra/public/pages/logs/settings/form_field_props.tsx b/x-pack/plugins/infra/public/pages/logs/settings/form_field_props.tsx index 4a3927157b13..81711f7464da 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/form_field_props.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/form_field_props.tsx @@ -19,17 +19,19 @@ export const getFormRowProps = (formElement: FormElement( - decodeInputValue: (value: string) => Value, - encodeInputValue: (value: Value) => string -) => (formElement: FormElement) => ({ - isInvalid: formElement.validity.validity === 'invalid', - onChange: (evt: React.ChangeEvent) => { - const newValue = evt.currentTarget.value; - formElement.updateValue(() => decodeInputValue(newValue)); - }, - value: encodeInputValue(formElement.value), -}); +export const getInputFieldProps = + ( + decodeInputValue: (value: string) => Value, + encodeInputValue: (value: Value) => string + ) => + (formElement: FormElement) => ({ + isInvalid: formElement.validity.validity === 'invalid', + onChange: (evt: React.ChangeEvent) => { + const newValue = evt.currentTarget.value; + formElement.updateValue(() => decodeInputValue(newValue)); + }, + value: encodeInputValue(formElement.value), + }); export const getStringInputFieldProps = getInputFieldProps( (value) => `${value}`, diff --git a/x-pack/plugins/infra/public/pages/logs/settings/index_pattern_configuration_panel.tsx b/x-pack/plugins/infra/public/pages/logs/settings/index_pattern_configuration_panel.tsx index a16f15505bc3..7e466ee2a6ae 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/index_pattern_configuration_panel.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/index_pattern_configuration_panel.tsx @@ -79,10 +79,10 @@ export const IndexPatternConfigurationPanel: React.FC<{ defaultMessage="Log index pattern" /> } - {...useMemo(() => (isLoading ? {} : getFormRowProps(indexPatternFormElement)), [ - isLoading, - indexPatternFormElement, - ])} + {...useMemo( + () => (isLoading ? {} : getFormRowProps(indexPatternFormElement)), + [isLoading, indexPatternFormElement] + )} > void; }> = ({ logColumnConfiguration, dragHandleProps, onRemove }) => { - const removeColumn = useCallback(() => onRemove(logColumnConfiguration), [ - logColumnConfiguration, - onRemove, - ]); + const removeColumn = useCallback( + () => onRemove(logColumnConfiguration), + [logColumnConfiguration, onRemove] + ); return ( <> diff --git a/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_form_state.tsx b/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_form_state.tsx index 67e790a98f51..ac390a5bcfb8 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_form_state.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_form_state.tsx @@ -28,19 +28,16 @@ export const useLogSourceConfigurationFormState = ( ) ); - const { - fieldsFormElement, - tiebreakerFieldFormElement, - timestampFieldFormElement, - } = useFieldsFormElement( - useMemo( - () => ({ - tiebreakerField: configuration?.fields?.tiebreaker ?? '_doc', - timestampField: configuration?.fields?.timestamp ?? '@timestamp', - }), - [configuration] - ) - ); + const { fieldsFormElement, tiebreakerFieldFormElement, timestampFieldFormElement } = + useFieldsFormElement( + useMemo( + () => ({ + tiebreakerField: configuration?.fields?.tiebreaker ?? '_doc', + timestampField: configuration?.fields?.timestamp ?? '@timestamp', + }), + [configuration] + ) + ); const logColumnsFormElement = useLogColumnsFormElement( useMemo(() => configuration?.logColumns ?? [], [configuration]) 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 51355cab1fba..883c321db9ae 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 @@ -76,10 +76,10 @@ export const LogsSettingsPage = () => { sourceConfigurationFormElement.resetValue(); }, [updateSource, sourceConfigurationFormElement, formState]); - const isWriteable = useMemo(() => shouldAllowEdit && source && source.origin !== 'internal', [ - shouldAllowEdit, - source, - ]); + const isWriteable = useMemo( + () => shouldAllowEdit && source && source.origin !== 'internal', + [shouldAllowEdit, source] + ); if ((isLoading || isUninitialized) && !resolvedSourceConfiguration) { return ; 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 6d7f9fb09676..015476687d46 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 @@ -27,12 +27,8 @@ export const LogsToolbar = () => { const { availableTextScales, setTextScale, setTextWrap, textScale, textWrap } = useContext( LogViewConfiguration.Context ); - const { - filterQueryDraft, - isFilterQueryDraftValid, - applyLogFilterQuery, - setLogFilterQueryDraft, - } = useContext(LogFilterState.Context); + const { filterQueryDraft, isFilterQueryDraftValid, applyLogFilterQuery, setLogFilterQueryDraft } = + useContext(LogFilterState.Context); const { setSurroundingLogsId } = useContext(LogFlyout.Context); const { 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 5537ef9541f8..da507fac5272 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 @@ -25,10 +25,8 @@ import { LogStream } from '../../../components/log_stream'; const MODAL_MARGIN = 25; export const PageViewLogInContext: React.FC = () => { - const [ - { contextEntry, startTimestamp, endTimestamp, sourceId }, - { setContextEntry }, - ] = useContext(ViewLogInContext.Context); + const [{ contextEntry, startTimestamp, endTimestamp, sourceId }, { setContextEntry }] = + useContext(ViewLogInContext.Context); const closeModal = useCallback(() => setContextEntry(undefined), [setContextEntry]); const { width: vw, height: vh } = useViewportDimensions(); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomalies_table/anomalies_table.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomalies_table/anomalies_table.tsx index 98f3c82818dd..05227dd1ed5e 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomalies_table/anomalies_table.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomalies_table/anomalies_table.tsx @@ -268,16 +268,14 @@ export const AnomaliesTable = (props: Props) => { fetchPreviousPage: k8sPreviousPage, isLoadingMetricsK8sAnomalies: k8sLoading, } = useMetricsK8sAnomaliesResults(anomalyParams); - const page = useMemo(() => (jobType === 'hosts' ? hostPage : k8sPage), [ - jobType, - hostPage, - k8sPage, - ]); - const isLoading = useMemo(() => (jobType === 'hosts' ? hostLoading : k8sLoading), [ - jobType, - hostLoading, - k8sLoading, - ]); + const page = useMemo( + () => (jobType === 'hosts' ? hostPage : k8sPage), + [jobType, hostPage, k8sPage] + ); + const isLoading = useMemo( + () => (jobType === 'hosts' ? hostLoading : k8sLoading), + [jobType, hostLoading, k8sLoading] + ); const fetchNextPage = useMemo( () => (jobType === 'hosts' ? hostFetchNextPage : k8sFetchNextPage), [jobType, hostFetchNextPage, k8sFetchNextPage] diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/flyout_home.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/flyout_home.tsx index 993ae1d9d757..a16aff903776 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/flyout_home.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/flyout_home.tsx @@ -48,11 +48,8 @@ export const FlyoutHome = (props: Props) => { setupStatus: k8sSetupStatus, jobSummaries: k8sJobSummaries, } = useMetricK8sModuleContext(); - const { - hasInfraMLCapabilities, - hasInfraMLReadCapabilities, - hasInfraMLSetupCapabilities, - } = useInfraMLCapabilitiesContext(); + const { hasInfraMLCapabilities, hasInfraMLReadCapabilities, hasInfraMLSetupCapabilities } = + useInfraMLCapabilitiesContext(); const createHosts = useCallback(() => { goToSetup('hosts'); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/job_setup_screen.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/job_setup_screen.tsx index f6d739078002..fd75aa3bec7a 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/job_setup_screen.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/job_setup_screen.tsx @@ -80,9 +80,10 @@ export const JobSetupScreen = (props: Props) => { } }, [props.jobType, k.jobSummaries, h.jobSummaries]); - const derivedIndexPattern = useMemo(() => createDerivedIndexPattern(), [ - createDerivedIndexPattern, - ]); + const derivedIndexPattern = useMemo( + () => createDerivedIndexPattern(), + [createDerivedIndexPattern] + ); const updateStart = useCallback((date: Moment) => { setStartDate(date); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/overlay.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/overlay.tsx index e2803629afd5..f4c9f9b80413 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/overlay.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/overlay.tsx @@ -50,9 +50,10 @@ export const NodeContextPopover = ({ const inventoryModel = findInventoryModel(nodeType); const nodeDetailFrom = currentTime - inventoryModel.metrics.defaultTimeRangeInSeconds * 1000; const uiCapabilities = useKibana().services.application?.capabilities; - const canCreateAlerts = useMemo(() => Boolean(uiCapabilities?.infrastructure?.save), [ - uiCapabilities, - ]); + const canCreateAlerts = useMemo( + () => Boolean(uiCapabilities?.infrastructure?.save), + [uiCapabilities] + ); const tabs = useMemo(() => { return tabConfigs.map((m) => { diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/metrics/metrics.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/metrics/metrics.tsx index b554cb802421..fbb8bd469c1e 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/metrics/metrics.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/metrics/metrics.tsx @@ -72,9 +72,10 @@ const TabComponent = (props: TabProps) => { const { sourceId, createDerivedIndexPattern } = useSourceContext(); const { nodeType, accountId, region, customMetrics } = useWaffleOptionsContext(); const { currentTime, options, node } = props; - const derivedIndexPattern = useMemo(() => createDerivedIndexPattern('metrics'), [ - createDerivedIndexPattern, - ]); + const derivedIndexPattern = useMemo( + () => createDerivedIndexPattern('metrics'), + [createDerivedIndexPattern] + ); let filter = options.fields ? `${findInventoryFields(nodeType, options.fields).id}: "${node.id}"` : ''; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx index df3b37c0aa38..c227a31edc4a 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx @@ -46,13 +46,12 @@ const TabComponent = ({ currentTime, node, nodeType, options }: TabProps) => { return { [field]: node.name }; }, [options, node, nodeType]); - const { loading, error, response, makeRequest: reload } = useProcessList( - hostTerm, - timefield, - currentTime, - sortBy, - parseSearchString(searchFilter) - ); + const { + loading, + error, + response, + makeRequest: reload, + } = useProcessList(hostTerm, timefield, currentTime, sortBy, parseSearchString(searchFilter)); const debouncedSearchOnChange = useMemo( () => debounce<(queryText: string) => void>((queryText) => setSearchFilter(queryText), 500), diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/timeline/timeline.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/timeline/timeline.tsx index dd1023e7f018..65c3136cb48a 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/timeline/timeline.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/timeline/timeline.tsx @@ -81,12 +81,10 @@ export const Timeline: React.FC = ({ interval, yAxisFormatter, isVisible defaultPaginationOptions: { pageSize: 100 }, }; - const { metricsHostsAnomalies, getMetricsHostsAnomalies } = useMetricsHostsAnomaliesResults( - anomalyParams - ); - const { metricsK8sAnomalies, getMetricsK8sAnomalies } = useMetricsK8sAnomaliesResults( - anomalyParams - ); + const { metricsHostsAnomalies, getMetricsHostsAnomalies } = + useMetricsHostsAnomaliesResults(anomalyParams); + const { metricsK8sAnomalies, getMetricsK8sAnomalies } = + useMetricsK8sAnomaliesResults(anomalyParams); const getAnomalies = useMemo(() => { if (nodeType === 'host') { 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 2d3ff0beb252..062349fa3ec6 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 @@ -21,20 +21,19 @@ interface Props { formatter: InfraFormatter; } -const createTickRender = (bounds: InfraWaffleMapBounds, formatter: InfraFormatter) => ( - rule: InfraWaffleMapGradientRule, - index: number -) => { - const value = rule.value === 0 ? bounds.min : bounds.max * rule.value; - const style = { left: `${rule.value * 100}%` }; - const label = formatter(value); - return ( - - - {label} - - ); -}; +const createTickRender = + (bounds: InfraWaffleMapBounds, formatter: InfraFormatter) => + (rule: InfraWaffleMapGradientRule, index: number) => { + const value = rule.value === 0 ? bounds.min : bounds.max * rule.value; + const style = { left: `${rule.value * 100}%` }; + const label = formatter(value); + return ( + + + {label} + + ); + }; export const GradientLegend: React.FC = ({ legend, bounds, formatter }) => { const maxValue = legend.rules.reduce((acc, rule) => { diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_time_controls.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_time_controls.tsx index 765ae9d131ba..39150a98c2e8 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_time_controls.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_time_controls.tsx @@ -17,13 +17,8 @@ interface Props { } export const WaffleTimeControls = withTheme(({ theme }: Props) => { - const { - currentTime, - isAutoReloading, - startAutoReload, - stopAutoReload, - jumpToTime, - } = useWaffleTimeContext(); + const { currentTime, isAutoReloading, startAutoReload, stopAutoReload, jumpToTime } = + useWaffleTimeContext(); const currentMoment = moment(currentTime); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_metrics_k8s_anomalies.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_metrics_k8s_anomalies.ts index 384cefa691d9..986c4dfa2f8e 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_metrics_k8s_anomalies.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_metrics_k8s_anomalies.ts @@ -315,16 +315,8 @@ export const callGetMetricsK8sAnomaliesAPI = async ( requestArgs: RequestArgs, fetch: HttpHandler ) => { - const { - sourceId, - anomalyThreshold, - startTime, - endTime, - metric, - query, - sort, - pagination, - } = requestArgs; + const { sourceId, anomalyThreshold, startTime, endTime, metric, query, sort, pagination } = + requestArgs; const response = await fetch(INFA_ML_GET_METRICS_K8S_ANOMALIES_PATH, { method: 'POST', body: JSON.stringify( diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_timeline.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_timeline.ts index b210379910c3..53ff7e318e1f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_timeline.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_timeline.ts @@ -77,9 +77,10 @@ export function useTimeline( const displayInterval = useMemo(() => getDisplayInterval(interval), [interval]); - const timeLengthResult = useMemo(() => getTimeLengthFromInterval(displayInterval), [ - displayInterval, - ]); + const timeLengthResult = useMemo( + () => getTimeLengthFromInterval(displayInterval), + [displayInterval] + ); const { timeLength, intervalInSeconds } = timeLengthResult; const endTime = currentTime + intervalInSeconds * 1000; 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 90cf96330e75..67bc13251de2 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 @@ -66,9 +66,10 @@ export const useWaffleFilters = () => { setFilterQueryDraft(filterQuery.expression); }, []); - const isFilterQueryDraftValid = useMemo(() => validateKuery(filterQueryDraft), [ - filterQueryDraft, - ]); + const isFilterQueryDraftValid = useMemo( + () => validateKuery(filterQueryDraft), + [filterQueryDraft] + ); const { inventoryPrefill } = useAlertPrefillContext(); const prefillContext = useMemo(() => inventoryPrefill, [inventoryPrefill]); // For Jest compatibility diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.test.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.test.ts index 0d8114af3d05..06b6138404a6 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.test.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.test.ts @@ -56,8 +56,7 @@ describe('useWaffleOptions', () => { customMetrics: [ { type: 'custom', - id: - "i don't want to bother to copy and paste an actual uuid so instead i'm going to smash my keyboard skjdghsjodkyjheurvjnsgn", + id: "i don't want to bother to copy and paste an actual uuid so instead i'm going to smash my keyboard skjdghsjodkyjheurvjnsgn", aggregation: 'avg', field: 'hey.system.are.you.good', }, diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_inventory_metric_formatter.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_inventory_metric_formatter.ts index b6ba48290010..ca09762442d2 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_inventory_metric_formatter.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_inventory_metric_formatter.ts @@ -78,17 +78,16 @@ const METRIC_FORMATTERS: MetricFormatters = { }, }; -export const createInventoryMetricFormatter = (metric: SnapshotMetricInput) => ( - val: string | number -) => { - if (SnapshotCustomMetricInputRT.is(metric)) { - const formatter = createFormatterForMetric(metric); +export const createInventoryMetricFormatter = + (metric: SnapshotMetricInput) => (val: string | number) => { + if (SnapshotCustomMetricInputRT.is(metric)) { + const formatter = createFormatterForMetric(metric); + return formatter(val); + } + const metricFormatter = get(METRIC_FORMATTERS, metric.type, METRIC_FORMATTERS.count); + if (val == null) { + return ''; + } + const formatter = createFormatter(metricFormatter.formatter, metricFormatter.template); return formatter(val); - } - const metricFormatter = get(METRIC_FORMATTERS, metric.type, METRIC_FORMATTERS.count); - if (val == null) { - return ''; - } - const formatter = createFormatter(metricFormatter.formatter, metricFormatter.template); - return formatter(val); -}; + }; diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/gauges_section_vis.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/gauges_section_vis.tsx index a4faa3d6c475..709357719763 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/gauges_section_vis.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/gauges_section_vis.tsx @@ -23,23 +23,25 @@ import { InventoryFormatterType } from '../../../../../common/inventory_models/t import { SeriesOverrides, VisSectionProps } from '../types'; import { getChartName } from './helpers'; -const getFormatter = ( - defaultFormatter: InventoryFormatterType = 'number', - defaultFormatterTemplate: string = '{{value}}', - seriesOverrides: SeriesOverrides = {}, - seriesId: string -) => (val: ReactText) => { - if (val == null) { - return ''; - } - const formatter = get(seriesOverrides, [seriesId, 'formatter'], defaultFormatter); - const formatterTemplate = get( - seriesOverrides, - [seriesId, 'formatterTemplate'], - defaultFormatterTemplate - ); - return createFormatter(formatter, formatterTemplate)(val); -}; +const getFormatter = + ( + defaultFormatter: InventoryFormatterType = 'number', + defaultFormatterTemplate: string = '{{value}}', + seriesOverrides: SeriesOverrides = {}, + seriesId: string + ) => + (val: ReactText) => { + if (val == null) { + return ''; + } + const formatter = get(seriesOverrides, [seriesId, 'formatter'], defaultFormatter); + const formatterTemplate = get( + seriesOverrides, + [seriesId, 'formatterTemplate'], + defaultFormatterTemplate + ); + return createFormatter(formatter, formatterTemplate)(val); + }; export const GaugesSectionVis = ({ id, diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/helpers.ts b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/helpers.ts index a0a795a760b5..0602e8a39b03 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/helpers.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/helpers.ts @@ -23,10 +23,10 @@ import { /** * Returns a formatter */ -export const getFormatter = ( - formatter: InventoryFormatterType = 'number', - template: string = '{{value}}' -) => (val: ReactText) => (val != null ? createFormatter(formatter, template)(val) : ''); +export const getFormatter = + (formatter: InventoryFormatterType = 'number', template: string = '{{value}}') => + (val: ReactText) => + val != null ? createFormatter(formatter, template)(val) : ''; /** * Does a series have more then two points? diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/page_providers.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/page_providers.tsx index c4e1b6bf8ef1..6f44d49ddce9 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/page_providers.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/page_providers.tsx @@ -10,14 +10,15 @@ import React from 'react'; import { Source } from '../../../containers/metrics_source'; import { MetricsTimeProvider } from './hooks/use_metrics_time'; -export const withMetricPageProviders = (Component: React.ComponentType) => ( - props: T -) => ( - - - - - - - -); +export const withMetricPageProviders = + (Component: React.ComponentType) => + (props: T) => + ( + + + + + + + + ); diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.test.ts b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.test.ts index a7ed8763d1c7..a9e65bc30a3c 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.test.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.test.ts @@ -22,7 +22,7 @@ import { MetricsExplorerOptions } from '../../hooks/use_metrics_explorer_options jest.mock('uuid'); const mockedUuid = uuid as jest.Mocked; -mockedUuid.v1.mockReturnValue(('test-id' as unknown) as OutputBuffer); +mockedUuid.v1.mockReturnValue('test-id' as unknown as OutputBuffer); const series = { id: 'example-01', rows: [], columns: [] }; describe('createTSVBLink()', () => { @@ -32,8 +32,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -50,8 +49,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:bytes,id:test-id,label:'rate(system.network.out.bytes)',line_width:2,metrics:!((field:system.network.out.bytes,id:test-id,type:max),(field:test-id,id:test-id,type:derivative,unit:'1s'),(field:test-id,id:test-id,type:positive_only)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}}/s)),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:bytes,id:test-id,label:'rate(system.network.out.bytes)',line_width:2,metrics:!((field:system.network.out.bytes,id:test-id,type:max),(field:test-id,id:test-id,type:derivative,unit:'1s'),(field:test-id,id:test-id,type:positive_only)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}}/s)),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -64,8 +62,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-10m,to:now))', type: 'metrics', }, @@ -82,8 +79,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'my-beats-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'my-beats-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:time,type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'my-beats-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'my-beats-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:time,type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -101,8 +97,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'my-beats-*',filter:(language:kuery,query:'system.network.name:lo* and host.name : \"example-01\"'),id:test-id,index_pattern:'my-beats-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:time,type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'my-beats-*',filter:(language:kuery,query:'system.network.name:lo* and host.name : \"example-01\"'),id:test-id,index_pattern:'my-beats-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:time,type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -116,8 +111,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -131,8 +125,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0.5,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0.5,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -150,8 +143,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0.5,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:stacked,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0.5,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:stacked,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -169,8 +161,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metric*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metric*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:time,type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metric*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metric*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:time,type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts index 1a549041823e..84d87ee4ad1b 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts @@ -84,27 +84,26 @@ export const metricsExplorerMetricToTSVBMetric = (metric: MetricsExplorerOptions } }; -const mapMetricToSeries = (chartOptions: MetricsExplorerChartOptions) => ( - metric: MetricsExplorerOptionsMetric -) => { - const format = metricToFormat(metric); - return { - label: createMetricLabel(metric), - axis_position: 'right', - chart_type: 'line', - color: (metric.color && colorTransformer(metric.color)) || colorTransformer(Color.color0), - fill: chartOptions.type === MetricsExplorerChartType.area ? 0.5 : 0, - formatter: format === InfraFormatterType.bits ? InfraFormatterType.bytes : format, - value_template: 'rate' === metric.aggregation ? '{{value}}/s' : '{{value}}', - id: uuid.v1(), - line_width: 2, - metrics: metricsExplorerMetricToTSVBMetric(metric), - point_size: 0, - separate_axis: 0, - split_mode: 'everything', - stacked: chartOptions.stack ? 'stacked' : 'none', +const mapMetricToSeries = + (chartOptions: MetricsExplorerChartOptions) => (metric: MetricsExplorerOptionsMetric) => { + const format = metricToFormat(metric); + return { + label: createMetricLabel(metric), + axis_position: 'right', + chart_type: 'line', + color: (metric.color && colorTransformer(metric.color)) || colorTransformer(Color.color0), + fill: chartOptions.type === MetricsExplorerChartType.area ? 0.5 : 0, + formatter: format === InfraFormatterType.bits ? InfraFormatterType.bytes : format, + value_template: 'rate' === metric.aggregation ? '{{value}}/s' : '{{value}}', + id: uuid.v1(), + line_width: 2, + metrics: metricsExplorerMetricToTSVBMetric(metric), + point_size: 0, + separate_axis: 0, + split_mode: 'everything', + stacked: chartOptions.stack ? 'stacked' : 'none', + }; }; -}; export const createFilterFromOptions = ( options: MetricsExplorerOptions, diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/kuery_bar.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/kuery_bar.tsx index e22c6fa66118..cf201c9a57f7 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/kuery_bar.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/kuery_bar.tsx @@ -99,5 +99,7 @@ export const MetricsExplorerKueryBar = ({ ); }; -const defaultCurryLoadSuggestions: CurryLoadSuggestionsType = (loadSuggestions) => (...args) => - loadSuggestions(...args); +const defaultCurryLoadSuggestions: CurryLoadSuggestionsType = + (loadSuggestions) => + (...args) => + loadSuggestions(...args); diff --git a/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_form_state.tsx b/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_form_state.tsx index 37da4bd1aa1b..909bf294e409 100644 --- a/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_form_state.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_form_state.tsx @@ -32,21 +32,24 @@ export const useSourceConfigurationFormState = ( ), }); - const errors = useMemo(() => [...indicesConfigurationFormState.errors], [ - indicesConfigurationFormState.errors, - ]); + const errors = useMemo( + () => [...indicesConfigurationFormState.errors], + [indicesConfigurationFormState.errors] + ); const resetForm = useCallback(() => { indicesConfigurationFormState.resetForm(); }, [indicesConfigurationFormState]); - const isFormDirty = useMemo(() => indicesConfigurationFormState.isFormDirty, [ - indicesConfigurationFormState.isFormDirty, - ]); + const isFormDirty = useMemo( + () => indicesConfigurationFormState.isFormDirty, + [indicesConfigurationFormState.isFormDirty] + ); - const isFormValid = useMemo(() => indicesConfigurationFormState.isFormValid, [ - indicesConfigurationFormState.isFormValid, - ]); + const isFormValid = useMemo( + () => indicesConfigurationFormState.isFormValid, + [indicesConfigurationFormState.isFormValid] + ); const formState = useMemo( () => ({ diff --git a/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_settings.tsx b/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_settings.tsx index 62577b949bdb..0adf4ed6b5b4 100644 --- a/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_settings.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_settings.tsx @@ -76,10 +76,10 @@ export const SourceConfigurationSettings = ({ formStateChanges, ]); - const isWriteable = useMemo(() => shouldAllowEdit && source && source.origin !== 'internal', [ - shouldAllowEdit, - source, - ]); + const isWriteable = useMemo( + () => shouldAllowEdit && source && source.origin !== 'internal', + [shouldAllowEdit, source] + ); const { hasInfraMLCapabilities } = useInfraMLCapabilitiesContext(); diff --git a/x-pack/plugins/infra/public/plugin.ts b/x-pack/plugins/infra/public/plugin.ts index 76e3e777e637..712b7c01b9f0 100644 --- a/x-pack/plugins/infra/public/plugin.ts +++ b/x-pack/plugins/infra/public/plugin.ts @@ -59,33 +59,39 @@ export class Plugin implements InfraClientPluginClass { /** !! Need to be kept in sync with the deepLinks in x-pack/plugins/infra/public/plugin.ts */ pluginsSetup.observability.navigation.registerSections( from(core.getStartServices()).pipe( - map(([{ application: { capabilities } }]) => [ - ...(capabilities.logs.show - ? [ - { - label: 'Logs', - sortKey: 200, - entries: [ - { label: 'Stream', app: 'logs', path: '/stream' }, - { label: 'Anomalies', app: 'logs', path: '/anomalies' }, - { label: 'Categories', app: 'logs', path: '/log-categories' }, - ], - }, - ] - : []), - ...(capabilities.infrastructure.show - ? [ - { - label: 'Metrics', - sortKey: 300, - entries: [ - { label: 'Inventory', app: 'metrics', path: '/inventory' }, - { label: 'Metrics Explorer', app: 'metrics', path: '/explorer' }, - ], - }, - ] - : []), - ]) + map( + ([ + { + application: { capabilities }, + }, + ]) => [ + ...(capabilities.logs.show + ? [ + { + label: 'Logs', + sortKey: 200, + entries: [ + { label: 'Stream', app: 'logs', path: '/stream' }, + { label: 'Anomalies', app: 'logs', path: '/anomalies' }, + { label: 'Categories', app: 'logs', path: '/log-categories' }, + ], + }, + ] + : []), + ...(capabilities.infrastructure.show + ? [ + { + label: 'Metrics', + sortKey: 300, + entries: [ + { label: 'Inventory', app: 'metrics', path: '/inventory' }, + { label: 'Metrics Explorer', app: 'metrics', path: '/explorer' }, + ], + }, + ] + : []), + ] + ) ) ); diff --git a/x-pack/plugins/infra/public/utils/data_search/normalize_data_search_responses.ts b/x-pack/plugins/infra/public/utils/data_search/normalize_data_search_responses.ts index 4c329110ae46..71975af168f9 100644 --- a/x-pack/plugins/infra/public/utils/data_search/normalize_data_search_responses.ts +++ b/x-pack/plugins/infra/public/utils/data_search/normalize_data_search_responses.ts @@ -12,9 +12,10 @@ import { AbortError } from '../../../../../../src/plugins/kibana_utils/public'; import { SearchStrategyError } from '../../../common/search_strategies/common/errors'; import { ParsedKibanaSearchResponse } from './types'; -export type RawResponseParser = ( - rawResponse: RawResponse -) => { data: Response; errors?: SearchStrategyError[] }; +export type RawResponseParser = (rawResponse: RawResponse) => { + data: Response; + errors?: SearchStrategyError[]; +}; /** * An operator factory that normalizes each {@link IKibanaSearchResponse} by @@ -30,49 +31,51 @@ export type RawResponseParser = ( * @return An operator that adds parsing and error handling transformations to * each response payload using the arguments given above. */ -export const normalizeDataSearchResponses = ( - initialResponse: InitialResponse, - parseRawResponse: RawResponseParser -) => ( - response$: Observable> -): Observable> => - response$.pipe( - map((response) => { - const { data, errors = [] } = parseRawResponse(response.rawResponse); - return { - data, - errors, - isPartial: response.isPartial ?? false, - isRunning: response.isRunning ?? false, - loaded: response.loaded, - total: response.total, - }; - }), - startWith({ - data: initialResponse, - errors: [], - isPartial: true, - isRunning: true, - loaded: 0, - total: undefined, - }), - catchError((error) => - of({ +export const normalizeDataSearchResponses = + ( + initialResponse: InitialResponse, + parseRawResponse: RawResponseParser + ) => + ( + response$: Observable> + ): Observable> => + response$.pipe( + map((response) => { + const { data, errors = [] } = parseRawResponse(response.rawResponse); + return { + data, + errors, + isPartial: response.isPartial ?? false, + isRunning: response.isRunning ?? false, + loaded: response.loaded, + total: response.total, + }; + }), + startWith({ data: initialResponse, - errors: [ - error instanceof AbortError - ? { - type: 'aborted' as const, - } - : { - type: 'generic' as const, - message: `${error.message ?? error}`, - }, - ], + errors: [], isPartial: true, - isRunning: false, + isRunning: true, loaded: 0, total: undefined, - }) - ) - ); + }), + catchError((error) => + of({ + data: initialResponse, + errors: [ + error instanceof AbortError + ? { + type: 'aborted' as const, + } + : { + type: 'generic' as const, + message: `${error.message ?? error}`, + }, + ], + isPartial: true, + isRunning: false, + loaded: 0, + total: undefined, + }) + ) + ); diff --git a/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.test.tsx b/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.test.tsx index 1ed912b0e01f..71c49ef75023 100644 --- a/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.test.tsx +++ b/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.test.tsx @@ -107,9 +107,8 @@ describe('useLatestPartialDataSearchResponse hook', () => { }), }; - const requests$ = of, string>>( - firstRequest - ); + const requests$ = + of, string>>(firstRequest); const { unmount } = renderHook(() => useLatestPartialDataSearchResponse(requests$)); diff --git a/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.ts b/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.ts index 741136b51311..2cafceaad3cb 100644 --- a/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.ts +++ b/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.ts @@ -16,9 +16,8 @@ import { useDataSearchResponseState } from './use_data_search_response_state'; export const useLatestPartialDataSearchResponse = ( requests$: Observable> ) => { - const latestResponse$: Observable< - ParsedDataSearchResponseDescriptor - > = useOperator(requests$, flattenLatestDataSearchResponse); + const latestResponse$: Observable> = + useOperator(requests$, flattenLatestDataSearchResponse); const { cancelRequest, diff --git a/x-pack/plugins/infra/public/utils/loading_state/loading_progress.ts b/x-pack/plugins/infra/public/utils/loading_state/loading_progress.ts index 5ddc5761f03c..4670883ec2a7 100644 --- a/x-pack/plugins/infra/public/utils/loading_state/loading_progress.ts +++ b/x-pack/plugins/infra/public/utils/loading_state/loading_progress.ts @@ -25,17 +25,19 @@ export const isRunningLoadingProgress =

( loadingProgress: LoadingProgress

): loadingProgress is RunningLoadingProgress

=> loadingProgress.progress === 'running'; -export const createIdleProgressReducer = () => ( - state: LoadingProgress -): IdleLoadingProgress => ({ - progress: 'idle', -}); +export const createIdleProgressReducer = + () => + (state: LoadingProgress): IdleLoadingProgress => ({ + progress: 'idle', + }); -export const createRunningProgressReducer = () => ( - state: LoadingProgress, - parameters: Parameters -): RunningLoadingProgress => ({ - parameters, - progress: 'running', - time: Date.now(), -}); +export const createRunningProgressReducer = + () => + ( + state: LoadingProgress, + parameters: Parameters + ): RunningLoadingProgress => ({ + parameters, + progress: 'running', + time: Date.now(), + }); 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 683de7aeedc1..09411f6c6fce 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 @@ -64,12 +64,15 @@ export const createSuccessResult = ( time: Date.now(), }); -export const createSuccessResultReducer = ( - isExhausted: (params: Parameters, result: Payload) => boolean -) => ( - state: LoadingResult, - { params, result }: { params: Parameters; result: Payload } -): SuccessLoadingResult => createSuccessResult(params, isExhausted(params, result)); +export const createSuccessResultReducer = + ( + isExhausted: (params: Parameters, result: Payload) => boolean + ) => + ( + state: LoadingResult, + { params, result }: { params: Parameters; result: Payload } + ): SuccessLoadingResult => + createSuccessResult(params, isExhausted(params, result)); export const createFailureResult = ( parameters: Parameters, @@ -81,9 +84,12 @@ export const createFailureResult = ( time: Date.now(), }); -export const createFailureResultReducer = ( - convertErrorToString: (error: ErrorPayload) => string = (error) => `${error}` -) => ( - state: LoadingResult, - { params, error }: { params: Parameters; error: ErrorPayload } -): FailureLoadingResult => createFailureResult(params, convertErrorToString(error)); +export const createFailureResultReducer = + ( + convertErrorToString: (error: ErrorPayload) => string = (error) => `${error}` + ) => + ( + state: LoadingResult, + { params, error }: { params: Parameters; error: ErrorPayload } + ): FailureLoadingResult => + createFailureResult(params, convertErrorToString(error)); diff --git a/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts b/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts index 8d51f54e3f55..6dfb40056771 100644 --- a/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts +++ b/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts @@ -21,9 +21,10 @@ const mockedCallFetchLogSourceStatusAPI = callFetchLogSourceStatusAPI as jest.Mo >; jest.mock('../containers/logs/log_source/api/fetch_log_source_configuration'); -const mockedCallFetchLogSourceConfigurationAPI = callFetchLogSourceConfigurationAPI as jest.MockedFunction< - typeof callFetchLogSourceConfigurationAPI ->; +const mockedCallFetchLogSourceConfigurationAPI = + callFetchLogSourceConfigurationAPI as jest.MockedFunction< + typeof callFetchLogSourceConfigurationAPI + >; const DEFAULT_PARAMS = { absoluteTime: { start: 1593430680000, end: 1593430800000 }, diff --git a/x-pack/plugins/infra/public/utils/styles.ts b/x-pack/plugins/infra/public/utils/styles.ts index db979a9ac68e..bd0ba2099d95 100644 --- a/x-pack/plugins/infra/public/utils/styles.ts +++ b/x-pack/plugins/infra/public/utils/styles.ts @@ -19,9 +19,7 @@ const asPropReader = (reader: string | string[] | PropReader) => ) => get(props, reader as Prop, defaultValue); export const switchProp = Object.assign( - (propName: string | string[] | PropReader, options: Map | object) => ( - props: object - ) => { + (propName: string | string[] | PropReader, options: Map | object) => (props: object) => { const propValue = asPropReader(propName)(props, switchProp.default); if (typeof propValue === 'undefined') { return; @@ -33,11 +31,10 @@ export const switchProp = Object.assign( } ); -export const ifProp = ( - propName: string | string[] | PropReader, - pass: Pass, - fail: Fail -) => (props: object) => (asPropReader(propName)(props) ? pass : fail); +export const ifProp = + (propName: string | string[] | PropReader, pass: Pass, fail: Fail) => + (props: object) => + asPropReader(propName)(props) ? pass : fail; export const tintOrShade = ( textColor: string, diff --git a/x-pack/plugins/infra/public/utils/typed_redux.ts b/x-pack/plugins/infra/public/utils/typed_redux.ts index 04b3190c0146..cd02539e719b 100644 --- a/x-pack/plugins/infra/public/utils/typed_redux.ts +++ b/x-pack/plugins/infra/public/utils/typed_redux.ts @@ -23,15 +23,13 @@ export type GlobalSelectors = { >; }; -export const globalizeSelector = < - GlobalState, - LocalSelector extends Selector, - LocalState = any, - Value = any ->( - globalizer: Selector, - selector: LocalSelector -): Selector => (globalState: GlobalState) => selector(globalizer(globalState)); +export const globalizeSelector = + , LocalState = any, Value = any>( + globalizer: Selector, + selector: LocalSelector + ): Selector => + (globalState: GlobalState) => + selector(globalizer(globalState)); export const globalizeSelectors = < GlobalState, @@ -63,9 +61,9 @@ type PlainActionCreator = WrappedActionCreator extends () ? (payload: A) => R : never; -export const bindPlainActionCreators = ( - actionCreators: WrappedActionCreators -) => (dispatch: Dispatch) => - (bindActionCreators(actionCreators, dispatch) as unknown) as { - [P in keyof WrappedActionCreators]: PlainActionCreator; - }; +export const bindPlainActionCreators = + (actionCreators: WrappedActionCreators) => + (dispatch: Dispatch) => + bindActionCreators(actionCreators, dispatch) as unknown as { + [P in keyof WrappedActionCreators]: PlainActionCreator; + }; diff --git a/x-pack/plugins/infra/public/utils/url_state.tsx b/x-pack/plugins/infra/public/utils/url_state.tsx index 0e6c38e893ca..8148463ab3fe 100644 --- a/x-pack/plugins/infra/public/utils/url_state.tsx +++ b/x-pack/plugins/infra/public/utils/url_state.tsx @@ -152,20 +152,19 @@ export const getParamFromQueryString = (queryString: string, key: string): strin return Array.isArray(queryParam) ? queryParam[0] : queryParam; }; -export const replaceStateKeyInQueryString = ( - stateKey: string, - urlState: UrlState | undefined -) => (queryString: string) => { - const previousQueryValues = parse(queryString, { sort: false }); - const newValue = - typeof urlState === 'undefined' - ? previousQueryValues - : { - ...previousQueryValues, - [stateKey]: encodeRisonUrlState(urlState), - }; - return stringify(url.encodeQuery(newValue), { sort: false, encode: false }); -}; +export const replaceStateKeyInQueryString = + (stateKey: string, urlState: UrlState | undefined) => + (queryString: string) => { + const previousQueryValues = parse(queryString, { sort: false }); + const newValue = + typeof urlState === 'undefined' + ? previousQueryValues + : { + ...previousQueryValues, + [stateKey]: encodeRisonUrlState(urlState), + }; + return stringify(url.encodeQuery(newValue), { sort: false, encode: false }); + }; const replaceQueryStringInLocation = (location: Location, queryString: string): Location => { if (queryString === getQueryStringFromLocation(location)) { diff --git a/x-pack/plugins/infra/public/utils/use_observable.ts b/x-pack/plugins/infra/public/utils/use_observable.ts index 345d57e6fa5f..87d182c94ac0 100644 --- a/x-pack/plugins/infra/public/utils/use_observable.ts +++ b/x-pack/plugins/infra/public/utils/use_observable.ts @@ -95,17 +95,19 @@ export const useOperator = ( ); }; -export const tapUnsubscribe = (onUnsubscribe: () => void) => (source$: Observable) => { - return new Observable((subscriber) => { - const subscription = source$.subscribe({ - next: (value) => subscriber.next(value), - error: (error) => subscriber.error(error), - complete: () => subscriber.complete(), +export const tapUnsubscribe = + (onUnsubscribe: () => void) => + (source$: Observable) => { + return new Observable((subscriber) => { + const subscription = source$.subscribe({ + next: (value) => subscriber.next(value), + error: (error) => subscriber.error(error), + complete: () => subscriber.complete(), + }); + + return () => { + onUnsubscribe(); + subscription.unsubscribe(); + }; }); - - return () => { - onUnsubscribe(); - subscription.unsubscribe(); - }; - }); -}; + }; 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 1b0c290bd651..4380db2dcb4c 100644 --- a/x-pack/plugins/infra/public/utils/use_tracked_promise.ts +++ b/x-pack/plugins/infra/public/utils/use_tracked_promise.ts @@ -113,109 +113,110 @@ export const useTrackedPromise = ( }); const execute = useMemo( - () => (...args: Arguments) => { - let rejectCancellationPromise!: (value: any) => void; - const cancellationPromise = new Promise((_, reject) => { - rejectCancellationPromise = reject; - }); - - // remember the list of prior pending promises for cancellation - const previousPendingPromises = pendingPromises.current; - - const cancelPreviousPendingPromises = () => { - previousPendingPromises.forEach((promise) => promise.cancel()); - }; - - const newPromise = createPromise(...args); - const newCancelablePromise = Promise.race([newPromise, cancellationPromise]); - - // track this new state - setPromiseState({ - state: 'pending', - promise: newCancelablePromise, - }); - - if (cancelPreviousOn === 'creation') { - cancelPreviousPendingPromises(); - } - - const newPendingPromise: CancelablePromise = { - cancel: () => { - rejectCancellationPromise(new CanceledPromiseError()); - }, - cancelSilently: () => { - rejectCancellationPromise(new SilentCanceledPromiseError()); - }, - promise: newCancelablePromise.then( - (value) => { - setPromiseState((previousPromiseState) => - previousPromiseState.state === 'pending' && - previousPromiseState.promise === newCancelablePromise - ? { - state: 'resolved', - promise: newPendingPromise.promise, - value, - } - : previousPromiseState - ); - - if (['settlement', 'resolution'].includes(cancelPreviousOn)) { - cancelPreviousPendingPromises(); - } - - // remove itself from the list of pending promises - pendingPromises.current = pendingPromises.current.filter( - (pendingPromise) => pendingPromise.promise !== newPendingPromise.promise - ); - - if (onResolve && shouldTriggerOrThrow()) { - onResolve(value); - } - - return value; + () => + (...args: Arguments) => { + let rejectCancellationPromise!: (value: any) => void; + const cancellationPromise = new Promise((_, reject) => { + rejectCancellationPromise = reject; + }); + + // remember the list of prior pending promises for cancellation + const previousPendingPromises = pendingPromises.current; + + const cancelPreviousPendingPromises = () => { + previousPendingPromises.forEach((promise) => promise.cancel()); + }; + + const newPromise = createPromise(...args); + const newCancelablePromise = Promise.race([newPromise, cancellationPromise]); + + // track this new state + setPromiseState({ + state: 'pending', + promise: newCancelablePromise, + }); + + if (cancelPreviousOn === 'creation') { + cancelPreviousPendingPromises(); + } + + const newPendingPromise: CancelablePromise = { + cancel: () => { + rejectCancellationPromise(new CanceledPromiseError()); }, - (value) => { - if (!(value instanceof SilentCanceledPromiseError)) { + cancelSilently: () => { + rejectCancellationPromise(new SilentCanceledPromiseError()); + }, + promise: newCancelablePromise.then( + (value) => { setPromiseState((previousPromiseState) => previousPromiseState.state === 'pending' && previousPromiseState.promise === newCancelablePromise ? { - state: 'rejected', - promise: newCancelablePromise, + state: 'resolved', + promise: newPendingPromise.promise, value, } : previousPromiseState ); - } - if (['settlement', 'rejection'].includes(cancelPreviousOn)) { - cancelPreviousPendingPromises(); - } + if (['settlement', 'resolution'].includes(cancelPreviousOn)) { + cancelPreviousPendingPromises(); + } - // remove itself from the list of pending promises - pendingPromises.current = pendingPromises.current.filter( - (pendingPromise) => pendingPromise.promise !== newPendingPromise.promise - ); + // remove itself from the list of pending promises + pendingPromises.current = pendingPromises.current.filter( + (pendingPromise) => pendingPromise.promise !== newPendingPromise.promise + ); - if (shouldTriggerOrThrow()) { - if (onReject) { - onReject(value); + if (onResolve && shouldTriggerOrThrow()) { + onResolve(value); } - throw value; + return value; + }, + (value) => { + if (!(value instanceof SilentCanceledPromiseError)) { + setPromiseState((previousPromiseState) => + previousPromiseState.state === 'pending' && + previousPromiseState.promise === newCancelablePromise + ? { + state: 'rejected', + promise: newCancelablePromise, + value, + } + : previousPromiseState + ); + } + + if (['settlement', 'rejection'].includes(cancelPreviousOn)) { + cancelPreviousPendingPromises(); + } + + // remove itself from the list of pending promises + pendingPromises.current = pendingPromises.current.filter( + (pendingPromise) => pendingPromise.promise !== newPendingPromise.promise + ); + + if (shouldTriggerOrThrow()) { + if (onReject) { + onReject(value); + } + + throw value; + } } - } - ), - }; + ), + }; - // add the new promise to the list of pending promises - pendingPromises.current = [...pendingPromises.current, newPendingPromise]; + // add the new promise to the list of pending promises + pendingPromises.current = [...pendingPromises.current, newPendingPromise]; - // silence "unhandled rejection" warnings - newPendingPromise.promise.catch(noOp); + // silence "unhandled rejection" warnings + newPendingPromise.promise.catch(noOp); - return newPendingPromise.promise; - }, + return newPendingPromise.promise; + }, // the dependencies are managed by the caller // eslint-disable-next-line react-hooks/exhaustive-deps dependencies diff --git a/x-pack/plugins/infra/public/utils/use_url_state.ts b/x-pack/plugins/infra/public/utils/use_url_state.ts index 970b3a20b295..eef82438ff01 100644 --- a/x-pack/plugins/infra/public/utils/use_url_state.ts +++ b/x-pack/plugins/infra/public/utils/use_url_state.ts @@ -105,21 +105,20 @@ const getParamFromQueryString = (queryString: string, key: string) => { return Array.isArray(queryParam) ? queryParam[0] : queryParam; }; -export const replaceStateKeyInQueryString = ( - stateKey: string, - urlState: UrlState | undefined -) => (queryString: string) => { - const previousQueryValues = parse(queryString, { sort: false }); - const newValue = - typeof urlState === 'undefined' - ? previousQueryValues - : { - ...previousQueryValues, - [stateKey]: encodeRisonUrlState(urlState), - }; - - return stringify(url.encodeQuery(newValue), { sort: false, encode: false }); -}; +export const replaceStateKeyInQueryString = + (stateKey: string, urlState: UrlState | undefined) => + (queryString: string) => { + const previousQueryValues = parse(queryString, { sort: false }); + const newValue = + typeof urlState === 'undefined' + ? previousQueryValues + : { + ...previousQueryValues, + [stateKey]: encodeRisonUrlState(urlState), + }; + + return stringify(url.encodeQuery(newValue), { sort: false, encode: false }); + }; const replaceQueryStringInLocation = (location: Location, queryString: string): Location => { if (queryString === getQueryStringFromLocation(location)) { 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 4ad2fa656f9b..ab98de7901a3 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 @@ -268,9 +268,7 @@ const createFilterClauses = ( const createQueryFilterClauses = (filterQuery: LogEntryQuery | undefined) => filterQuery ? [filterQuery] : []; -function processCursor( - cursor: LogEntriesParams['cursor'] -): { +function processCursor(cursor: LogEntriesParams['cursor']): { sortDirection: 'asc' | 'desc'; searchAfterClause: { search_after?: readonly [number, number] }; } { 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 079d39c080bf..0aa305a580ff 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 @@ -76,11 +76,11 @@ export class InfraElasticsearchSourceStatusAdapter implements InfraSourceStatusA } } -const withDefaultIfNotFound = (defaultValue: DefaultValue) => ( - error: any -): DefaultValue => { - if (error && error.status === 404) { - return defaultValue; - } - throw error; -}; +const withDefaultIfNotFound = + (defaultValue: DefaultValue) => + (error: any): DefaultValue => { + if (error && error.status === 404) { + return defaultValue; + } + throw error; + }; 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 ddfc575438fa..bbbb0e917d51 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 @@ -70,13 +70,8 @@ export const createInventoryMetricThresholdExecutor = (libs: InfraBackendLibs) = InventoryMetricThresholdAlertInstanceContext, InventoryMetricThresholdAllowedActionGroups >(async ({ services, params }) => { - const { - criteria, - filterQuery, - sourceId, - nodeType, - alertOnNoData, - } = params as InventoryMetricThresholdParams; + const { criteria, filterQuery, sourceId, nodeType, alertOnNoData } = + params as InventoryMetricThresholdParams; if (criteria.length === 0) throw new Error('Cannot execute an alert with 0 conditions'); const { alertWithLifecycle, savedObjectsClient } = services; const alertInstanceFactory: InventoryMetricThresholdAlertInstanceFactory = (id, reason) => @@ -185,7 +180,7 @@ export const createInventoryMetricThresholdExecutor = (libs: InfraBackendLibs) = * TODO: We're lying to the compiler here as explicitly calling `scheduleActions` on * the RecoveredActionGroup isn't allowed */ - (actionGroupId as unknown) as InventoryMetricThresholdAllowedActionGroups, + actionGroupId as unknown as InventoryMetricThresholdAllowedActionGroups, { group: item, alertState: stateToAlertMessage[nextState], diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_anomaly/metric_anomaly_executor.ts b/x-pack/plugins/infra/server/lib/alerting/metric_anomaly/metric_anomaly_executor.ts index 2282a7ff255d..f7dbe95b4161 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_anomaly/metric_anomaly_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_anomaly/metric_anomaly_executor.ts @@ -25,80 +25,79 @@ import { KibanaRequest } from '../../../../../../../src/core/server'; import { InfraBackendLibs } from '../../infra_types'; import { evaluateCondition } from './evaluate_condition'; -export const createMetricAnomalyExecutor = (libs: InfraBackendLibs, ml?: MlPluginSetup) => async ({ - services, - params, - startedAt, -}: AlertExecutorOptions< - /** - * TODO: Remove this use of `any` by utilizing a proper type - */ - Record, - Record, - AlertInstanceState, - AlertInstanceContext, - MetricAnomalyAllowedActionGroups ->) => { - if (!ml) { - return; - } - const request = {} as KibanaRequest; - const mlSystem = ml.mlSystemProvider(request, services.savedObjectsClient); - const mlAnomalyDetectors = ml.anomalyDetectorsProvider(request, services.savedObjectsClient); +export const createMetricAnomalyExecutor = + (libs: InfraBackendLibs, ml?: MlPluginSetup) => + async ({ + services, + params, + startedAt, + }: AlertExecutorOptions< + /** + * TODO: Remove this use of `any` by utilizing a proper type + */ + Record, + Record, + AlertInstanceState, + AlertInstanceContext, + MetricAnomalyAllowedActionGroups + >) => { + if (!ml) { + return; + } + const request = {} as KibanaRequest; + const mlSystem = ml.mlSystemProvider(request, services.savedObjectsClient); + const mlAnomalyDetectors = ml.anomalyDetectorsProvider(request, services.savedObjectsClient); - const { - metric, - alertInterval, - influencerFilter, - sourceId, - spaceId, - nodeType, - threshold, - } = params as MetricAnomalyParams; + const { metric, alertInterval, influencerFilter, sourceId, spaceId, nodeType, threshold } = + params as MetricAnomalyParams; - const bucketInterval = getIntervalInSeconds('15m') * 1000; - const alertIntervalInMs = getIntervalInSeconds(alertInterval ?? '1m') * 1000; + const bucketInterval = getIntervalInSeconds('15m') * 1000; + const alertIntervalInMs = getIntervalInSeconds(alertInterval ?? '1m') * 1000; - const endTime = startedAt.getTime(); - // Anomalies are bucketed at :00, :15, :30, :45 minutes every hour - const previousBucketStartTime = endTime - (endTime % bucketInterval); + const endTime = startedAt.getTime(); + // Anomalies are bucketed at :00, :15, :30, :45 minutes every hour + const previousBucketStartTime = endTime - (endTime % bucketInterval); - // If the alert interval is less than 15m, make sure that it actually queries an anomaly bucket - const startTime = Math.min(endTime - alertIntervalInMs, previousBucketStartTime); + // If the alert interval is less than 15m, make sure that it actually queries an anomaly bucket + const startTime = Math.min(endTime - alertIntervalInMs, previousBucketStartTime); - const { data } = await evaluateCondition({ - sourceId: sourceId ?? 'default', - spaceId: spaceId ?? 'default', - mlSystem, - mlAnomalyDetectors, - startTime, - endTime, - metric, - threshold, - nodeType, - influencerFilter, - }); + const { data } = await evaluateCondition({ + sourceId: sourceId ?? 'default', + spaceId: spaceId ?? 'default', + mlSystem, + mlAnomalyDetectors, + startTime, + endTime, + metric, + threshold, + nodeType, + influencerFilter, + }); - const shouldAlertFire = data.length > 0; + const shouldAlertFire = data.length > 0; - if (shouldAlertFire) { - const { startTime: anomalyStartTime, anomalyScore, actual, typical, influencers } = first( - data as MappedAnomalyHit[] - )!; - const alertInstance = services.alertInstanceFactory(`${nodeType}-${metric}`); + if (shouldAlertFire) { + const { + startTime: anomalyStartTime, + anomalyScore, + actual, + typical, + influencers, + } = first(data as MappedAnomalyHit[])!; + const alertInstance = services.alertInstanceFactory(`${nodeType}-${metric}`); - alertInstance.scheduleActions(FIRED_ACTIONS_ID, { - alertState: stateToAlertMessage[AlertStates.ALERT], - timestamp: moment(anomalyStartTime).toISOString(), - anomalyScore, - actual, - typical, - metric: metricNameMap[metric], - summary: generateSummaryMessage(actual, typical), - influencers: influencers.join(', '), - }); - } -}; + alertInstance.scheduleActions(FIRED_ACTIONS_ID, { + alertState: stateToAlertMessage[AlertStates.ALERT], + timestamp: moment(anomalyStartTime).toISOString(), + anomalyScore, + actual, + typical, + metric: metricNameMap[metric], + summary: generateSummaryMessage(actual, typical), + influencers: influencers.join(', '), + }); + } + }; export const FIRED_ACTIONS_ID = 'metrics.anomaly.fired'; export const FIRED_ACTIONS: ActionGroup = { diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts index a099b83fdb42..c7c1eb5454d1 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts @@ -195,7 +195,7 @@ const getMetric: ( return { [UNGROUPED_FACTORY_KEY]: getValuesFromAggregations( - (result.aggregations! as unknown) as Aggregation, + result.aggregations! as unknown as Aggregation, aggType, dropPartialBucketsOptions, calculatedTimerange, @@ -225,16 +225,18 @@ interface DropPartialBucketOptions { bucketSizeInMillis: number; } -const dropPartialBuckets = ({ from, to, bucketSizeInMillis }: DropPartialBucketOptions) => ( - row: { - key: string; - value: number | null; - } | null -) => { - if (row == null) return null; - const timestamp = new Date(row.key).valueOf(); - return timestamp >= from && timestamp + bucketSizeInMillis <= to; -}; +const dropPartialBuckets = + ({ from, to, bucketSizeInMillis }: DropPartialBucketOptions) => + ( + row: { + key: string; + value: number | null; + } | null + ) => { + if (row == null) return null; + const timestamp = new Date(row.key).valueOf(); + return timestamp >= from && timestamp + bucketSizeInMillis <= to; + }; const getValuesFromAggregations = ( aggregations: Aggregation | undefined, 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 259318b6c93a..9c99ad6bf49e 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 @@ -207,14 +207,8 @@ const formatAlertResult = ( } & AlertResult, useWarningThreshold?: boolean ) => { - const { - metric, - currentValue, - threshold, - comparator, - warningThreshold, - warningComparator, - } = alertResult; + const { metric, currentValue, threshold, comparator, warningThreshold, warningComparator } = + alertResult; const noDataValue = i18n.translate( 'xpack.infra.metrics.alerting.threshold.noDataFormattedValue', { diff --git a/x-pack/plugins/infra/server/lib/create_search_client.ts b/x-pack/plugins/infra/server/lib/create_search_client.ts index afe16801dd2a..6688ae1af1af 100644 --- a/x-pack/plugins/infra/server/lib/create_search_client.ts +++ b/x-pack/plugins/infra/server/lib/create_search_client.ts @@ -9,10 +9,9 @@ import type { InfraPluginRequestHandlerContext } from '../types'; import { CallWithRequestParams, InfraDatabaseSearchResponse } from './adapters/framework'; import { KibanaFramework } from './adapters/framework/kibana_framework_adapter'; -export const createSearchClient = ( - requestContext: InfraPluginRequestHandlerContext, - framework: KibanaFramework -) => ( - opts: CallWithRequestParams -): Promise> => - framework.callWithRequest(requestContext, 'search', opts); +export const createSearchClient = + (requestContext: InfraPluginRequestHandlerContext, framework: KibanaFramework) => + ( + opts: CallWithRequestParams + ): Promise> => + framework.callWithRequest(requestContext, 'search', opts); 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 f6be310d79ed..16209e5e4b68 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 @@ -166,28 +166,26 @@ export class InfraLogEntriesDomain { id: doc.id, index: doc.index, cursor: doc.cursor, - columns: columnDefinitions.map( - (column): LogColumn => { - if ('timestampColumn' in column) { - return { - columnId: column.timestampColumn.id, - timestamp: doc.cursor.time, - }; - } else if ('messageColumn' in column) { - return { - columnId: column.messageColumn.id, - message: messageFormattingRules.format(doc.fields, doc.highlights), - }; - } else { - return { - columnId: column.fieldColumn.id, - field: column.fieldColumn.field, - value: doc.fields[column.fieldColumn.field] ?? [], - highlights: doc.highlights[column.fieldColumn.field] ?? [], - }; - } + columns: columnDefinitions.map((column): LogColumn => { + if ('timestampColumn' in column) { + return { + columnId: column.timestampColumn.id, + timestamp: doc.cursor.time, + }; + } else if ('messageColumn' in column) { + return { + columnId: column.messageColumn.id, + message: messageFormattingRules.format(doc.fields, doc.highlights), + }; + } else { + return { + columnId: column.fieldColumn.id, + field: column.fieldColumn.field, + value: doc.fields[column.fieldColumn.field] ?? [], + highlights: doc.highlights[column.fieldColumn.field] ?? [], + }; } - ), + }), context: getContextFromDoc(doc), }; }); diff --git a/x-pack/plugins/infra/server/lib/host_details/process_list.ts b/x-pack/plugins/infra/server/lib/host_details/process_list.ts index e51e06af83f9..a9125c73fe5d 100644 --- a/x-pack/plugins/infra/server/lib/host_details/process_list.ts +++ b/x-pack/plugins/infra/server/lib/host_details/process_list.ts @@ -129,8 +129,8 @@ export const getProcessList = async ( let summary: { [p: string]: number } = {}; if (result.aggregations!.summaryEvent.summary.hits.hits.length) { - summary = result.aggregations!.summaryEvent.summary.hits.hits[0]._source.system.process - .summary; + summary = + result.aggregations!.summaryEvent.summary.hits.hits[0]._source.system.process.summary; } return { 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 7739f39cb562..7023f7007763 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 @@ -244,15 +244,14 @@ async function fetchTopLogEntryCategories( const topLogEntryCategories = topLogEntryCategoriesResponse.aggregations?.terms_category_id.buckets.map( (topCategoryBucket) => { - const maximumAnomalyScoresByDataset = topCategoryBucket.filter_record.terms_dataset.buckets.reduce< - Record - >( - (accumulatedMaximumAnomalyScores, datasetFromRecord) => ({ - ...accumulatedMaximumAnomalyScores, - [datasetFromRecord.key]: datasetFromRecord.maximum_record_score.value ?? 0, - }), - {} - ); + const maximumAnomalyScoresByDataset = + topCategoryBucket.filter_record.terms_dataset.buckets.reduce>( + (accumulatedMaximumAnomalyScores, datasetFromRecord) => ({ + ...accumulatedMaximumAnomalyScores, + [datasetFromRecord.key]: datasetFromRecord.maximum_record_score.value ?? 0, + }), + {} + ); return { categoryId: parseCategoryId(topCategoryBucket.key), diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_datasets_stats.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_datasets_stats.ts index 7c92a81e1a89..8c3f73933915 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_datasets_stats.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_datasets_stats.ts @@ -34,16 +34,17 @@ export async function getLatestLogEntriesCategoriesDatasetsStats( let afterLatestBatchKey: CompositeDatasetKey | undefined; while (true) { - const latestLogEntryCategoriesDatasetsStatsResponse = await context.infra.mlSystem.mlAnomalySearch( - createLatestLogEntryCategoriesDatasetsStatsQuery( - jobIds, - startTime, - endTime, - COMPOSITE_AGGREGATION_BATCH_SIZE, - afterLatestBatchKey - ), - jobIds - ); + const latestLogEntryCategoriesDatasetsStatsResponse = + await context.infra.mlSystem.mlAnomalySearch( + createLatestLogEntryCategoriesDatasetsStatsQuery( + jobIds, + startTime, + endTime, + COMPOSITE_AGGREGATION_BATCH_SIZE, + afterLatestBatchKey + ), + jobIds + ); const { after_key: afterKey, buckets: latestBatchBuckets = [] } = decodeOrThrow(latestLogEntryCategoriesDatasetsStatsResponseRT)( diff --git a/x-pack/plugins/infra/server/lib/metrics/lib/convert_histogram_buckets_to_timeseries.ts b/x-pack/plugins/infra/server/lib/metrics/lib/convert_histogram_buckets_to_timeseries.ts index f6761f72fabb..82bd99896839 100644 --- a/x-pack/plugins/infra/server/lib/metrics/lib/convert_histogram_buckets_to_timeseries.ts +++ b/x-pack/plugins/infra/server/lib/metrics/lib/convert_histogram_buckets_to_timeseries.ts @@ -64,9 +64,9 @@ const getValue = (valueObject: ValueObjectType) => { return null; }; -const dropOutOfBoundsBuckets = (from: number, to: number, bucketSizeInMillis: number) => ( - row: MetricsAPIRow -) => row.timestamp >= from && row.timestamp + bucketSizeInMillis <= to; +const dropOutOfBoundsBuckets = + (from: number, to: number, bucketSizeInMillis: number) => (row: MetricsAPIRow) => + row.timestamp >= from && row.timestamp + bucketSizeInMillis <= to; const convertBucketsToRows = ( options: MetricsAPIRequest, diff --git a/x-pack/plugins/infra/server/lib/sources/sources.ts b/x-pack/plugins/infra/server/lib/sources/sources.ts index 7dc47388bd1d..45da4546ad3b 100644 --- a/x-pack/plugins/infra/server/lib/sources/sources.ts +++ b/x-pack/plugins/infra/server/lib/sources/sources.ts @@ -205,11 +205,12 @@ export class InfraSources { } private async getStaticDefaultSourceConfiguration() { - const staticSourceConfiguration: SourceConfigurationConfigFileProperties['sources']['default'] = pipe( - sourceConfigurationConfigFilePropertiesRT.decode(this.libs.config), - map(({ sources: { default: defaultConfiguration } }) => defaultConfiguration), - fold(constant({}), identity) - ); + const staticSourceConfiguration: SourceConfigurationConfigFileProperties['sources']['default'] = + pipe( + sourceConfigurationConfigFilePropertiesRT.decode(this.libs.config), + map(({ sources: { default: defaultConfiguration } }) => defaultConfiguration), + fold(constant({}), identity) + ); // NOTE: Legacy logAlias needs converting to a logIndices reference until we can remove // config file sources in 8.0.0. diff --git a/x-pack/plugins/infra/server/routes/metadata/index.ts b/x-pack/plugins/infra/server/routes/metadata/index.ts index cc8888e9bd09..39021ba51c9d 100644 --- a/x-pack/plugins/infra/server/routes/metadata/index.ts +++ b/x-pack/plugins/infra/server/routes/metadata/index.ts @@ -92,7 +92,9 @@ export const initMetadataRoute = (libs: InfraBackendLibs) => { ); }; -const nameToFeature = (source: string) => (name: string): InfraMetadataFeature => ({ - name, - source, -}); +const nameToFeature = + (source: string) => + (name: string): InfraMetadataFeature => ({ + name, + source, + }); diff --git a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/transform_series.ts b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/transform_series.ts index 3de020c2ad32..6b876887bd56 100644 --- a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/transform_series.ts +++ b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/transform_series.ts @@ -7,19 +7,21 @@ import { MetricsAPISeries, MetricsExplorerSeries } from '../../../../common/http_api'; -export const transformSeries = (hasGroupBy: boolean) => ( - series: MetricsAPISeries -): MetricsExplorerSeries => { - const id = series.keys?.join(' / ') ?? series.id; - return { - ...series, - id, - rows: series.rows.map((row) => { - if (hasGroupBy) { - return { ...row, groupBy: id }; - } - return row; - }), - columns: hasGroupBy ? [...series.columns, { name: 'groupBy', type: 'string' }] : series.columns, +export const transformSeries = + (hasGroupBy: boolean) => + (series: MetricsAPISeries): MetricsExplorerSeries => { + const id = series.keys?.join(' / ') ?? series.id; + return { + ...series, + id, + rows: series.rows.map((row) => { + if (hasGroupBy) { + return { ...row, groupBy: id }; + } + return row; + }), + columns: hasGroupBy + ? [...series.columns, { name: 'groupBy', type: 'string' }] + : series.columns, + }; }; -}; diff --git a/x-pack/plugins/infra/server/routes/snapshot/lib/query_all_data.ts b/x-pack/plugins/infra/server/routes/snapshot/lib/query_all_data.ts index ff0e9b6ce57f..b92fbab90af9 100644 --- a/x-pack/plugins/infra/server/routes/snapshot/lib/query_all_data.ts +++ b/x-pack/plugins/infra/server/routes/snapshot/lib/query_all_data.ts @@ -9,25 +9,23 @@ import { MetricsAPIRequest, MetricsAPIResponse } from '../../../../common/http_a import { ESSearchClient } from '../../../lib/metrics/types'; import { query } from '../../../lib/metrics'; -const handleResponse = ( - client: ESSearchClient, - options: MetricsAPIRequest, - previousResponse?: MetricsAPIResponse -) => async (resp: MetricsAPIResponse): Promise => { - const combinedResponse = previousResponse - ? { - ...previousResponse, - series: [...previousResponse.series, ...resp.series], - info: resp.info, - } - : resp; - if (resp.info.afterKey) { - return query(client, { ...options, afterKey: resp.info.afterKey }).then( - handleResponse(client, options, combinedResponse) - ); - } - return combinedResponse; -}; +const handleResponse = + (client: ESSearchClient, options: MetricsAPIRequest, previousResponse?: MetricsAPIResponse) => + async (resp: MetricsAPIResponse): Promise => { + const combinedResponse = previousResponse + ? { + ...previousResponse, + series: [...previousResponse.series, ...resp.series], + info: resp.info, + } + : resp; + if (resp.info.afterKey) { + return query(client, { ...options, afterKey: resp.info.afterKey }).then( + handleResponse(client, options, combinedResponse) + ); + } + return combinedResponse; + }; export const queryAllData = (client: ESSearchClient, options: MetricsAPIRequest) => { return query(client, options).then(handleResponse(client, options)); diff --git a/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.ts b/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.ts index c47a1c163f9e..651758d9cd97 100644 --- a/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.ts +++ b/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.ts @@ -197,17 +197,18 @@ const { asyncInitialRequestRT, asyncRecoveredRequestRT, asyncRequestRT } = creat logEntriesSearchRequestParamsRT ); -const getLogEntryFromHit = ( - columnDefinitions: LogSourceColumnConfiguration[], - messageFormattingRules: CompiledLogMessageFormattingRule -) => (hit: LogEntryHit): LogEntry => { - const cursor = getLogEntryCursorFromHit(hit); - return { - id: hit._id, - index: hit._index, - cursor, - columns: columnDefinitions.map( - (column): LogColumn => { +const getLogEntryFromHit = + ( + columnDefinitions: LogSourceColumnConfiguration[], + messageFormattingRules: CompiledLogMessageFormattingRule + ) => + (hit: LogEntryHit): LogEntry => { + const cursor = getLogEntryCursorFromHit(hit); + return { + id: hit._id, + index: hit._index, + cursor, + columns: columnDefinitions.map((column): LogColumn => { if ('timestampColumn' in column) { return { columnId: column.timestampColumn.id, @@ -226,11 +227,10 @@ const getLogEntryFromHit = ( highlights: hit.highlight?.[column.fieldColumn.field] ?? [], }; } - } - ), - context: getContextFromHit(hit), + }), + context: getContextFromHit(hit), + }; }; -}; const pickRequestCursor = ( params: LogEntriesSearchRequestParams diff --git a/x-pack/plugins/infra/server/utils/create_afterkey_handler.ts b/x-pack/plugins/infra/server/utils/create_afterkey_handler.ts index 0c320c7b8ec1..6d41f17a6bb5 100644 --- a/x-pack/plugins/infra/server/utils/create_afterkey_handler.ts +++ b/x-pack/plugins/infra/server/utils/create_afterkey_handler.ts @@ -8,18 +8,20 @@ import { set } from '@elastic/safer-lodash-set'; import { InfraDatabaseSearchResponse } from '../lib/adapters/framework'; -export const createAfterKeyHandler = ( - optionsAfterKeyPath: string | string[], - afterKeySelector: (input: InfraDatabaseSearchResponse) => any -) => ( - options: Options, - response: InfraDatabaseSearchResponse -): Options => { - if (!response.aggregations) { - return options; - } - const newOptions = { ...options }; - const afterKey = afterKeySelector(response); - set(newOptions, optionsAfterKeyPath, afterKey); - return newOptions; -}; +export const createAfterKeyHandler = + ( + optionsAfterKeyPath: string | string[], + afterKeySelector: (input: InfraDatabaseSearchResponse) => any + ) => + ( + options: Options, + response: InfraDatabaseSearchResponse + ): Options => { + if (!response.aggregations) { + return options; + } + const newOptions = { ...options }; + const afterKey = afterKeySelector(response); + set(newOptions, optionsAfterKeyPath, afterKey); + return newOptions; + }; diff --git a/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/setup_environment.tsx index abd8efb730ef..7ba5e44cddf6 100644 --- a/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/setup_environment.tsx +++ b/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/setup_environment.tsx @@ -52,7 +52,7 @@ const appServices = { export const setupEnvironment = () => { uiMetricService.setup(usageCollectionPluginMock.createSetupContract()); - apiService.setup((mockHttpClient as unknown) as HttpSetup, uiMetricService); + apiService.setup(mockHttpClient as unknown as HttpSetup, uiMetricService); documentationService.setup(docLinksServiceMock.createStartContract()); breadcrumbService.setup(() => {}); @@ -64,8 +64,9 @@ export const setupEnvironment = () => { }; }; -export const WithAppDependencies = (Comp: any) => (props: any) => ( - - - -); +export const WithAppDependencies = (Comp: any) => (props: any) => + ( + + + + ); diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/__jest__/pipeline_processors_editor.test.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/__jest__/pipeline_processors_editor.test.tsx index 5b02927ab873..c5daa1db2ac0 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/__jest__/pipeline_processors_editor.test.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/__jest__/pipeline_processors_editor.test.tsx @@ -297,21 +297,25 @@ describe('Pipeline Editor', () => { none: 'No description', }; - const createAssertForProcessor = (processorIndex: string) => ({ - description, - descriptionVisible, - }: { - description: string; - descriptionVisible: boolean; - }) => { - expect(find(`processors>${processorIndex}.inlineTextInputNonEditableText`).text()).toBe( - description - ); - expect( - (find(`processors>${processorIndex}.pipelineProcessorItemDescriptionContainer`).props() - .className as string).includes('--displayNone') - ).toBe(!descriptionVisible); - }; + const createAssertForProcessor = + (processorIndex: string) => + ({ + description, + descriptionVisible, + }: { + description: string; + descriptionVisible: boolean; + }) => { + expect(find(`processors>${processorIndex}.inlineTextInputNonEditableText`).text()).toBe( + description + ); + expect( + ( + find(`processors>${processorIndex}.pipelineProcessorItemDescriptionContainer`).props() + .className as string + ).includes('--displayNone') + ).toBe(!descriptionVisible); + }; const assertScriptProcessor = createAssertForProcessor('0'); const assertSetProcessor = createAssertForProcessor('2'); diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/field_components/drag_and_drop_text_list.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/field_components/drag_and_drop_text_list.tsx index 03bdc2ceb957..7a0ea533b0d6 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/field_components/drag_and_drop_text_list.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/field_components/drag_and_drop_text_list.tsx @@ -152,9 +152,8 @@ function DragAndDropTextListComponent({ readDefaultValueOnForm={!item.isNew} > {(field) => { - const { isInvalid, errorMessage } = getFieldValidityAndErrorMessage( - field - ); + const { isInvalid, errorMessage } = + getFieldValidityAndErrorMessage(field); return ( diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/network_direction.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/network_direction.tsx index 22f2226d80b1..ab8744ee01ab 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/network_direction.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/network_direction.tsx @@ -86,9 +86,7 @@ const fieldsConfig: FieldsConfig = { }, }; -const getInternalNetworkConfig: ( - toggleCustom: () => void -) => Record< +const getInternalNetworkConfig: (toggleCustom: () => void) => Record< keyof InternalNetworkFields, { path: string; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/set.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/set.tsx index 16d89fcbfb11..6bbda366826f 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/set.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/set.tsx @@ -97,9 +97,7 @@ const fieldsConfig: FieldsConfig = { }; // Required fields config -const getValueConfig: ( - toggleCustom: () => void -) => Record< +const getValueConfig: (toggleCustom: () => void) => Record< keyof ValueToggleFields, { path: string; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/shared.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/shared.ts index 9a45f7f0017c..a14944a33a8c 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/shared.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/shared.ts @@ -81,7 +81,7 @@ export const from = { return undefined; }, optionalArrayOfStrings: (v: string[]) => (v.length ? v : undefined), - undefinedIfValue: (value: unknown) => (v: boolean) => (v === value ? undefined : v), + undefinedIfValue: (value: unknown) => (v: boolean) => v === value ? undefined : v, emptyStringToUndefined: (v: unknown) => (v === '' ? undefined : v), /** * Useful when serializing user input from a