diff --git a/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.md b/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.md index 7be45c6c173b45..706408f81f02a8 100644 --- a/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.md +++ b/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.md @@ -30,7 +30,7 @@ export interface SavedObjectsFindOptions | [searchAfter](./kibana-plugin-core-public.savedobjectsfindoptions.searchafter.md) | estypes.Id[] | Use the sort values from the previous page to retrieve the next page of results. | | [searchFields](./kibana-plugin-core-public.savedobjectsfindoptions.searchfields.md) | string[] | The fields to perform the parsed query against. See Elasticsearch Simple Query String fields argument for more information | | [sortField](./kibana-plugin-core-public.savedobjectsfindoptions.sortfield.md) | string | | -| [sortOrder](./kibana-plugin-core-public.savedobjectsfindoptions.sortorder.md) | estypes.SortOrder | | +| [sortOrder](./kibana-plugin-core-public.savedobjectsfindoptions.sortorder.md) | estypes.SearchSortOrder | | | [type](./kibana-plugin-core-public.savedobjectsfindoptions.type.md) | string | string[] | | | [typeToNamespacesMap](./kibana-plugin-core-public.savedobjectsfindoptions.typetonamespacesmap.md) | Map<string, string[] | undefined> | This map defines each type to search for, and the namespace(s) to search for the type in; this is only intended to be used by a saved object client wrapper. If this is defined, it supersedes the type and namespaces fields when building the Elasticsearch query. Any types that are not included in this map will be excluded entirely. If a type is included but its value is undefined, the operation will search for that type in the Default namespace. | diff --git a/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.sortorder.md b/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.sortorder.md index 36f99e51ea8c65..506fb9041e353b 100644 --- a/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.sortorder.md +++ b/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.sortorder.md @@ -7,5 +7,5 @@ Signature: ```typescript -sortOrder?: estypes.SortOrder; +sortOrder?: estypes.SearchSortOrder; ``` diff --git a/docs/development/core/server/kibana-plugin-core-server.md b/docs/development/core/server/kibana-plugin-core-server.md index 32a2f3312708ce..604cdea1a7fbe6 100644 --- a/docs/development/core/server/kibana-plugin-core-server.md +++ b/docs/development/core/server/kibana-plugin-core-server.md @@ -159,8 +159,6 @@ The plugin integrates with the core system via lifecycle events: `setup` | [SavedObjectsCollectMultiNamespaceReferencesObject](./kibana-plugin-core-server.savedobjectscollectmultinamespacereferencesobject.md) | An object to collect references for. It must be a multi-namespace type (in other words, the object type must be registered with the namespaceType: 'multiple' or namespaceType: 'multiple-isolated' option).Note: if options.purpose is 'updateObjectsSpaces', it must be a shareable type (in other words, the object type must be registered with the namespaceType: 'multiple'). | | [SavedObjectsCollectMultiNamespaceReferencesOptions](./kibana-plugin-core-server.savedobjectscollectmultinamespacereferencesoptions.md) | Options for collecting references. | | [SavedObjectsCollectMultiNamespaceReferencesResponse](./kibana-plugin-core-server.savedobjectscollectmultinamespacereferencesresponse.md) | The response when object references are collected. | -| [SavedObjectsComplexFieldMapping](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.md) | See [SavedObjectsFieldMapping](./kibana-plugin-core-server.savedobjectsfieldmapping.md) for documentation. | -| [SavedObjectsCoreFieldMapping](./kibana-plugin-core-server.savedobjectscorefieldmapping.md) | See [SavedObjectsFieldMapping](./kibana-plugin-core-server.savedobjectsfieldmapping.md) for documentation. | | [SavedObjectsCreateOptions](./kibana-plugin-core-server.savedobjectscreateoptions.md) | | | [SavedObjectsCreatePointInTimeFinderDependencies](./kibana-plugin-core-server.savedobjectscreatepointintimefinderdependencies.md) | | | [SavedObjectsDeleteByNamespaceOptions](./kibana-plugin-core-server.savedobjectsdeletebynamespaceoptions.md) | | diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.doc_values.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.doc_values.md deleted file mode 100644 index 3f2d81cc97c7c8..00000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.doc_values.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsComplexFieldMapping](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.md) > [doc\_values](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.doc_values.md) - -## SavedObjectsComplexFieldMapping.doc\_values property - -Signature: - -```typescript -doc_values?: boolean; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.dynamic.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.dynamic.md deleted file mode 100644 index b01da3c62fda67..00000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.dynamic.md +++ /dev/null @@ -1,15 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsComplexFieldMapping](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.md) > [dynamic](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.dynamic.md) - -## SavedObjectsComplexFieldMapping.dynamic property - -The dynamic property of the mapping, either `false` or `'strict'`. If unspecified `dynamic: 'strict'` will be inherited from the top-level index mappings. - -Note: To limit the number of mapping fields Saved Object types should \*never\* use `dynamic: true`. - -Signature: - -```typescript -dynamic?: false | 'strict'; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.enabled.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.enabled.md deleted file mode 100644 index 08513aa2a849b7..00000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.enabled.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsComplexFieldMapping](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.md) > [enabled](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.enabled.md) - -## SavedObjectsComplexFieldMapping.enabled property - -Signature: - -```typescript -enabled?: boolean; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.md deleted file mode 100644 index fc262cad54f183..00000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.md +++ /dev/null @@ -1,24 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsComplexFieldMapping](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.md) - -## SavedObjectsComplexFieldMapping interface - -See [SavedObjectsFieldMapping](./kibana-plugin-core-server.savedobjectsfieldmapping.md) for documentation. - -Signature: - -```typescript -export interface SavedObjectsComplexFieldMapping -``` - -## Properties - -| Property | Type | Description | -| --- | --- | --- | -| [doc\_values](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.doc_values.md) | boolean | | -| [dynamic](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.dynamic.md) | false | 'strict' | The dynamic property of the mapping, either false or 'strict'. If unspecified dynamic: 'strict' will be inherited from the top-level index mappings.Note: To limit the number of mapping fields Saved Object types should \*never\* use dynamic: true. | -| [enabled](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.enabled.md) | boolean | | -| [properties](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.properties.md) | SavedObjectsMappingProperties | | -| [type](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.type.md) | string | | - diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.properties.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.properties.md deleted file mode 100644 index 613a36a09ba1ed..00000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.properties.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsComplexFieldMapping](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.md) > [properties](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.properties.md) - -## SavedObjectsComplexFieldMapping.properties property - -Signature: - -```typescript -properties: SavedObjectsMappingProperties; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.type.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.type.md deleted file mode 100644 index 8aaa524dad43a9..00000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.type.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsComplexFieldMapping](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.md) > [type](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.type.md) - -## SavedObjectsComplexFieldMapping.type property - -Signature: - -```typescript -type?: string; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.doc_values.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.doc_values.md deleted file mode 100644 index 2a79eafd85a6c2..00000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.doc_values.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsCoreFieldMapping](./kibana-plugin-core-server.savedobjectscorefieldmapping.md) > [doc\_values](./kibana-plugin-core-server.savedobjectscorefieldmapping.doc_values.md) - -## SavedObjectsCoreFieldMapping.doc\_values property - -Signature: - -```typescript -doc_values?: boolean; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.fields.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.fields.md deleted file mode 100644 index 4f88b635ca2f7c..00000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.fields.md +++ /dev/null @@ -1,16 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsCoreFieldMapping](./kibana-plugin-core-server.savedobjectscorefieldmapping.md) > [fields](./kibana-plugin-core-server.savedobjectscorefieldmapping.fields.md) - -## SavedObjectsCoreFieldMapping.fields property - -Signature: - -```typescript -fields?: { - [subfield: string]: { - type: string; - ignore_above?: number; - }; - }; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.index.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.index.md deleted file mode 100644 index e3cf685e310d27..00000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.index.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsCoreFieldMapping](./kibana-plugin-core-server.savedobjectscorefieldmapping.md) > [index](./kibana-plugin-core-server.savedobjectscorefieldmapping.index.md) - -## SavedObjectsCoreFieldMapping.index property - -Signature: - -```typescript -index?: boolean; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.md deleted file mode 100644 index e9b9c2bcf51b55..00000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.md +++ /dev/null @@ -1,24 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsCoreFieldMapping](./kibana-plugin-core-server.savedobjectscorefieldmapping.md) - -## SavedObjectsCoreFieldMapping interface - -See [SavedObjectsFieldMapping](./kibana-plugin-core-server.savedobjectsfieldmapping.md) for documentation. - -Signature: - -```typescript -export interface SavedObjectsCoreFieldMapping -``` - -## Properties - -| Property | Type | Description | -| --- | --- | --- | -| [doc\_values](./kibana-plugin-core-server.savedobjectscorefieldmapping.doc_values.md) | boolean | | -| [fields](./kibana-plugin-core-server.savedobjectscorefieldmapping.fields.md) | {
[subfield: string]: {
type: string;
ignore_above?: number;
};
} | | -| [index](./kibana-plugin-core-server.savedobjectscorefieldmapping.index.md) | boolean | | -| [null\_value](./kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md) | number | boolean | string | | -| [type](./kibana-plugin-core-server.savedobjectscorefieldmapping.type.md) | string | | - diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md deleted file mode 100644 index 627ea3695383a0..00000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsCoreFieldMapping](./kibana-plugin-core-server.savedobjectscorefieldmapping.md) > [null\_value](./kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md) - -## SavedObjectsCoreFieldMapping.null\_value property - -Signature: - -```typescript -null_value?: number | boolean | string; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.type.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.type.md deleted file mode 100644 index 94d395d7983e57..00000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.type.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsCoreFieldMapping](./kibana-plugin-core-server.savedobjectscorefieldmapping.md) > [type](./kibana-plugin-core-server.savedobjectscorefieldmapping.type.md) - -## SavedObjectsCoreFieldMapping.type property - -Signature: - -```typescript -type: string; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsfieldmapping.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfieldmapping.md index 925ca4be92e663..85b52bacafa252 100644 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectsfieldmapping.md +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfieldmapping.md @@ -11,5 +11,7 @@ Please refer to [elasticsearch documentation](https://www.elastic.co/guide/en/el Signature: ```typescript -export declare type SavedObjectsFieldMapping = SavedObjectsCoreFieldMapping | SavedObjectsComplexFieldMapping; +export declare type SavedObjectsFieldMapping = estypes.MappingProperty & { + dynamic?: false | 'strict'; +}; ``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.md index a92b1f48d08ebc..d3696ee71049a2 100644 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.md +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.md @@ -30,7 +30,7 @@ export interface SavedObjectsFindOptions | [searchAfter](./kibana-plugin-core-server.savedobjectsfindoptions.searchafter.md) | estypes.Id[] | Use the sort values from the previous page to retrieve the next page of results. | | [searchFields](./kibana-plugin-core-server.savedobjectsfindoptions.searchfields.md) | string[] | The fields to perform the parsed query against. See Elasticsearch Simple Query String fields argument for more information | | [sortField](./kibana-plugin-core-server.savedobjectsfindoptions.sortfield.md) | string | | -| [sortOrder](./kibana-plugin-core-server.savedobjectsfindoptions.sortorder.md) | estypes.SortOrder | | +| [sortOrder](./kibana-plugin-core-server.savedobjectsfindoptions.sortorder.md) | estypes.SearchSortOrder | | | [type](./kibana-plugin-core-server.savedobjectsfindoptions.type.md) | string | string[] | | | [typeToNamespacesMap](./kibana-plugin-core-server.savedobjectsfindoptions.typetonamespacesmap.md) | Map<string, string[] | undefined> | This map defines each type to search for, and the namespace(s) to search for the type in; this is only intended to be used by a saved object client wrapper. If this is defined, it supersedes the type and namespaces fields when building the Elasticsearch query. Any types that are not included in this map will be excluded entirely. If a type is included but its value is undefined, the operation will search for that type in the Default namespace. | diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.sortorder.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.sortorder.md index e1c657e3a5171f..dca5a7d8c75836 100644 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.sortorder.md +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.sortorder.md @@ -7,5 +7,5 @@ Signature: ```typescript -sortOrder?: estypes.SortOrder; +sortOrder?: estypes.SearchSortOrder; ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.lang.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.lang.md index a994fc458cfb6f..f99e7ba8b967ec 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.lang.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.lang.md @@ -7,5 +7,5 @@ Signature: ```typescript -lang?: string; +lang?: estypes.ScriptLanguage; ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.md index 4e3dea5549b566..29377ff8fd392a 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.md @@ -26,7 +26,7 @@ export interface IFieldType | [esTypes](./kibana-plugin-plugins-data-public.ifieldtype.estypes.md) | string[] | | | [filterable](./kibana-plugin-plugins-data-public.ifieldtype.filterable.md) | boolean | | | [format](./kibana-plugin-plugins-data-public.ifieldtype.format.md) | any | | -| [lang](./kibana-plugin-plugins-data-public.ifieldtype.lang.md) | string | | +| [lang](./kibana-plugin-plugins-data-public.ifieldtype.lang.md) | estypes.ScriptLanguage | | | [name](./kibana-plugin-plugins-data-public.ifieldtype.name.md) | string | | | [readFromDocValues](./kibana-plugin-plugins-data-public.ifieldtype.readfromdocvalues.md) | boolean | | | [script](./kibana-plugin-plugins-data-public.ifieldtype.script.md) | string | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.addscriptedfield.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.addscriptedfield.md index 812f014b15a6c9..e0ee1f0ec15a4c 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.addscriptedfield.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.addscriptedfield.md @@ -6,6 +6,7 @@ > Warning: This API is now obsolete. > +> use runtime field instead > Add scripted field to field list diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.getnonscriptedfields.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.getnonscriptedfields.md index 1792a979bf7490..94adbefe535dd3 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.getnonscriptedfields.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.getnonscriptedfields.md @@ -6,6 +6,7 @@ > Warning: This API is now obsolete. > +> use runtime field instead > Signature: diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.getscriptedfields.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.getscriptedfields.md index b6b3dcb19bac17..57e1b5f49371bf 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.getscriptedfields.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.getscriptedfields.md @@ -6,6 +6,7 @@ > Warning: This API is now obsolete. > +> use runtime field instead > Signature: diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.removescriptedfield.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.removescriptedfield.md index 91f25c09ab197a..d3e1b26810fd74 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.removescriptedfield.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.removescriptedfield.md @@ -6,6 +6,7 @@ > Warning: This API is now obsolete. > +> use runtime field instead > Remove scripted field from field list diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.lang.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.lang.md index b81218eb088866..3666e503e27227 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.lang.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.lang.md @@ -9,7 +9,7 @@ Script field language Signature: ```typescript -get lang(): string | undefined; +get lang(): "painless" | "expression" | "mustache" | "java" | undefined; -set lang(lang: string | undefined); +set lang(lang: "painless" | "expression" | "mustache" | "java" | undefined); ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.md index 05c807b1cd8457..8cd1a476cf32f8 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.md @@ -28,7 +28,7 @@ export declare class IndexPatternField implements IFieldType | [esTypes](./kibana-plugin-plugins-data-public.indexpatternfield.estypes.md) | | string[] | undefined | | | [filterable](./kibana-plugin-plugins-data-public.indexpatternfield.filterable.md) | | boolean | | | [isMapped](./kibana-plugin-plugins-data-public.indexpatternfield.ismapped.md) | | boolean | undefined | Is the field part of the index mapping? | -| [lang](./kibana-plugin-plugins-data-public.indexpatternfield.lang.md) | | string | undefined | Script field language | +| [lang](./kibana-plugin-plugins-data-public.indexpatternfield.lang.md) | | "painless" | "expression" | "mustache" | "java" | undefined | Script field language | | [name](./kibana-plugin-plugins-data-public.indexpatternfield.name.md) | | string | | | [readFromDocValues](./kibana-plugin-plugins-data-public.indexpatternfield.readfromdocvalues.md) | | boolean | | | [runtimeField](./kibana-plugin-plugins-data-public.indexpatternfield.runtimefield.md) | | RuntimeField | undefined | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.tojson.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.tojson.md index f0600dd20658a8..8882fa05ce0c25 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.tojson.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.tojson.md @@ -10,7 +10,7 @@ toJSON(): { count: number; script: string | undefined; - lang: string | undefined; + lang: "painless" | "expression" | "mustache" | "java" | undefined; conflictDescriptions: Record | undefined; name: string; type: string; @@ -28,7 +28,7 @@ toJSON(): { `{ count: number; script: string | undefined; - lang: string | undefined; + lang: "painless" | "expression" | "mustache" | "java" | undefined; conflictDescriptions: Record | undefined; name: string; type: string; diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.phrasefilter.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.phrasefilter.md index 090b78a7078cc5..8d0447d58634c9 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.phrasefilter.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.phrasefilter.md @@ -12,7 +12,7 @@ export declare type PhraseFilter = Filter & { script?: { script: { source?: any; - lang?: string; + lang?: estypes.ScriptLanguage; params: any; }; }; diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.rangefilter.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.rangefilter.md index fbe04f5e0a2a94..1cb627ec3a8f93 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.rangefilter.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.rangefilter.md @@ -12,7 +12,7 @@ export declare type RangeFilter = Filter & EsRangeFilter & { script?: { script: { params: any; - lang: string; + lang: estypes.ScriptLanguage; source: any; }; }; diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.lang.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.lang.md index 095142cf0f05b1..757d8f34a0c3ab 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.lang.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.lang.md @@ -7,5 +7,5 @@ Signature: ```typescript -lang?: string; +lang?: estypes.ScriptLanguage; ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.md index a1a76f2d2a295e..fb39333cf245e0 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.md @@ -15,7 +15,7 @@ export interface Reason | Property | Type | Description | | --- | --- | --- | | [caused\_by](./kibana-plugin-plugins-data-public.reason.caused_by.md) | {
type: string;
reason: string;
} | | -| [lang](./kibana-plugin-plugins-data-public.reason.lang.md) | string | | +| [lang](./kibana-plugin-plugins-data-public.reason.lang.md) | estypes.ScriptLanguage | | | [position](./kibana-plugin-plugins-data-public.reason.position.md) | {
offset: number;
start: number;
end: number;
} | | | [reason](./kibana-plugin-plugins-data-public.reason.reason.md) | string | | | [script\_stack](./kibana-plugin-plugins-data-public.reason.script_stack.md) | string[] | | diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.lang.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.lang.md index d033804cb6fcbb..3d5a757cb8f187 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.lang.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.lang.md @@ -7,5 +7,5 @@ Signature: ```typescript -lang?: string; +lang?: estypes.ScriptLanguage; ``` diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.md index 5ac48d26a85d6d..bbc4cc2135d406 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.md @@ -26,7 +26,7 @@ export interface IFieldType | [esTypes](./kibana-plugin-plugins-data-server.ifieldtype.estypes.md) | string[] | | | [filterable](./kibana-plugin-plugins-data-server.ifieldtype.filterable.md) | boolean | | | [format](./kibana-plugin-plugins-data-server.ifieldtype.format.md) | any | | -| [lang](./kibana-plugin-plugins-data-server.ifieldtype.lang.md) | string | | +| [lang](./kibana-plugin-plugins-data-server.ifieldtype.lang.md) | estypes.ScriptLanguage | | | [name](./kibana-plugin-plugins-data-server.ifieldtype.name.md) | string | | | [readFromDocValues](./kibana-plugin-plugins-data-server.ifieldtype.readfromdocvalues.md) | boolean | | | [script](./kibana-plugin-plugins-data-server.ifieldtype.script.md) | string | | diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md index 981f28a51ae09d..33f1ac5e316605 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md @@ -6,6 +6,7 @@ > Warning: This API is now obsolete. > +> use runtime field instead > Add scripted field to field list diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getnonscriptedfields.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getnonscriptedfields.md index cff2c5de98de61..e791dfc7c3738f 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getnonscriptedfields.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getnonscriptedfields.md @@ -6,6 +6,7 @@ > Warning: This API is now obsolete. > +> use runtime field instead > Signature: diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getscriptedfields.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getscriptedfields.md index 62b8f1b62ac787..95f9f31309674c 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getscriptedfields.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getscriptedfields.md @@ -6,6 +6,7 @@ > Warning: This API is now obsolete. > +> use runtime field instead > Signature: diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.removescriptedfield.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.removescriptedfield.md index f6beed7389e438..b351eba2ace4f6 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.removescriptedfield.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.removescriptedfield.md @@ -6,6 +6,7 @@ > Warning: This API is now obsolete. > +> use runtime field instead > Remove scripted field from field list diff --git a/examples/search_examples/public/search_sessions/app.tsx b/examples/search_examples/public/search_sessions/app.tsx index a768600db24eea..7fdf91537c977c 100644 --- a/examples/search_examples/public/search_sessions/app.tsx +++ b/examples/search_examples/public/search_sessions/app.tsx @@ -702,7 +702,7 @@ function doSearch( const startTs = performance.now(); // Submit the search request using the `data.search` service. - // @ts-expect-error request.params is incompatible. Filter is not assignable to QueryContainer + // @ts-expect-error request.params is incompatible. Filter is not assignable to QueryDslQueryContainer return data.search .search(req, { sessionId }) .pipe( diff --git a/package.json b/package.json index 4614e9293e633a..7d4d96e8407529 100644 --- a/package.json +++ b/package.json @@ -101,7 +101,7 @@ "@elastic/apm-rum-react": "^1.2.5", "@elastic/charts": "30.0.0", "@elastic/datemath": "link:bazel-bin/packages/elastic-datemath", - "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.4", + "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.13", "@elastic/ems-client": "7.13.0", "@elastic/eui": "33.0.0", "@elastic/filesaver": "1.1.2", diff --git a/packages/kbn-es-archiver/src/lib/indices/create_index_stream.ts b/packages/kbn-es-archiver/src/lib/indices/create_index_stream.ts index b45a8b18a5776a..fba3df24e896f8 100644 --- a/packages/kbn-es-archiver/src/lib/indices/create_index_stream.ts +++ b/packages/kbn-es-archiver/src/lib/indices/create_index_stream.ts @@ -19,7 +19,7 @@ import { deleteIndex } from './delete_index'; import { ES_CLIENT_HEADERS } from '../../client_headers'; interface DocRecord { - value: estypes.IndexState & { + value: estypes.IndicesIndexState & { index: string; type: string; }; diff --git a/packages/kbn-es-archiver/src/lib/indices/delete_index.ts b/packages/kbn-es-archiver/src/lib/indices/delete_index.ts index 2a42d52e2ca80b..d3d6f85d7a360b 100644 --- a/packages/kbn-es-archiver/src/lib/indices/delete_index.ts +++ b/packages/kbn-es-archiver/src/lib/indices/delete_index.ts @@ -126,7 +126,7 @@ export async function waitForSnapshotCompletion( const { body: repositoryMap } = await client.snapshot.getRepository({} as any); for (const repository of Object.keys(repositoryMap)) { const allInProgress = await getInProgressSnapshots(repository); - const found = allInProgress.find((s: any) => s.indices.includes(index)); + const found = allInProgress?.find((s: any) => s.indices.includes(index)); if (!found) { continue; diff --git a/packages/kbn-es-archiver/src/lib/indices/kibana_index.ts b/packages/kbn-es-archiver/src/lib/indices/kibana_index.ts index 51d4f28d20f2e0..0712d2789a91ae 100644 --- a/packages/kbn-es-archiver/src/lib/indices/kibana_index.ts +++ b/packages/kbn-es-archiver/src/lib/indices/kibana_index.ts @@ -35,7 +35,7 @@ export async function deleteKibanaIndices({ await client.indices.putSettings( { index: indexNames, - body: { index: { blocks: { read_only: false } } }, + body: { settings: { blocks: { read_only: false } } }, }, { headers: ES_CLIENT_HEADERS, diff --git a/src/core/public/public.api.md b/src/core/public/public.api.md index 608af520540406..235110aeb4633c 100644 --- a/src/core/public/public.api.md +++ b/src/core/public/public.api.md @@ -1255,7 +1255,7 @@ export interface SavedObjectsCreateOptions { // @public (undocumented) export interface SavedObjectsFindOptions { // @alpha - aggs?: Record; + aggs?: Record; defaultSearchOperator?: 'AND' | 'OR'; fields?: string[]; // Warning: (ae-forgotten-export) The symbol "KueryNode" needs to be exported by the entry point index.d.ts @@ -1281,7 +1281,7 @@ export interface SavedObjectsFindOptions { // (undocumented) sortField?: string; // (undocumented) - sortOrder?: estypes.SortOrder; + sortOrder?: estypes.SearchSortOrder; // (undocumented) type: string | string[]; typeToNamespacesMap?: Map; diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.ts index 43cd52f1b57211..e1f18f8ad836ad 100644 --- a/src/core/server/elasticsearch/version_check/ensure_es_version.ts +++ b/src/core/server/elasticsearch/version_check/ensure_es_version.ts @@ -31,7 +31,7 @@ export interface PollEsNodesVersionOptions { interface NodeInfo { version: string; ip: string; - http: { + http?: { publish_address: string; }; name: string; diff --git a/src/core/server/http/integration_tests/core_services.test.ts b/src/core/server/http/integration_tests/core_services.test.ts index 5433f0d3c3e31c..99b63fc73687a1 100644 --- a/src/core/server/http/integration_tests/core_services.test.ts +++ b/src/core/server/http/integration_tests/core_services.test.ts @@ -405,7 +405,7 @@ describe('http service', () => { const { body } = await kbnTestServer.request.get(root, '/new-platform/').expect(400); - expect(body.message).toEqual('[error_type]: error_reason'); + expect(body.message).toMatch('[error_type]: error_reason'); }); }); }); diff --git a/src/core/server/index.ts b/src/core/server/index.ts index 2e495657d34104..ef1ee69ff529b5 100644 --- a/src/core/server/index.ts +++ b/src/core/server/index.ts @@ -339,8 +339,6 @@ export type { SavedObjectsDeleteByNamespaceOptions, SavedObjectsIncrementCounterOptions, SavedObjectsIncrementCounterField, - SavedObjectsComplexFieldMapping, - SavedObjectsCoreFieldMapping, SavedObjectsFieldMapping, SavedObjectsTypeMappingDefinition, SavedObjectsMappingProperties, diff --git a/src/core/server/saved_objects/index.ts b/src/core/server/saved_objects/index.ts index 2af25e0cdef3f2..b1b1584d7de88c 100644 --- a/src/core/server/saved_objects/index.ts +++ b/src/core/server/saved_objects/index.ts @@ -72,8 +72,6 @@ export type { } from './service/lib/repository'; export type { - SavedObjectsCoreFieldMapping, - SavedObjectsComplexFieldMapping, SavedObjectsFieldMapping, SavedObjectsMappingProperties, SavedObjectsTypeMappingDefinition, diff --git a/src/core/server/saved_objects/mappings/index.ts b/src/core/server/saved_objects/mappings/index.ts index bf1029e9f3b81d..5da185ace79c63 100644 --- a/src/core/server/saved_objects/mappings/index.ts +++ b/src/core/server/saved_objects/mappings/index.ts @@ -8,8 +8,6 @@ export { getTypes, getProperty, getRootProperties, getRootPropertiesObjects } from './lib'; export type { - SavedObjectsComplexFieldMapping, - SavedObjectsCoreFieldMapping, SavedObjectsTypeMappingDefinition, SavedObjectsTypeMappingDefinitions, SavedObjectsMappingProperties, diff --git a/src/core/server/saved_objects/mappings/lib/get_property.test.ts b/src/core/server/saved_objects/mappings/lib/get_property.test.ts index dab712bbb87add..8732b5e07d3fa7 100644 --- a/src/core/server/saved_objects/mappings/lib/get_property.test.ts +++ b/src/core/server/saved_objects/mappings/lib/get_property.test.ts @@ -34,7 +34,7 @@ const MAPPINGS = { }, }, }, -}; +} as const; function runTest(key: string | string[], mapping: IndexMapping | SavedObjectsFieldMapping) { expect(typeof key === 'string' || Array.isArray(key)).toBeTruthy(); diff --git a/src/core/server/saved_objects/mappings/lib/get_property.ts b/src/core/server/saved_objects/mappings/lib/get_property.ts index c2daa1e70a898a..2a9993bc175ca1 100644 --- a/src/core/server/saved_objects/mappings/lib/get_property.ts +++ b/src/core/server/saved_objects/mappings/lib/get_property.ts @@ -7,7 +7,7 @@ */ import { toPath } from 'lodash'; -import { SavedObjectsCoreFieldMapping, SavedObjectsFieldMapping, IndexMapping } from '../types'; +import { SavedObjectsFieldMapping, IndexMapping } from '../types'; function getPropertyMappingFromObjectMapping( mapping: IndexMapping | SavedObjectsFieldMapping, @@ -15,7 +15,7 @@ function getPropertyMappingFromObjectMapping( ): SavedObjectsFieldMapping | undefined { const props = (mapping && (mapping as IndexMapping).properties) || - (mapping && (mapping as SavedObjectsCoreFieldMapping).fields); + (mapping && (mapping as SavedObjectsFieldMapping).fields); if (!props) { return undefined; diff --git a/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.test.ts b/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.test.ts index 2daca3a1fdd83c..cbc6808418bc06 100644 --- a/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.test.ts +++ b/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.test.ts @@ -15,7 +15,7 @@ test(`returns single object with properties`, () => { properties: {}, }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({ @@ -32,7 +32,7 @@ test(`returns single object with type === 'object'`, () => { type: 'object', }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({ @@ -75,7 +75,7 @@ test(`returns two objects with type === 'object'`, () => { type: 'object', }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({ @@ -95,7 +95,7 @@ test(`excludes objects without properties and type of keyword`, () => { type: 'keyword', }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({}); @@ -111,7 +111,7 @@ test(`excludes two objects without properties and type of keyword`, () => { type: 'keyword', }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({}); @@ -127,7 +127,7 @@ test(`includes one object with properties and excludes one object without proper type: 'keyword', }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({ @@ -147,7 +147,7 @@ test(`includes one object with type === 'object' and excludes one object without type: 'keyword', }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({ @@ -170,7 +170,7 @@ test('excludes references and migrationVersion which are part of the blacklist', type: 'object', }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({ foo: { diff --git a/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.ts b/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.ts index 3a25865c03b265..54ea4eafc186f9 100644 --- a/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.ts +++ b/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.ts @@ -6,11 +6,7 @@ * Side Public License, v 1. */ -import { - SavedObjectsComplexFieldMapping, - IndexMapping, - SavedObjectsMappingProperties, -} from '../types'; +import { SavedObjectsFieldMapping, IndexMapping, SavedObjectsMappingProperties } from '../types'; import { getRootProperties } from './get_root_properties'; /** @@ -36,7 +32,7 @@ export function getRootPropertiesObjects(mappings: IndexMapping) { // we consider the existence of the properties or type of object to designate that this is an object datatype if ( !omittedRootProps.includes(key) && - ((value as SavedObjectsComplexFieldMapping).properties || value.type === 'object') + ((value as SavedObjectsFieldMapping).properties || value.type === 'object') ) { acc[key] = value; } diff --git a/src/core/server/saved_objects/mappings/types.ts b/src/core/server/saved_objects/mappings/types.ts index 25fb61de935187..e2ad2a91fd000a 100644 --- a/src/core/server/saved_objects/mappings/types.ts +++ b/src/core/server/saved_objects/mappings/types.ts @@ -6,6 +6,7 @@ * Side Public License, v 1. */ +import type { estypes } from '@elastic/elasticsearch'; /** * Describe a saved object type mapping. * @@ -96,9 +97,17 @@ export interface SavedObjectsMappingProperties { * * @public */ -export type SavedObjectsFieldMapping = - | SavedObjectsCoreFieldMapping - | SavedObjectsComplexFieldMapping; +export type SavedObjectsFieldMapping = estypes.MappingProperty & { + /** + * The dynamic property of the mapping, either `false` or `'strict'`. If + * unspecified `dynamic: 'strict'` will be inherited from the top-level + * index mappings. + * + * Note: To limit the number of mapping fields Saved Object types should + * *never* use `dynamic: true`. + */ + dynamic?: false | 'strict'; +}; /** @internal */ export interface IndexMapping { @@ -114,42 +123,3 @@ export interface IndexMappingMeta { // the md5 hash of that mapping's value when the index was created. migrationMappingPropertyHashes?: { [k: string]: string }; } - -/** - * See {@link SavedObjectsFieldMapping} for documentation. - * - * @public - */ -export interface SavedObjectsCoreFieldMapping { - type: string; - null_value?: number | boolean | string; - index?: boolean; - doc_values?: boolean; - fields?: { - [subfield: string]: { - type: string; - ignore_above?: number; - }; - }; -} - -/** - * See {@link SavedObjectsFieldMapping} for documentation. - * - * @public - */ -export interface SavedObjectsComplexFieldMapping { - /** - * The dynamic property of the mapping, either `false` or `'strict'`. If - * unspecified `dynamic: 'strict'` will be inherited from the top-level - * index mappings. - * - * Note: To limit the number of mapping fields Saved Object types should - * *never* use `dynamic: true`. - */ - dynamic?: false | 'strict'; - enabled?: boolean; - doc_values?: boolean; - type?: string; - properties: SavedObjectsMappingProperties; -} diff --git a/src/core/server/saved_objects/migrations/core/build_active_mappings.test.ts b/src/core/server/saved_objects/migrations/core/build_active_mappings.test.ts index 5465da2f620adb..a39fff20abbe71 100644 --- a/src/core/server/saved_objects/migrations/core/build_active_mappings.test.ts +++ b/src/core/server/saved_objects/migrations/core/build_active_mappings.test.ts @@ -19,19 +19,19 @@ describe('buildActiveMappings', () => { const properties = { aaa: { type: 'text' }, bbb: { type: 'long' }, - }; + } as const; expect(buildActiveMappings(properties)).toMatchSnapshot(); }); test('disallows duplicate mappings', () => { - const properties = { type: { type: 'long' } }; + const properties = { type: { type: 'long' } } as const; expect(() => buildActiveMappings(properties)).toThrow(/Cannot redefine core mapping \"type\"/); }); test('disallows mappings with leading underscore', () => { - const properties = { _hm: { type: 'keyword' } }; + const properties = { _hm: { type: 'keyword' } } as const; expect(() => buildActiveMappings(properties)).toThrow( /Invalid mapping \"_hm\"\. Mappings cannot start with _/ @@ -60,7 +60,7 @@ describe('buildActiveMappings', () => { aaa: { type: 'keyword', fields: { a: { type: 'keyword' }, b: { type: 'text' } } }, bbb: { fields: { b: { type: 'text' }, a: { type: 'keyword' } }, type: 'keyword' }, ccc: { fields: { b: { type: 'text' }, a: { type: 'text' } }, type: 'keyword' }, - }; + } as const; const mappings = buildActiveMappings(properties); const hashes = mappings._meta!.migrationMappingPropertyHashes!; diff --git a/src/core/server/saved_objects/migrations/core/build_index_map.test.ts b/src/core/server/saved_objects/migrations/core/build_index_map.test.ts index c7a3251e33ab18..731b7f8c029c24 100644 --- a/src/core/server/saved_objects/migrations/core/build_index_map.test.ts +++ b/src/core/server/saved_objects/migrations/core/build_index_map.test.ts @@ -36,7 +36,7 @@ test('mappings without index pattern goes to default index', () => { type1: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, @@ -48,7 +48,7 @@ test('mappings without index pattern goes to default index', () => { type1: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, @@ -69,7 +69,7 @@ test(`mappings with custom index pattern doesn't go to default index`, () => { type1: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, @@ -81,7 +81,7 @@ test(`mappings with custom index pattern doesn't go to default index`, () => { type1: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, @@ -103,7 +103,7 @@ test('creating a script gets added to the index pattern', () => { type1: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, @@ -116,7 +116,7 @@ test('creating a script gets added to the index pattern', () => { type1: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, @@ -144,18 +144,18 @@ test('throws when two scripts are defined for an index pattern', () => { type1: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, type2: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, - }; + } as const; expect(() => createIndexMap({ kibanaIndexName: defaultIndex, diff --git a/src/core/server/saved_objects/migrations/core/elastic_index.test.ts b/src/core/server/saved_objects/migrations/core/elastic_index.test.ts index 1d2ec6abc0dd14..c9c24cc85a4528 100644 --- a/src/core/server/saved_objects/migrations/core/elastic_index.test.ts +++ b/src/core/server/saved_objects/migrations/core/elastic_index.test.ts @@ -40,10 +40,10 @@ describe('ElasticIndex', () => { return elasticsearchClientMock.createSuccessTransportRequestPromise({ [index]: { aliases: { foo: index }, - mappings: { dynamic: 'strict', properties: { a: 'b' } }, + mappings: { dynamic: 'strict', properties: { a: 'b' } as any }, settings: {}, }, - } as estypes.GetIndexResponse); + } as estypes.IndicesGetResponse); }); const info = await Index.fetchInfo(client, '.baz'); @@ -164,7 +164,7 @@ describe('ElasticIndex', () => { client.tasks.get.mockResolvedValue( elasticsearchClientMock.createSuccessTransportRequestPromise({ completed: true, - } as estypes.GetTaskResponse) + } as estypes.TaskGetResponse) ); const info = { @@ -175,7 +175,7 @@ describe('ElasticIndex', () => { dynamic: 'strict' as const, properties: { foo: { type: 'keyword' } }, }, - }; + } as const; await Index.convertToAlias( client, @@ -248,7 +248,7 @@ describe('ElasticIndex', () => { reason: 'all shards failed', failed_shards: [], }, - } as estypes.GetTaskResponse) + } as estypes.TaskGetResponse) ); const info = { diff --git a/src/core/server/saved_objects/migrations/core/elastic_index.ts b/src/core/server/saved_objects/migrations/core/elastic_index.ts index 76fdd5e73d804f..296a4cee07c11b 100644 --- a/src/core/server/saved_objects/migrations/core/elastic_index.ts +++ b/src/core/server/saved_objects/migrations/core/elastic_index.ts @@ -32,7 +32,7 @@ export interface FullIndexInfo { // saved objects which are no longer used. These saved objects will still be // kept in the outdated index for backup purposes, but won't be available in // the upgraded index. -export const excludeUnusedTypesQuery: estypes.QueryContainer = { +export const excludeUnusedTypesQuery: estypes.QueryDslQueryContainer = { bool: { must_not: [ // https://github.com/elastic/kibana/issues/91869 @@ -401,7 +401,6 @@ async function reindex( task_id: String(task), }); - // @ts-expect-error @elastic/elasticsearch GetTaskResponse doesn't contain `error` property const e = body.error; if (e) { throw new Error(`Re-index failed [${e.type}] ${e.reason} :: ${JSON.stringify(e)}`); diff --git a/src/core/server/saved_objects/migrations/core/index_migrator.test.ts b/src/core/server/saved_objects/migrations/core/index_migrator.test.ts index fcc03f363139b0..64d4fa3609e90f 100644 --- a/src/core/server/saved_objects/migrations/core/index_migrator.test.ts +++ b/src/core/server/saved_objects/migrations/core/index_migrator.test.ts @@ -450,7 +450,7 @@ function withIndex( client.tasks.get.mockReturnValue( elasticsearchClientMock.createSuccessTransportRequestPromise({ completed: true, - } as estypes.GetTaskResponse) + } as estypes.TaskGetResponse) ); client.search.mockReturnValue( elasticsearchClientMock.createSuccessTransportRequestPromise(searchResult(0) as any) diff --git a/src/core/server/saved_objects/migrations/core/migration_context.test.ts b/src/core/server/saved_objects/migrations/core/migration_context.test.ts index 5f2e8a37ec4279..240b41266abb66 100644 --- a/src/core/server/saved_objects/migrations/core/migration_context.test.ts +++ b/src/core/server/saved_objects/migrations/core/migration_context.test.ts @@ -31,7 +31,7 @@ describe('disableUnknownTypeMappingFields', () => { }, }, }, - }; + } as const; const activeMappings = { _meta: { migrationMappingPropertyHashes: { @@ -46,7 +46,7 @@ describe('disableUnknownTypeMappingFields', () => { }, }, }, - }; + } as const; const targetMappings = disableUnknownTypeMappingFields(activeMappings, sourceMappings); it('disables complex field mappings from unknown types in the source mappings', () => { diff --git a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts index 37cea5d2de3d2c..d0cc52f2dd9bd1 100644 --- a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts +++ b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts @@ -320,7 +320,11 @@ const mockV2MigrationOptions = () => { ) ); options.client.indices.addBlock.mockReturnValue( - elasticsearchClientMock.createSuccessTransportRequestPromise({ acknowledged: true }) + elasticsearchClientMock.createSuccessTransportRequestPromise({ + acknowledged: true, + shards_acknowledged: true, + indices: [], + }) ); options.client.reindex.mockReturnValue( elasticsearchClientMock.createSuccessTransportRequestPromise({ @@ -333,7 +337,7 @@ const mockV2MigrationOptions = () => { error: undefined, failures: [], task: { description: 'task description' } as any, - } as estypes.GetTaskResponse) + } as estypes.TaskGetResponse) ); options.client.search = jest 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 47ee44e762db79..8e5042a5ff8fe0 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/create_index.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/create_index.ts @@ -24,8 +24,8 @@ import { } from './constants'; import { waitForIndexStatusYellow } from './wait_for_index_status_yellow'; -function aliasArrayToRecord(aliases: string[]): Record { - const result: Record = {}; +function aliasArrayToRecord(aliases: string[]): Record { + const result: Record = {}; for (const alias of aliases) { result[alias] = {}; } 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 b508a6198bfb34..3fa4d59e383bfa 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 @@ -242,9 +242,7 @@ describe('migration actions', () => { it('rejects if there is a non-retryable error', async () => { expect.assertions(1); const task = removeWriteBlock({ client, index: 'no_such_index' }); - await expect(task()).rejects.toMatchInlineSnapshot( - `[ResponseError: index_not_found_exception]` - ); + await expect(task()).rejects.toThrow('index_not_found_exception'); }); }); @@ -264,7 +262,7 @@ describe('migration actions', () => { // Allocate 1 replica so that this index stays yellow number_of_replicas: '1', // Disable all shard allocation so that the index status is red - index: { routing: { allocation: { enable: 'none' } } }, + routing: { allocation: { enable: 'none' } }, }, }, }, @@ -284,7 +282,7 @@ describe('migration actions', () => { index: 'red_then_yellow_index', body: { // Enable all shard allocation so that the index status turns yellow - index: { routing: { allocation: { enable: 'all' } } }, + settings: { routing: { allocation: { enable: 'all' } } }, }, }); @@ -354,7 +352,7 @@ describe('migration actions', () => { index: 'clone_red_then_yellow_index', body: { // Enable all shard allocation so that the index status goes yellow - index: { routing: { allocation: { enable: 'all' } } }, + settings: { routing: { allocation: { enable: 'all' } } }, }, }); indexYellow = true; @@ -859,9 +857,7 @@ describe('migration actions', () => { sourceIndex: 'no_such_index', targetIndex: 'existing_index_2', }); - await expect(task()).rejects.toMatchInlineSnapshot( - `[ResponseError: index_not_found_exception]` - ); + await expect(task()).rejects.toThrow('index_not_found_exception'); task = verifyReindex({ client, @@ -1142,10 +1138,7 @@ describe('migration actions', () => { timeout: '10s', }); - await expect(task()).rejects.toMatchInlineSnapshot(` - [Error: pickupUpdatedMappings task failed with the following error: - {"type":"index_not_found_exception","reason":"no such index [no_such_index]","resource.type":"index_or_alias","resource.id":"no_such_index","index_uuid":"_na_","index":"no_such_index"}] - `); + await expect(task()).rejects.toThrow('index_not_found_exception'); }); it('resolves left wait_for_task_completion_timeout when the task does not complete within the timeout', async () => { const res = (await pickupUpdatedMappings( @@ -1433,7 +1426,7 @@ describe('migration actions', () => { index: 'red_then_yellow_index', body: { // Disable all shard allocation so that the index status is red - index: { routing: { allocation: { enable: 'all' } } }, + settings: { routing: { allocation: { enable: 'all' } } }, }, }); indexYellow = true; @@ -1455,7 +1448,7 @@ describe('migration actions', () => { // failure await expect( createIndex({ client, indexName: 'existing_index_2_alias', mappings: undefined as any })() - ).rejects.toMatchInlineSnapshot(`[ResponseError: invalid_index_name_exception]`); + ).rejects.toThrow('invalid_index_name_exception'); }); }); 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 16f1df05f26b3e..b101e7db0141ca 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 @@ -28,7 +28,7 @@ export interface ReadWithPit { export interface ReadWithPitParams { client: ElasticsearchClient; pitId: string; - query: estypes.QueryContainer; + query: estypes.QueryDslQueryContainer; batchSize: number; searchAfter?: number[]; seqNoPrimaryTerm?: boolean; diff --git a/src/core/server/saved_objects/migrationsv2/actions/reindex.ts b/src/core/server/saved_objects/migrationsv2/actions/reindex.ts index ca8d3b594703c3..e9cfb4b61dace5 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/reindex.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/reindex.ts @@ -32,7 +32,7 @@ export interface ReindexParams { * are no longer used. These saved objects will still be kept in the outdated * index for backup purposes, but won't be available in the upgraded index. */ - unusedTypesQuery: estypes.QueryContainer; + unusedTypesQuery: estypes.QueryDslQueryContainer; } /** * Reindex documents from the `sourceIndex` into the `targetIndex`. Returns a 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 c55e4a235fbf10..b5bf64d5c29f75 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 @@ -39,7 +39,7 @@ export const removeWriteBlock = ({ // Don't change any existing settings preserve_existing: true, body: { - index: { + settings: { blocks: { write: false, }, 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 7406cd35b1593e..c27170a78245b2 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 @@ -24,7 +24,7 @@ export interface SearchResponse { export interface SearchForOutdatedDocumentsOptions { batchSize: number; targetIndex: string; - outdatedDocumentsQuery?: estypes.QueryContainer; + outdatedDocumentsQuery?: estypes.QueryDslQueryContainer; } /** diff --git a/src/core/server/saved_objects/migrationsv2/actions/wait_for_reindex_task.ts b/src/core/server/saved_objects/migrationsv2/actions/wait_for_reindex_task.ts index fcadb5e80298a7..18cf3350292b5c 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/wait_for_reindex_task.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/wait_for_reindex_task.ts @@ -42,7 +42,7 @@ export const waitForReindexTask = flow( if (res.error.value.type === 'index_not_found_exception') { return TaskEither.left({ type: 'index_not_found_exception' as const, - index: res.error.value.index, + index: res.error.value.index!, }); } else { throw new Error('Reindex failed with the following error:\n' + JSON.stringify(res.error)); 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 4e3631797e34bc..0cdaa88c535ab7 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 @@ -16,7 +16,7 @@ import { } from './catch_retryable_es_client_errors'; /** @internal */ export interface WaitForTaskResponse { - error: Option.Option<{ type: string; reason: string; index: string }>; + error: Option.Option<{ type: string; reason: string; index?: string }>; completed: boolean; failures: Option.Option; description?: string; @@ -84,7 +84,6 @@ export const waitForTask = ({ const failures = body.response?.failures ?? []; return Either.right({ completed: body.completed, - // @ts-expect-error @elastic/elasticsearch GetTaskResponse doesn't declare `error` property error: Option.fromNullable(body.error), failures: failures.length > 0 ? Option.some(failures) : Option.none, description: body.task.description, diff --git a/src/core/server/saved_objects/migrationsv2/integration_tests/migration.test.ts b/src/core/server/saved_objects/migrationsv2/integration_tests/migration.test.ts index 5e4b8feefbd958..f9d8e7cc4fbaab 100644 --- a/src/core/server/saved_objects/migrationsv2/integration_tests/migration.test.ts +++ b/src/core/server/saved_objects/migrationsv2/integration_tests/migration.test.ts @@ -157,7 +157,10 @@ describe('migration v2', () => { const response = body[migratedIndex]; expect(response).toBeDefined(); - expect(Object.keys(response.aliases).sort()).toEqual(['.kibana', `.kibana_${kibanaVersion}`]); + expect(Object.keys(response.aliases!).sort()).toEqual([ + '.kibana', + `.kibana_${kibanaVersion}`, + ]); }); it('copies all the document of the previous index to the new one', async () => { @@ -216,7 +219,10 @@ describe('migration v2', () => { const response = body[migratedIndex]; expect(response).toBeDefined(); - expect(Object.keys(response.aliases).sort()).toEqual(['.kibana', `.kibana_${kibanaVersion}`]); + expect(Object.keys(response.aliases!).sort()).toEqual([ + '.kibana', + `.kibana_${kibanaVersion}`, + ]); }); it('copies all the document of the previous index to the new one', async () => { diff --git a/src/core/server/saved_objects/migrationsv2/model.test.ts b/src/core/server/saved_objects/migrationsv2/model.test.ts index 186cb24b4a34a8..86dc590aabdad8 100644 --- a/src/core/server/saved_objects/migrationsv2/model.test.ts +++ b/src/core/server/saved_objects/migrationsv2/model.test.ts @@ -244,7 +244,7 @@ describe('migrations v2 model', () => { disabled_saved_object_type: '7997cf5a56cc02bdc9c93361bde732b0', }, }, - }; + } as const; test('INIT -> OUTDATED_DOCUMENTS_SEARCH_OPEN_PIT if .kibana is already pointing to the target index', () => { const res: ResponseType<'INIT'> = Either.right({ @@ -683,7 +683,7 @@ describe('migrations v2 model', () => { disabled_saved_object_type: '7997cf5a56cc02bdc9c93361bde732b0', }, }, - }; + } as const; const waitForYellowSourceState: WaitForYellowSourceState = { ...baseState, diff --git a/src/core/server/saved_objects/migrationsv2/types.ts b/src/core/server/saved_objects/migrationsv2/types.ts index adcd2ad32fd24e..1151e8337d3d59 100644 --- a/src/core/server/saved_objects/migrationsv2/types.ts +++ b/src/core/server/saved_objects/migrationsv2/types.ts @@ -53,7 +53,7 @@ export interface BaseState extends ControlState { readonly tempIndexMappings: IndexMapping; /** Script to apply to a legacy index before it can be used as a migration source */ readonly preMigrationScript: Option.Option; - readonly outdatedDocumentsQuery: estypes.QueryContainer; + readonly outdatedDocumentsQuery: estypes.QueryDslQueryContainer; readonly retryCount: number; readonly retryDelay: number; /** @@ -112,7 +112,7 @@ export interface BaseState extends ControlState { * are no longer used. These saved objects will still be kept in the outdated * index for backup purposes, but won't be available in the upgraded index. */ - readonly unusedTypesQuery: estypes.QueryContainer; + readonly unusedTypesQuery: estypes.QueryDslQueryContainer; } export interface InitState extends BaseState { @@ -132,7 +132,7 @@ export interface PostInitState extends BaseState { /** The target index is the index to which the migration writes */ readonly targetIndex: string; readonly versionIndexReadyActions: Option.Option; - readonly outdatedDocumentsQuery: estypes.QueryContainer; + readonly outdatedDocumentsQuery: estypes.QueryDslQueryContainer; } export interface DoneState extends PostInitState { diff --git a/src/core/server/saved_objects/saved_objects_type_registry.ts b/src/core/server/saved_objects/saved_objects_type_registry.ts index a63837132b652e..ba5960c59239d7 100644 --- a/src/core/server/saved_objects/saved_objects_type_registry.ts +++ b/src/core/server/saved_objects/saved_objects_type_registry.ts @@ -33,7 +33,7 @@ export class SavedObjectTypeRegistry { throw new Error(`Type '${type.name}' is already registered`); } validateType(type); - this.types.set(type.name, deepFreeze(type)); + this.types.set(type.name, deepFreeze(type) as SavedObjectsType); } /** diff --git a/src/core/server/saved_objects/service/lib/aggregations/validation.test.ts b/src/core/server/saved_objects/service/lib/aggregations/validation.test.ts index 57421db76f5b6e..53f1b5c9d78c57 100644 --- a/src/core/server/saved_objects/service/lib/aggregations/validation.test.ts +++ b/src/core/server/saved_objects/service/lib/aggregations/validation.test.ts @@ -9,7 +9,7 @@ import type { estypes } from '@elastic/elasticsearch'; import { validateAndConvertAggregations } from './validation'; -type AggsMap = Record; +type AggsMap = Record; const mockMappings = { properties: { @@ -19,7 +19,9 @@ const mockMappings = { references: { type: 'nested', properties: { - id: 'keyword', + id: { + type: 'keyword', + }, }, }, foo: { @@ -31,7 +33,7 @@ const mockMappings = { type: 'text', }, bytes: { - type: 'number', + type: 'integer', }, }, }, @@ -73,7 +75,7 @@ const mockMappings = { }, }, }, -}; +} as const; describe('validateAndConvertAggregations', () => { it('validates a simple aggregations', () => { diff --git a/src/core/server/saved_objects/service/lib/aggregations/validation.ts b/src/core/server/saved_objects/service/lib/aggregations/validation.ts index cd41a23f4a28b5..5ef89f297a796b 100644 --- a/src/core/server/saved_objects/service/lib/aggregations/validation.ts +++ b/src/core/server/saved_objects/service/lib/aggregations/validation.ts @@ -37,9 +37,9 @@ interface ValidationContext { */ export const validateAndConvertAggregations = ( allowedTypes: string[], - aggs: Record, + aggs: Record, indexMapping: IndexMapping -): Record => { +): Record => { return validateAggregations(aggs, { allowedTypes, indexMapping, @@ -53,16 +53,15 @@ export const validateAndConvertAggregations = ( * Or a nested record of aggregation (`SearchRequest.body.aggs.myAggregation.aggs`) */ const validateAggregations = ( - aggregations: Record, + aggregations: Record, context: ValidationContext ) => { - return Object.entries(aggregations).reduce>( - (memo, [aggrName, aggrContainer]) => { - memo[aggrName] = validateAggregation(aggrContainer, childContext(context, aggrName)); - return memo; - }, - {} - ); + return Object.entries(aggregations).reduce< + Record + >((memo, [aggrName, aggrContainer]) => { + memo[aggrName] = validateAggregation(aggrContainer, childContext(context, aggrName)); + return memo; + }, {}); }; /** @@ -70,7 +69,7 @@ const validateAggregations = ( * from a nested aggregation record, including its potential nested aggregations. */ const validateAggregation = ( - aggregation: estypes.AggregationContainer, + aggregation: estypes.AggregationsAggregationContainer, context: ValidationContext ) => { const container = validateAggregationContainer(aggregation, context); @@ -93,10 +92,10 @@ const validateAggregation = ( * (ignoring its nested aggregations) */ const validateAggregationContainer = ( - container: estypes.AggregationContainer, + container: estypes.AggregationsAggregationContainer, context: ValidationContext ) => { - return Object.entries(container).reduce( + return Object.entries(container).reduce( (memo, [aggName, aggregation]) => { if (aggregationKeys.includes(aggName)) { return memo; diff --git a/src/core/server/saved_objects/service/lib/aggregations/validation_utils.test.ts b/src/core/server/saved_objects/service/lib/aggregations/validation_utils.test.ts index 25c3aea474ecec..0425e46b4477e6 100644 --- a/src/core/server/saved_objects/service/lib/aggregations/validation_utils.test.ts +++ b/src/core/server/saved_objects/service/lib/aggregations/validation_utils.test.ts @@ -6,7 +6,6 @@ * Side Public License, v 1. */ -import { IndexMapping } from '../../../mappings'; import { isRootLevelAttribute, rewriteRootLevelAttribute, @@ -14,7 +13,7 @@ import { rewriteObjectTypeAttribute, } from './validation_utils'; -const mockMappings: IndexMapping = { +const mockMappings = { properties: { updated_at: { type: 'date', @@ -28,7 +27,7 @@ const mockMappings: IndexMapping = { type: 'text', }, bytes: { - type: 'number', + type: 'integer', }, }, }, @@ -70,7 +69,7 @@ const mockMappings: IndexMapping = { }, }, }, -}; +} as const; describe('isRootLevelAttribute', () => { it('returns true when referring to a path to a valid root level field', () => { diff --git a/src/core/server/saved_objects/service/lib/filter_utils.test.ts b/src/core/server/saved_objects/service/lib/filter_utils.test.ts index 2ef5219ccfff16..e6934398862dc0 100644 --- a/src/core/server/saved_objects/service/lib/filter_utils.test.ts +++ b/src/core/server/saved_objects/service/lib/filter_utils.test.ts @@ -31,7 +31,7 @@ const mockMappings = { type: 'text', }, bytes: { - type: 'number', + type: 'integer', }, }, }, @@ -90,7 +90,7 @@ const mockMappings = { }, }, }, -}; +} as const; describe('Filter Utils', () => { describe('#validateConvertFilterToKueryNode', () => { diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts index c626a2b2acfb58..6b51bd57248a1d 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -672,7 +672,6 @@ export class SavedObjectsRepository { } const deleteDocNotFound = body.result === 'not_found'; - // @ts-expect-error 'error' does not exist on type 'DeleteResponse' const deleteIndexNotFound = body.error && body.error.type === 'index_not_found_exception'; if (deleteDocNotFound || deleteIndexNotFound) { // see "404s from missing index" above @@ -897,7 +896,7 @@ export class SavedObjectsRepository { per_page: perPage, total: body.hits.total, saved_objects: body.hits.hits.map( - (hit: estypes.Hit): SavedObjectsFindResult => ({ + (hit: estypes.SearchHit): SavedObjectsFindResult => ({ // @ts-expect-error @elastic/elasticsearch declared Id as string | number ...this._rawToSavedObject(hit), score: hit._score!, @@ -1835,13 +1834,9 @@ export class SavedObjectsRepository { ...(preference ? { preference } : {}), }; - const { body, statusCode } = await this.client.openPointInTime( - // @ts-expect-error @elastic/elasticsearch OpenPointInTimeRequest.index expected to accept string[] - esOptions, - { - ignore: [404], - } - ); + const { body, statusCode } = await this.client.openPointInTime(esOptions, { + ignore: [404], + }); if (statusCode === 404) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(); } diff --git a/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts b/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts index 64b3dd428fb8bf..3196a59ca39ee4 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts @@ -26,7 +26,7 @@ interface GetSearchDslOptions { rootSearchFields?: string[]; searchAfter?: estypes.Id[]; sortField?: string; - sortOrder?: estypes.SortOrder; + sortOrder?: estypes.SearchSortOrder; namespaces?: string[]; pit?: SavedObjectsPitParams; typeToNamespacesMap?: Map; diff --git a/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.test.ts b/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.test.ts index 1376f0d50a9da6..e2a21cc03ce3be 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.test.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.test.ts @@ -50,7 +50,7 @@ const MAPPINGS = { }, }, }, -}; +} as const; describe('searchDsl/getSortParams', () => { describe('type, no sortField', () => { diff --git a/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.ts b/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.ts index 64849c308f3f09..592110a5413ec7 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.ts @@ -16,8 +16,8 @@ export function getSortingParams( mappings: IndexMapping, type: string | string[], sortField?: string, - sortOrder?: estypes.SortOrder -): { sort?: estypes.SortContainer[] } { + sortOrder?: estypes.SearchSortOrder +): { sort?: estypes.SearchSortContainer[] } { if (!sortField) { return {}; } diff --git a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts index 079549265385cd..3131d0240f96b9 100644 --- a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts +++ b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import type { BulkOperationContainer, MultiGetOperation } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import intersection from 'lodash/intersection'; import type { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; @@ -173,7 +173,7 @@ export async function updateObjectsSpaces({ }; }); - const bulkGetDocs = expectedBulkGetResults.reduce((acc, x) => { + const bulkGetDocs = expectedBulkGetResults.reduce((acc, x) => { if (isRight(x) && x.value.esRequestIndex !== undefined) { acc.push({ _id: serializer.generateRawId(undefined, x.value.type, x.value.id), @@ -192,7 +192,7 @@ export async function updateObjectsSpaces({ const time = new Date().toISOString(); let bulkOperationRequestIndexCounter = 0; - const bulkOperationParams: BulkOperationContainer[] = []; + const bulkOperationParams: estypes.BulkOperationContainer[] = []; const expectedBulkOperationResults: Either[] = expectedBulkGetResults.map( (expectedBulkGetResult) => { if (isLeft(expectedBulkGetResult)) { diff --git a/src/core/server/saved_objects/types.ts b/src/core/server/saved_objects/types.ts index d3bfdcc6923dcf..964ba671b59646 100644 --- a/src/core/server/saved_objects/types.ts +++ b/src/core/server/saved_objects/types.ts @@ -80,7 +80,7 @@ export interface SavedObjectsFindOptions { page?: number; perPage?: number; sortField?: string; - sortOrder?: estypes.SortOrder; + sortOrder?: estypes.SearchSortOrder; /** * An array of fields to include in the results * @example @@ -137,7 +137,7 @@ export interface SavedObjectsFindOptions { * * @alpha */ - aggs?: Record; + aggs?: Record; namespaces?: string[]; /** * This map defines each type to search for, and the namespace(s) to search for the type in; this is only intended to be used by a saved diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index 379e4147ae024c..acec03902bf6aa 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -2361,38 +2361,6 @@ export interface SavedObjectsCollectMultiNamespaceReferencesResponse { objects: SavedObjectReferenceWithContext[]; } -// @public -export interface SavedObjectsComplexFieldMapping { - // (undocumented) - doc_values?: boolean; - dynamic?: false | 'strict'; - // (undocumented) - enabled?: boolean; - // (undocumented) - properties: SavedObjectsMappingProperties; - // (undocumented) - type?: string; -} - -// @public -export interface SavedObjectsCoreFieldMapping { - // (undocumented) - doc_values?: boolean; - // (undocumented) - fields?: { - [subfield: string]: { - type: string; - ignore_above?: number; - }; - }; - // (undocumented) - index?: boolean; - // (undocumented) - null_value?: number | boolean | string; - // (undocumented) - type: string; -} - // @public (undocumented) export interface SavedObjectsCreateOptions extends SavedObjectsBaseOptions { coreMigrationVersion?: string; @@ -2554,12 +2522,14 @@ export interface SavedObjectsExportTransformContext { } // @public -export type SavedObjectsFieldMapping = SavedObjectsCoreFieldMapping | SavedObjectsComplexFieldMapping; +export type SavedObjectsFieldMapping = estypes.MappingProperty & { + dynamic?: false | 'strict'; +}; // @public (undocumented) export interface SavedObjectsFindOptions { // @alpha - aggs?: Record; + aggs?: Record; defaultSearchOperator?: 'AND' | 'OR'; fields?: string[]; // Warning: (ae-forgotten-export) The symbol "KueryNode" needs to be exported by the entry point index.d.ts @@ -2583,7 +2553,7 @@ export interface SavedObjectsFindOptions { // (undocumented) sortField?: string; // (undocumented) - sortOrder?: estypes.SortOrder; + sortOrder?: estypes.SearchSortOrder; // (undocumented) type: string | string[]; typeToNamespacesMap?: Map; diff --git a/src/plugins/data/common/es_query/filters/phrase_filter.ts b/src/plugins/data/common/es_query/filters/phrase_filter.ts index 2a7f2458a27de8..85562435e68d02 100644 --- a/src/plugins/data/common/es_query/filters/phrase_filter.ts +++ b/src/plugins/data/common/es_query/filters/phrase_filter.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 { estypes } from '@elastic/elasticsearch'; import { get, isPlainObject } from 'lodash'; import { Filter, FilterMeta } from './meta_filter'; import { IIndexPattern, IFieldType } from '../../index_patterns'; @@ -23,7 +23,7 @@ export type PhraseFilter = Filter & { script?: { script: { source?: any; - lang?: string; + lang?: estypes.ScriptLanguage; params: any; }; }; diff --git a/src/plugins/data/common/es_query/filters/range_filter.ts b/src/plugins/data/common/es_query/filters/range_filter.ts index fb8426655583ee..a082b93c0a79a1 100644 --- a/src/plugins/data/common/es_query/filters/range_filter.ts +++ b/src/plugins/data/common/es_query/filters/range_filter.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 { estypes } from '@elastic/elasticsearch'; import { map, reduce, mapValues, get, keys, pickBy } from 'lodash'; import { Filter, FilterMeta } from './meta_filter'; import { IIndexPattern, IFieldType } from '../../index_patterns'; @@ -63,7 +63,7 @@ export type RangeFilter = Filter & script?: { script: { params: any; - lang: string; + lang: estypes.ScriptLanguage; source: any; }; }; diff --git a/src/plugins/data/common/index_patterns/fields/__snapshots__/index_pattern_field.test.ts.snap b/src/plugins/data/common/index_patterns/fields/__snapshots__/index_pattern_field.test.ts.snap index 6b1d01e5ba1429..681aba41a609c0 100644 --- a/src/plugins/data/common/index_patterns/fields/__snapshots__/index_pattern_field.test.ts.snap +++ b/src/plugins/data/common/index_patterns/fields/__snapshots__/index_pattern_field.test.ts.snap @@ -16,7 +16,7 @@ Object { "esTypes": Array [ "keyword", ], - "lang": "lang", + "lang": "java", "name": "name", "readFromDocValues": false, "script": "script", @@ -58,7 +58,7 @@ Object { }, }, "isMapped": undefined, - "lang": "lang", + "lang": "java", "name": "name", "readFromDocValues": false, "runtimeField": Object { diff --git a/src/plugins/data/common/index_patterns/fields/index_pattern_field.test.ts b/src/plugins/data/common/index_patterns/fields/index_pattern_field.test.ts index 48342a9e02a2bd..73f015ca5517c3 100644 --- a/src/plugins/data/common/index_patterns/fields/index_pattern_field.test.ts +++ b/src/plugins/data/common/index_patterns/fields/index_pattern_field.test.ts @@ -24,7 +24,7 @@ describe('Field', function () { name: 'name', type: 'string', script: 'script', - lang: 'lang', + lang: 'java' as const, count: 1, esTypes: ['text'], // note, this will get replaced by the runtime field type aggregatable: true, diff --git a/src/plugins/data/common/index_patterns/fields/types.ts b/src/plugins/data/common/index_patterns/fields/types.ts index 565dd6d9269488..0fb7a46c2cf73d 100644 --- a/src/plugins/data/common/index_patterns/fields/types.ts +++ b/src/plugins/data/common/index_patterns/fields/types.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 { estypes } from '@elastic/elasticsearch'; import { FieldSpec, IFieldSubType, IndexPattern } from '../..'; /** @@ -16,7 +16,7 @@ export interface IFieldType { name: string; type: string; script?: string; - lang?: string; + lang?: estypes.ScriptLanguage; count?: number; // esTypes might be undefined on old index patterns that have not been refreshed since we added // this prop. It is also undefined on scripted fields. diff --git a/src/plugins/data/common/index_patterns/types.ts b/src/plugins/data/common/index_patterns/types.ts index 0fcdea1a878ebc..07aa8967b905e4 100644 --- a/src/plugins/data/common/index_patterns/types.ts +++ b/src/plugins/data/common/index_patterns/types.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 { estypes } from '@elastic/elasticsearch'; import { ToastInputFields, ErrorToastOptions } from 'src/core/public/notifications'; // eslint-disable-next-line import type { SavedObject } from 'src/core/server'; @@ -167,7 +167,7 @@ export type FieldSpecConflictDescriptions = Record; export interface FieldSpecExportFmt { count?: number; script?: string; - lang?: string; + lang?: estypes.ScriptLanguage; conflictDescriptions?: FieldSpecConflictDescriptions; name: string; type: KBN_FIELD_TYPES; @@ -197,7 +197,7 @@ export interface FieldSpec { * Scripted field langauge * Painless is the only valid scripted field language */ - lang?: string; + lang?: estypes.ScriptLanguage; conflictDescriptions?: Record; format?: SerializedFieldFormat; name: string; diff --git a/src/plugins/data/common/search/aggs/agg_configs.ts b/src/plugins/data/common/search/aggs/agg_configs.ts index 6f8a8d38a4a286..8593a0b0ed0fa3 100644 --- a/src/plugins/data/common/search/aggs/agg_configs.ts +++ b/src/plugins/data/common/search/aggs/agg_configs.ts @@ -10,7 +10,7 @@ import moment from 'moment'; import _, { cloneDeep } from 'lodash'; import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { Aggregate, Bucket } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { IEsSearchResponse, @@ -57,7 +57,9 @@ export interface AggConfigsOptions { export type CreateAggConfigParams = Assign; -export type GenericBucket = Bucket & { [property: string]: Aggregate }; +export type GenericBucket = estypes.AggregationsBucket & { + [property: string]: estypes.AggregationsAggregate; +}; /** * @name AggConfigs @@ -412,7 +414,7 @@ export class AggConfigs { const transformedRawResponse = cloneDeep(response.rawResponse); if (!transformedRawResponse.aggregations) { transformedRawResponse.aggregations = { - doc_count: response.rawResponse.hits?.total as Aggregate, + doc_count: response.rawResponse.hits?.total as estypes.AggregationsAggregate, }; } const aggCursor = transformedRawResponse.aggregations!; 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 4ac47efaea3476..75c1c091e07561 100644 --- a/src/plugins/data/common/search/aggs/utils/time_splits.ts +++ b/src/plugins/data/common/search/aggs/utils/time_splits.ts @@ -8,12 +8,7 @@ import moment from 'moment'; import _, { isArray } from 'lodash'; -import { - Aggregate, - FiltersAggregate, - FiltersBucketItem, - MultiBucketAggregate, -} from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { AggGroupNames } from '../agg_groups'; import { GenericBucket, AggConfigs, getTime, AggConfig } from '../../../../common'; @@ -156,12 +151,15 @@ import { IBucketAggConfig } from '../buckets'; } // ... * ``` - * - * + * + * * @param aggConfigs The agg configs instance * @param aggCursor The root aggregations object from the response which will be mutated in place */ -export function mergeTimeShifts(aggConfigs: AggConfigs, aggCursor: Record) { +export function mergeTimeShifts( + aggConfigs: AggConfigs, + aggCursor: Record +) { const timeShifts = aggConfigs.getTimeShifts(); const hasMultipleTimeShifts = Object.keys(timeShifts).length > 1; const requestAggs = aggConfigs.getRequestAggs(); @@ -200,7 +198,7 @@ export function mergeTimeShifts(aggConfigs: AggConfigs, aggCursor: Record @@ -212,7 +210,7 @@ export function mergeTimeShifts(aggConfigs: AggConfigs, aggCursor: Record bucketAgg.type.orderBuckets(bucketAgg, a, b)); } else if (baseBuckets && buckets && !isArray(baseBuckets)) { @@ -249,7 +247,10 @@ export function mergeTimeShifts(aggConfigs: AggConfigs, aggCursor: Record, aggIndex: number): undefined => { + const transformTimeShift = ( + cursor: Record, + aggIndex: number + ): undefined => { const shouldSplit = aggConfigs.aggs[aggIndex].type.splitForTimeShift( aggConfigs.aggs[aggIndex], aggConfigs @@ -257,10 +258,8 @@ export function mergeTimeShifts(aggConfigs: AggConfigs, aggCursor: Record; + const timeShiftedBuckets = (cursor.time_offset_split as estypes.AggregationsFiltersAggregate) + .buckets as Record; const subTree = {}; Object.entries(timeShifts).forEach(([key, shift]) => { mergeAggLevel( @@ -301,7 +300,7 @@ export function mergeTimeShifts(aggConfigs: AggConfigs, aggCursor: Record { querySuggestionsArgs, mockKueryNode({ prefix, suffix }) ); + // @ts-expect-error indexPatternResponse is not properly typed json const filterableFields = indexPatternResponse.fields.filter(indexPatternsUtils.isFilterable); expect(suggestions.length).toBe(filterableFields.length); diff --git a/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md index 9f5c2ef5fad3df..5ef499840fa6de 100644 --- a/src/plugins/data/public/public.api.md +++ b/src/plugins/data/public/public.api.md @@ -7,13 +7,11 @@ import { $Values } from '@kbn/utility-types'; import { Action } from 'history'; import { Adapters as Adapters_2 } from 'src/plugins/inspector/common'; -import { Aggregate } from '@elastic/elasticsearch/api/types'; import { ApiResponse } from '@elastic/elasticsearch/lib/Transport'; import { ApplicationStart } from 'kibana/public'; import { Assign } from '@kbn/utility-types'; import { BfetchPublicSetup } from 'src/plugins/bfetch/public'; import Boom from '@hapi/boom'; -import { Bucket } from '@elastic/elasticsearch/api/types'; import { ConfigDeprecationProvider } from '@kbn/config'; import { CoreSetup } from 'src/core/public'; import { CoreSetup as CoreSetup_2 } from 'kibana/public'; @@ -1245,7 +1243,7 @@ export interface IFieldType { // (undocumented) format?: any; // (undocumented) - lang?: string; + lang?: estypes.ScriptLanguage; // (undocumented) name: string; // (undocumented) @@ -1520,8 +1518,8 @@ export class IndexPatternField implements IFieldType { // (undocumented) get filterable(): boolean; get isMapped(): boolean | undefined; - get lang(): string | undefined; - set lang(lang: string | undefined); + get lang(): "painless" | "expression" | "mustache" | "java" | undefined; + set lang(lang: "painless" | "expression" | "mustache" | "java" | undefined); // (undocumented) get name(): string; // (undocumented) @@ -1545,7 +1543,7 @@ export class IndexPatternField implements IFieldType { toJSON(): { count: number; script: string | undefined; - lang: string | undefined; + lang: "painless" | "expression" | "mustache" | "java" | undefined; conflictDescriptions: Record | undefined; name: string; type: string; @@ -1990,7 +1988,7 @@ export type PhraseFilter = Filter & { script?: { script: { source?: any; - lang?: string; + lang?: estypes.ScriptLanguage; params: any; }; }; @@ -2208,7 +2206,7 @@ export type RangeFilter = Filter & EsRangeFilter & { script?: { script: { params: any; - lang: string; + lang: estypes.ScriptLanguage; source: any; }; }; @@ -2254,7 +2252,7 @@ export interface Reason { reason: string; }; // (undocumented) - lang?: string; + lang?: estypes.ScriptLanguage; // (undocumented) position?: { offset: number; diff --git a/src/plugins/data/public/search/errors/painless_error.test.tsx b/src/plugins/data/public/search/errors/painless_error.test.tsx index f07f078ea03a3f..833573786594b2 100644 --- a/src/plugins/data/public/search/errors/painless_error.test.tsx +++ b/src/plugins/data/public/search/errors/painless_error.test.tsx @@ -23,6 +23,7 @@ describe('PainlessError', () => { const e = new PainlessError({ statusCode: 400, message: 'search_phase_execution_exception', + // @ts-expect-error searchPhaseException is not properly typed json attributes: searchPhaseException.error, }); const component = mount(e.getErrorMessage(startMock.application)); diff --git a/src/plugins/data/public/search/errors/types.ts b/src/plugins/data/public/search/errors/types.ts index 445293fe47ea35..13c5d0c242ed00 100644 --- a/src/plugins/data/public/search/errors/types.ts +++ b/src/plugins/data/public/search/errors/types.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 { estypes } from '@elastic/elasticsearch'; import { KibanaServerError } from '../../../../kibana_utils/common'; export interface FailedShard { @@ -24,7 +24,7 @@ export interface Reason { start: number; end: number; }; - lang?: string; + lang?: estypes.ScriptLanguage; script?: string; caused_by?: { type: string; diff --git a/src/plugins/data/public/search/search_interceptor/search_interceptor.test.ts b/src/plugins/data/public/search/search_interceptor/search_interceptor.test.ts index dfbc912453d6e0..fe66d4b6e99370 100644 --- a/src/plugins/data/public/search/search_interceptor/search_interceptor.test.ts +++ b/src/plugins/data/public/search/search_interceptor/search_interceptor.test.ts @@ -135,6 +135,7 @@ describe('SearchInterceptor', () => { new PainlessError({ statusCode: 400, message: 'search_phase_execution_exception', + // @ts-expect-error searchPhaseException is not properly typed json attributes: searchPhaseException.error, }) ); diff --git a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_types.ts b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_types.ts index c34a47dc1c6dd6..83e4abf55d5256 100644 --- a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_types.ts +++ b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_types.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 { estypes } from '@elastic/elasticsearch'; export interface ShardFailureRequest { docvalue_fields: string[]; _source: unknown; @@ -24,7 +24,7 @@ export interface ShardFailure { type: string; }; reason: string; - lang?: string; + lang?: estypes.ScriptLanguage; script?: string; script_stack?: string[]; type: string; diff --git a/src/plugins/data/server/autocomplete/value_suggestions_route.ts b/src/plugins/data/server/autocomplete/value_suggestions_route.ts index b2568a5a43611b..8fa14f8cbbd427 100644 --- a/src/plugins/data/server/autocomplete/value_suggestions_route.ts +++ b/src/plugins/data/server/autocomplete/value_suggestions_route.ts @@ -78,7 +78,7 @@ async function getBody( { timeout, terminate_after }: Record, field: IFieldType | string, query: string, - filters: estypes.QueryContainer[] = [] + filters: estypes.QueryDslQueryContainer[] = [] ) { const isFieldObject = (f: any): f is IFieldType => Boolean(f && f.name); diff --git a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts index c4c1ffa3cf9f91..6db9254b815280 100644 --- a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts +++ b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts @@ -69,7 +69,7 @@ import { FieldDescriptor } from '../../../fetcher'; * @return {Array} */ export function readFieldCapsResponse( - fieldCapsResponse: estypes.FieldCapabilitiesResponse + fieldCapsResponse: estypes.FieldCapsResponse ): FieldDescriptor[] { const capsByNameThenType = fieldCapsResponse.fields; diff --git a/src/plugins/data/server/search/routes/call_msearch.ts b/src/plugins/data/server/search/routes/call_msearch.ts index 0c238adf831bd9..4a7db9517c688b 100644 --- a/src/plugins/data/server/search/routes/call_msearch.ts +++ b/src/plugins/data/server/search/routes/call_msearch.ts @@ -8,7 +8,8 @@ import { Observable } from 'rxjs'; import { first } from 'rxjs/operators'; -import { IUiSettingsClient, IScopedClusterClient, SharedGlobalConfig } from 'src/core/server'; +import type { IUiSettingsClient, IScopedClusterClient, SharedGlobalConfig } from 'src/core/server'; +import type { estypes } from '@elastic/elasticsearch'; import type { MsearchRequestBody, MsearchResponse } from '../../../common/search/search_source'; import { getKbnServerError } from '../../../../kibana_utils/server'; @@ -78,7 +79,9 @@ export function getCallMsearch(dependencies: CallMsearchDependencies) { body: { ...response, body: { - responses: response.body.responses?.map((r) => shimHitsTotal(r)), + responses: response.body.responses?.map((r) => + shimHitsTotal(r as estypes.SearchResponse) + ), }, }, }; diff --git a/src/plugins/data/server/search/routes/msearch.test.ts b/src/plugins/data/server/search/routes/msearch.test.ts index 6ae8612cceb1e9..303f83582f737e 100644 --- a/src/plugins/data/server/search/routes/msearch.test.ts +++ b/src/plugins/data/server/search/routes/msearch.test.ts @@ -116,7 +116,7 @@ describe('msearch route', () => { const error: any = mockResponse.customError.mock.calls[0][0]; expect(error.statusCode).toBe(400); - expect(error.body.message).toBe('json_e_o_f_exception'); + expect(error.body.message).toMatch(/json_e_o_f_exception/); expect(error.body.attributes).toBe(jsonEofException.error); }); diff --git a/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts b/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts index 0e3acedfe12f67..91de0fca3674c9 100644 --- a/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts +++ b/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts @@ -54,7 +54,8 @@ export const eqlSearchStrategyProvider = ( }; const promise = id ? client.get({ ...params, id }, request.options) - : client.search(params as EqlSearchStrategyRequest['params'], request.options); + : // @ts-expect-error EqlRequestParams | undefined is not assignable to EqlRequestParams + client.search(params as EqlSearchStrategyRequest['params'], request.options); const response = await shimAbortSignal(promise, options.abortSignal); return toEqlKibanaSearchResponse(response as ApiResponse); }; 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 216318339622f0..56b26a7ebe02cc 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 @@ -293,7 +293,7 @@ describe('ES search strategy', () => { expect(mockGetCaller).toBeCalled(); const request = mockGetCaller.mock.calls[0][0]; - expect(request).toEqual({ id, body: { keep_alive: keepAlive } }); + expect(request).toEqual({ id, keep_alive: keepAlive }); }); it('throws normalized error on ElasticsearchClientError', async () => { diff --git a/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts index ab6162f756ea89..d6af00ada80fa6 100644 --- a/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts +++ b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts @@ -177,7 +177,7 @@ export const enhancedEsSearchStrategyProvider = ( const client = useInternalUser ? esClient.asInternalUser : esClient.asCurrentUser; await client.asyncSearch.get({ id, - body: { keep_alive: keepAlive }, + keep_alive: keepAlive, }); } catch (e) { throw getKbnServerError(e); diff --git a/src/plugins/data/server/server.api.md b/src/plugins/data/server/server.api.md index f57ba274881033..ff265ccf533015 100644 --- a/src/plugins/data/server/server.api.md +++ b/src/plugins/data/server/server.api.md @@ -6,10 +6,8 @@ import { $Values } from '@kbn/utility-types'; import { Adapters } from 'src/plugins/inspector/common'; -import { Aggregate } from '@elastic/elasticsearch/api/types'; import { Assign } from '@kbn/utility-types'; import { BfetchServerSetup } from 'src/plugins/bfetch/server'; -import { Bucket } from '@elastic/elasticsearch/api/types'; import { ConfigDeprecationProvider } from '@kbn/config'; import { CoreSetup } from 'src/core/server'; import { CoreSetup as CoreSetup_2 } from 'kibana/server'; @@ -713,7 +711,7 @@ export interface IFieldType { // (undocumented) format?: any; // (undocumented) - lang?: string; + lang?: estypes.ScriptLanguage; // (undocumented) name: string; // (undocumented) @@ -1420,22 +1418,22 @@ export const shimAbortSignal: (promise: TransportRequestPromise, signal?: export function shimHitsTotal(response: estypes.SearchResponse, { legacyHitsTotal }?: ISearchOptions): { hits: { total: any; - hits: estypes.Hit[]; + hits: estypes.SearchHit[]; max_score?: number | undefined; }; took: number; timed_out: boolean; _shards: estypes.ShardStatistics; - aggregations?: Record | undefined; + aggregations?: Record | undefined; _clusters?: estypes.ClusterStatistics | undefined; documents?: unknown[] | undefined; fields?: Record | undefined; max_score?: number | undefined; num_reduce_phases?: number | undefined; - profile?: estypes.Profile | undefined; + profile?: estypes.SearchProfile | undefined; pit_id?: string | undefined; _scroll_id?: string | undefined; - suggest?: Record[]> | undefined; + suggest?: Record[]> | undefined; terminated_early?: boolean | undefined; }; diff --git a/src/plugins/discover/public/application/angular/doc_table/create_doc_table_react.tsx b/src/plugins/discover/public/application/angular/doc_table/create_doc_table_react.tsx index 1135d79b6b69ee..681418c1bd7cfe 100644 --- a/src/plugins/discover/public/application/angular/doc_table/create_doc_table_react.tsx +++ b/src/plugins/discover/public/application/angular/doc_table/create_doc_table_react.tsx @@ -21,7 +21,7 @@ export interface DocTableLegacyProps { searchDescription?: string; searchTitle?: string; onFilter: (field: IndexPatternField | string, value: string, type: '+' | '-') => void; - rows: estypes.Hit[]; + rows: estypes.SearchHit[]; indexPattern: IIndexPattern; minimumVisibleRows?: number; onAddColumn?: (column: string) => void; diff --git a/src/plugins/discover/public/application/components/doc/use_es_doc_search.ts b/src/plugins/discover/public/application/components/doc/use_es_doc_search.ts index 6b8e912bbffba4..7a3320d43c8b51 100644 --- a/src/plugins/discover/public/application/components/doc/use_es_doc_search.ts +++ b/src/plugins/discover/public/application/components/doc/use_es_doc_search.ts @@ -33,7 +33,7 @@ export function buildSearchBody( useNewFieldsApi: boolean ): RequestBody | undefined { const computedFields = indexPattern.getComputedFields(); - const runtimeFields = computedFields.runtimeFields as estypes.RuntimeFields; + const runtimeFields = computedFields.runtimeFields as estypes.MappingRuntimeFields; const request: RequestBody = { body: { query: { diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/confirmation_modal/confirmation_modal.test.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/confirmation_modal/confirmation_modal.test.tsx index 96f78a088fff49..bacab18d285095 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/confirmation_modal/confirmation_modal.test.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/confirmation_modal/confirmation_modal.test.tsx @@ -15,6 +15,7 @@ describe('DeleteScritpedFieldConfirmationModal', () => { test('should render normally', () => { const component = shallow( {}} hideDeleteConfirmationModal={() => {}} diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/table/table.test.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/table/table.test.tsx index 83ac96f6c1695b..5a9f4eb8711816 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/table/table.test.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/table/table.test.tsx @@ -15,6 +15,7 @@ import { IIndexPattern } from 'src/plugins/data/public'; const getIndexPatternMock = (mockedFields: any = {}) => ({ ...mockedFields } as IIndexPattern); +// @ts-expect-error invalid lang type const items: ScriptedFieldItem[] = [{ name: '1', lang: 'Elastic', script: '' }]; describe('Table', () => { 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 08a5f22723628c..e6aa87172ca0b7 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 @@ -155,6 +155,7 @@ describe('ScriptedFieldsTable', () => { ); await component.update(); // Fire `componentWillMount()` + // @ts-expect-error lang is not valid component.instance().startDeleteField({ name: 'ScriptedField', lang: '', script: '' }); await component.update(); @@ -179,6 +180,7 @@ describe('ScriptedFieldsTable', () => { ); await component.update(); // Fire `componentWillMount()` + // @ts-expect-error lang is not valid component.instance().startDeleteField({ name: 'ScriptedField', lang: '', script: '' }); await component.update(); diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx index 77ba2f734d3fea..7fd5170b669f7c 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx @@ -65,7 +65,7 @@ export class ScriptedFieldsTable extends Component< const supportedLangs = getSupportedScriptingLanguages(); for (const field of fields) { - const lang: string = field.lang; + const lang = field.lang; if (deprecatedLangs.includes(lang) || !supportedLangs.includes(lang)) { deprecatedLangsInUse.push(lang); } diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/types.ts b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/types.ts index 3348f5eb052eb7..5c6adc824d225e 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/types.ts +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/types.ts @@ -5,10 +5,10 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - +import type { estypes } from '@elastic/elasticsearch'; /** @internal **/ export interface ScriptedFieldItem { name: string; - lang: string; + lang: estypes.ScriptLanguage; script: string; } diff --git a/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx b/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx index f0da57a5f9b6f3..b05ddaed064cdc 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx @@ -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 { estypes } from '@elastic/elasticsearch'; import React, { PureComponent, Fragment } from 'react'; import { intersection, union, get } from 'lodash'; @@ -100,7 +100,7 @@ export interface FieldEditorState { isReady: boolean; isCreating: boolean; isDeprecatedLang: boolean; - scriptingLangs: string[]; + scriptingLangs: estypes.ScriptLanguage[]; fieldTypes: string[]; fieldTypeFormats: FieldTypeFormat[]; existingFieldNames: string[]; @@ -131,8 +131,8 @@ export class FieldEditor extends PureComponent { + onLangChange = (lang: estypes.ScriptLanguage) => { const { spec } = this.state; const fieldTypes = get(FIELD_TYPES_BY_LANG, lang, DEFAULT_FIELD_TYPES); spec.lang = lang; @@ -373,7 +374,7 @@ export class FieldEditor extends PureComponent { - this.onLangChange(e.target.value); + this.onLangChange(e.target.value as estypes.ScriptLanguage); }} /> diff --git a/src/plugins/index_pattern_management/public/scripting_languages/index.ts b/src/plugins/index_pattern_management/public/scripting_languages/index.ts index c6b2f3c4b6b27a..aeb38c8172be02 100644 --- a/src/plugins/index_pattern_management/public/scripting_languages/index.ts +++ b/src/plugins/index_pattern_management/public/scripting_languages/index.ts @@ -5,15 +5,15 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { HttpStart, NotificationsStart } from 'src/core/public'; -export function getSupportedScriptingLanguages(): string[] { +export function getSupportedScriptingLanguages(): estypes.ScriptLanguage[] { return ['painless']; } -export function getDeprecatedScriptingLanguages(): string[] { +export function getDeprecatedScriptingLanguages(): estypes.ScriptLanguage[] { return []; } 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 7fd6ca4080d6af..bacfa5e77107fe 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 @@ -188,7 +188,7 @@ describe('get_local_stats', () => { describe('handleLocalStats', () => { it('returns expected object without xpack or kibana data', () => { const result = handleLocalStats( - clusterInfo as estypes.RootNodeInfoResponse, + clusterInfo as estypes.InfoResponse, clusterStatsWithNodesUsage, void 0, void 0, @@ -205,7 +205,7 @@ describe('get_local_stats', () => { it('returns expected object with xpack', () => { const result = handleLocalStats( - clusterInfo as estypes.RootNodeInfoResponse, + clusterInfo as estypes.InfoResponse, clusterStatsWithNodesUsage, void 0, void 0, diff --git a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts index 7fdcb50b704afe..7860949e098aa1 100644 --- a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts +++ b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts @@ -28,7 +28,7 @@ import { getDataTelemetry, DATA_TELEMETRY_ID, DataTelemetryPayload } from './get */ export function handleLocalStats( // eslint-disable-next-line @typescript-eslint/naming-convention - { cluster_name, cluster_uuid, version }: estypes.RootNodeInfoResponse, + { cluster_name, cluster_uuid, version }: estypes.InfoResponse, { _nodes, cluster_name: clusterName, ...clusterStats }: ClusterStats, kibana: KibanaUsageStats | undefined, dataTelemetry: DataTelemetryPayload | undefined, diff --git a/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts b/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts index c35b8a3d24498e..0d58d80ed59653 100644 --- a/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts +++ b/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts @@ -14,7 +14,7 @@ import { TIMEOUT } from './constants'; * Data returned by GET /_nodes/usage, but flattened as an array of {@link estypes.NodeUsageInformation} * with the node ID set in the field `node_id`. */ -export interface NodeUsage extends estypes.NodeUsageInformation { +export interface NodeUsage extends estypes.NodesUsageNodeUsage { /** * The Node ID as reported by ES */ diff --git a/src/plugins/vis_type_timeseries/common/fields_utils.test.ts b/src/plugins/vis_type_timeseries/common/fields_utils.test.ts index 9550697e228512..f056c38b0c0c30 100644 --- a/src/plugins/vis_type_timeseries/common/fields_utils.test.ts +++ b/src/plugins/vis_type_timeseries/common/fields_utils.test.ts @@ -12,7 +12,7 @@ import type { FieldSpec } from '../../data/common'; describe('fields_utils', () => { describe('toSanitizedFieldType', () => { const mockedField = { - lang: 'lang', + lang: 'painless', conflictDescriptions: {}, aggregatable: true, name: 'name', diff --git a/src/plugins/vis_type_vega/public/data_model/types.ts b/src/plugins/vis_type_vega/public/data_model/types.ts index 255bd9774f9df8..9e3cf0a5421c1c 100644 --- a/src/plugins/vis_type_vega/public/data_model/types.ts +++ b/src/plugins/vis_type_vega/public/data_model/types.ts @@ -17,7 +17,7 @@ import { EmsFileParser } from './ems_file_parser'; import { UrlParser } from './url_parser'; interface Body { - aggs?: Record; + aggs?: Record; query?: Query; timeout?: string; } diff --git a/test/api_integration/apis/saved_objects/migrations.ts b/test/api_integration/apis/saved_objects/migrations.ts index d009a66e9df55f..0877998ca6c1f3 100644 --- a/test/api_integration/apis/saved_objects/migrations.ts +++ b/test/api_integration/apis/saved_objects/migrations.ts @@ -87,7 +87,7 @@ export default ({ getService }: FtrProviderContext) => { const mappingProperties = { foo: { properties: { name: { type: 'text' } } }, bar: { properties: { mynum: { type: 'integer' } } }, - }; + } as const; const savedObjectTypes: SavedObjectsType[] = [ { @@ -221,7 +221,7 @@ export default ({ getService }: FtrProviderContext) => { const mappingProperties = { foo: { properties: { name: { type: 'text' } } }, bar: { properties: { mynum: { type: 'integer' } } }, - }; + } as const; let savedObjectTypes: SavedObjectsType[] = [ { @@ -357,7 +357,7 @@ export default ({ getService }: FtrProviderContext) => { const mappingProperties = { 'fleet-agent-event': { properties: { name: { type: 'text' } } }, bar: { properties: { mynum: { type: 'integer' } } }, - }; + } as const; let savedObjectTypes: SavedObjectsType[] = [ FLEET_AGENT_EVENT_TYPE, @@ -417,7 +417,7 @@ export default ({ getService }: FtrProviderContext) => { const mappingProperties = { foo: { properties: { name: { type: 'text' } } }, - }; + } as const; const savedObjectTypes: SavedObjectsType[] = [ { @@ -510,7 +510,7 @@ export default ({ getService }: FtrProviderContext) => { foo: { properties: { name: { type: 'text' } } }, bar: { properties: { nomnom: { type: 'integer' } } }, baz: { properties: { title: { type: 'keyword' } } }, - }; + } as const; const savedObjectTypes: SavedObjectsType[] = [ { @@ -677,7 +677,7 @@ async function createIndex({ coreMigrationVersion: { type: 'keyword', }, - }; + } as const; await esClient.indices.create({ index, body: { mappings: { dynamic: 'strict', properties } }, diff --git a/test/api_integration/apis/search/verify_error.ts b/test/api_integration/apis/search/verify_error.ts index d6b729f59d8d4e..1973fe4e4ab361 100644 --- a/test/api_integration/apis/search/verify_error.ts +++ b/test/api_integration/apis/search/verify_error.ts @@ -16,7 +16,7 @@ export const verifyErrorResponse = ( ) => { expect(r.statusCode).to.be(expectedCode); if (message) { - expect(r.message).to.be(message); + expect(r.message).to.include.string(message); } if (shouldHaveAttrs) { expect(r).to.have.property('attributes'); diff --git a/test/common/services/saved_object_info.ts b/test/common/services/saved_object_info.ts index 1558b364f53916..2be17636508942 100644 --- a/test/common/services/saved_object_info.ts +++ b/test/common/services/saved_object_info.ts @@ -8,7 +8,7 @@ import { inspect } from 'util'; -import { TermsAggregate } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { FtrService } from '../ftr_provider_context'; @@ -32,7 +32,7 @@ export class SavedObjectInfoService extends FtrService { }); const agg = body.aggregations?.savedobjs as - | TermsAggregate<{ key: string; doc_count: number }> + | estypes.AggregationsTermsAggregate<{ key: string; doc_count: number }> | undefined; if (!agg?.buckets) { diff --git a/typings/elasticsearch/index.d.ts b/typings/elasticsearch/index.d.ts index 7eaf762d353ac4..1951434890c50f 100644 --- a/typings/elasticsearch/index.d.ts +++ b/typings/elasticsearch/index.d.ts @@ -8,9 +8,9 @@ import { estypes } from '@elastic/elasticsearch'; import { InferSearchResponseOf, AggregateOf as AggregationResultOf, SearchHit } from './search'; -export type ESFilter = estypes.QueryContainer; +export type ESFilter = estypes.QueryDslQueryContainer; export type ESSearchRequest = estypes.SearchRequest; -export type AggregationOptionsByType = Required; +export type AggregationOptionsByType = Required; // Typings for Elasticsearch queries and aggregations. These are intended to be // moved to the Elasticsearch JS client at some point (see #77720.) diff --git a/typings/elasticsearch/search.d.ts b/typings/elasticsearch/search.d.ts index d75f31d388176d..36a684fb097a51 100644 --- a/typings/elasticsearch/search.d.ts +++ b/typings/elasticsearch/search.d.ts @@ -28,14 +28,14 @@ type KeysOfSources = T extends [infer U, ...infer V] : {}; type CompositeKeysOf< - TAggregationContainer extends estypes.AggregationContainer + TAggregationContainer extends estypes.AggregationsAggregationContainer > = TAggregationContainer extends { composite: { sources: [...infer TSource] }; } ? KeysOfSources : unknown; -type Source = estypes.SourceFilter | boolean | estypes.Fields; +type Source = estypes.SearchSourceFilter | boolean | estypes.Fields; type ValueTypeOfField = T extends Record ? ValuesType @@ -50,13 +50,13 @@ type ValueTypeOfField = T extends Record type MaybeArray = T | T[]; type Fields = Exclude['body']['fields'], undefined>; -type DocValueFields = MaybeArray; +type DocValueFields = MaybeArray; export type SearchHit< TSource extends any = unknown, TFields extends Fields | undefined = undefined, TDocValueFields extends DocValueFields | undefined = undefined -> = Omit & +> = Omit & (TSource extends false ? {} : { _source: TSource }) & (TFields extends Fields ? { @@ -82,11 +82,17 @@ type HitsOf< > >; -type AggregationTypeName = Exclude; +type AggregationTypeName = Exclude< + keyof estypes.AggregationsAggregationContainer, + 'aggs' | 'aggregations' +>; -type AggregationMap = Partial>; +type AggregationMap = Partial>; -type TopLevelAggregationRequest = Pick; +type TopLevelAggregationRequest = Pick< + estypes.AggregationsAggregationContainer, + 'aggs' | 'aggregations' +>; type MaybeKeyed< TAggregationContainer, @@ -97,7 +103,7 @@ type MaybeKeyed< : { buckets: TBucket[] }; export type AggregateOf< - TAggregationContainer extends estypes.AggregationContainer, + TAggregationContainer extends estypes.AggregationsAggregationContainer, TDocument > = (Record & { adjacency_matrix: { @@ -518,9 +524,9 @@ export type AggregateOf< relation: 'eq' | 'gte'; }; max_score: number | null; - hits: TAggregationContainer extends { top_hits: estypes.TopHitsAggregation } + hits: TAggregationContainer extends { top_hits: estypes.AggregationsTopHitsAggregation } ? HitsOf - : estypes.HitsMetadata; + : estypes.SearchHitsMetadata; }; }; top_metrics: { @@ -542,7 +548,7 @@ export type AggregateOf< })[ValidAggregationKeysOf & AggregationTypeName]; type AggregateOfMap = { - [TAggregationName in keyof TAggregationMap]: TAggregationMap[TAggregationName] extends estypes.AggregationContainer + [TAggregationName in keyof TAggregationMap]: TAggregationMap[TAggregationName] extends estypes.AggregationsAggregationContainer ? AggregateOf : never; // using never means we effectively ignore optional keys, using {} creates a union type of { ... } | {} }; diff --git a/x-pack/plugins/actions/server/actions_client.ts b/x-pack/plugins/actions/server/actions_client.ts index c655141415b548..449d218ed5ae04 100644 --- a/x-pack/plugins/actions/server/actions_client.ts +++ b/x-pack/plugins/actions/server/actions_client.ts @@ -515,7 +515,7 @@ async function injectExtraFindData( scopedClusterClient: IScopedClusterClient, actionResults: ActionResult[] ): Promise { - const aggs: Record = {}; + const aggs: Record = {}; for (const actionResult of actionResults) { aggs[actionResult.id] = { filter: { diff --git a/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.ts b/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.ts index fe9874fb1d671a..28b904361e6774 100644 --- a/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.ts +++ b/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.ts @@ -56,6 +56,7 @@ async function createIndexTemplate({ await client.indices.putIndexTemplate({ name: templateName, body: template, + // @ts-expect-error doesn't exist in @elastic/elasticsearch create: true, }); } catch (err) { diff --git a/x-pack/plugins/actions/server/saved_objects/index.ts b/x-pack/plugins/actions/server/saved_objects/index.ts index 9360bc919a2d50..9d8c3640079596 100644 --- a/x-pack/plugins/actions/server/saved_objects/index.ts +++ b/x-pack/plugins/actions/server/saved_objects/index.ts @@ -5,10 +5,11 @@ * 2.0. */ -import { +import type { SavedObject, SavedObjectsExportTransformContext, SavedObjectsServiceSetup, + SavedObjectsTypeMappingDefinition, } from 'kibana/server'; import { EncryptedSavedObjectsPluginSetup } from '../../../encrypted_saved_objects/server'; import mappings from './mappings.json'; @@ -31,7 +32,7 @@ export function setupSavedObjects( name: ACTION_SAVED_OBJECT_TYPE, hidden: true, namespaceType: 'single', - mappings: mappings.action, + mappings: mappings.action as SavedObjectsTypeMappingDefinition, migrations: getMigrations(encryptedSavedObjects), management: { defaultSearchField: 'name', @@ -67,7 +68,7 @@ export function setupSavedObjects( name: ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, hidden: true, namespaceType: 'single', - mappings: mappings.action_task_params, + mappings: mappings.action_task_params as SavedObjectsTypeMappingDefinition, }); encryptedSavedObjects.registerType({ type: ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, diff --git a/x-pack/plugins/alerting/server/alerts_client/alerts_client.ts b/x-pack/plugins/alerting/server/alerts_client/alerts_client.ts index b8df0c3d8de097..c81fa7927ef7df 100644 --- a/x-pack/plugins/alerting/server/alerts_client/alerts_client.ts +++ b/x-pack/plugins/alerting/server/alerts_client/alerts_client.ts @@ -109,7 +109,7 @@ export interface FindOptions extends IndexType { defaultSearchOperator?: 'AND' | 'OR'; searchFields?: string[]; sortField?: string; - sortOrder?: estypes.SortOrder; + sortOrder?: estypes.SearchSortOrder; hasReference?: { type: string; id: string; diff --git a/x-pack/plugins/alerting/server/saved_objects/index.ts b/x-pack/plugins/alerting/server/saved_objects/index.ts index c339183eeedcdb..1ad0f972b2ec01 100644 --- a/x-pack/plugins/alerting/server/saved_objects/index.ts +++ b/x-pack/plugins/alerting/server/saved_objects/index.ts @@ -5,10 +5,11 @@ * 2.0. */ -import { +import type { SavedObject, SavedObjectsExportTransformContext, SavedObjectsServiceSetup, + SavedObjectsTypeMappingDefinition, } from 'kibana/server'; import mappings from './mappings.json'; import { getMigrations } from './migrations'; @@ -51,7 +52,7 @@ export function setupSavedObjects( hidden: true, namespaceType: 'single', migrations: getMigrations(encryptedSavedObjects), - mappings: mappings.alert, + mappings: mappings.alert as SavedObjectsTypeMappingDefinition, ...(config.enableImportExport ? { management: { diff --git a/x-pack/plugins/apm/scripts/create-functional-tests-archive/index.ts b/x-pack/plugins/apm/scripts/create-functional-tests-archive/index.ts index 7f62fd39980606..18cb641bd4e658 100644 --- a/x-pack/plugins/apm/scripts/create-functional-tests-archive/index.ts +++ b/x-pack/plugins/apm/scripts/create-functional-tests-archive/index.ts @@ -10,7 +10,7 @@ import { execSync } from 'child_process'; import moment from 'moment'; import path from 'path'; import fs from 'fs'; -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { getEsClient } from '../shared/get_es_client'; import { parseIndexUrl } from '../shared/parse_index_url'; @@ -117,7 +117,7 @@ async function run() { const query = { bool: { - should: should.map(({ bool }) => ({ bool })) as QueryContainer[], + should: should.map(({ bool }) => ({ bool })) as QueryDslQueryContainer[], minimum_should_match: 1, }, }; 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 508b9419344cde..091982598d6a3e 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 @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { PROCESSOR_EVENT, SERVICE_NAME, @@ -45,7 +45,7 @@ export function getTransactionDurationChartPreview({ : []), ...rangeQuery(start, end), ...environmentQuery(environment), - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }; 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 f77cc3ee930b16..3e870eb3e32c61 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 @@ -7,7 +7,7 @@ import { schema } from '@kbn/config-schema'; import { take } from 'rxjs/operators'; -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { ALERT_EVALUATION_THRESHOLD, ALERT_EVALUATION_VALUE, @@ -109,7 +109,7 @@ export function registerTransactionDurationAlertType({ }, }, ...environmentQuery(alertParams.environment), - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }, aggs: { 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 399fb9a216ef50..4cc2324f47b9dd 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 @@ -8,7 +8,7 @@ import { schema } from '@kbn/config-schema'; import { compact } from 'lodash'; import { ESSearchResponse } from 'typings/elasticsearch'; -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { ALERT_EVALUATION_THRESHOLD, ALERT_EVALUATION_VALUE, @@ -157,7 +157,7 @@ export function registerTransactionDurationAnomalyAlertType({ }, ] : []), - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }, aggs: { 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 e2a39b521466a4..3d5b4b754e4aa5 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 @@ -5,7 +5,7 @@ * 2.0. */ import { flatten, merge, sortBy, sum, pickBy } from 'lodash'; -import { CompositeAggregationSource } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { asMutableArray } from '../../../../common/utils/as_mutable_array'; import { ProcessorEvent } from '../../../../common/processor_event'; import { TelemetryTask } from '.'; @@ -59,7 +59,7 @@ export const tasks: TelemetryTask[] = [ // the transaction count for that time range. executor: async ({ indices, search }) => { async function getBucketCountFromPaginatedQuery( - sources: CompositeAggregationSource[], + sources: estypes.AggregationsCompositeAggregationSource[], prevResult?: { transaction_count: number; expected_metric_document_count: number; diff --git a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts index 9d7434d127ead0..1544538de74a65 100644 --- a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts +++ b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts @@ -6,11 +6,7 @@ */ import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport'; -import { - CreateIndexRequest, - DeleteRequest, - IndexRequest, -} from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { unwrapEsResponse } from '../../../../../../observability/server'; import { APMRouteHandlerResources } from '../../../../routes/typings'; import { @@ -24,7 +20,7 @@ import { } from '../call_async_with_debug'; import { cancelEsRequestOnAbort } from '../cancel_es_request_on_abort'; -export type APMIndexDocumentParams = IndexRequest; +export type APMIndexDocumentParams = estypes.IndexRequest; export type APMInternalClient = ReturnType; @@ -78,14 +74,14 @@ export function createInternalESClient({ params, }); }, - delete: (params: DeleteRequest): Promise<{ result: string }> => { + delete: (params: estypes.DeleteRequest): Promise<{ result: string }> => { return callEs({ requestType: 'delete', cb: () => asInternalUser.delete(params), params, }); }, - indicesCreate: (params: CreateIndexRequest) => { + indicesCreate: (params: estypes.IndicesCreateRequest) => { return callEs({ requestType: 'indices.create', cb: () => asInternalUser.indices.create(params), diff --git a/x-pack/plugins/apm/server/lib/metrics/by_agent/shared/memory/index.ts b/x-pack/plugins/apm/server/lib/metrics/by_agent/shared/memory/index.ts index c58fb170bd2b0e..0ec2f2c2fcfb25 100644 --- a/x-pack/plugins/apm/server/lib/metrics/by_agent/shared/memory/index.ts +++ b/x-pack/plugins/apm/server/lib/metrics/by_agent/shared/memory/index.ts @@ -46,7 +46,7 @@ const chartBase: ChartBase = { export const percentSystemMemoryUsedScript = { lang: 'expression', source: `1 - doc['${METRIC_SYSTEM_FREE_MEMORY}'] / doc['${METRIC_SYSTEM_TOTAL_MEMORY}']`, -}; +} as const; export const percentCgroupMemoryUsedScript = { lang: 'painless', @@ -68,7 +68,7 @@ export const percentCgroupMemoryUsedScript = { return used / total; `, -}; +} as const; export async function getMemoryChartData({ environment, diff --git a/x-pack/plugins/apm/server/lib/service_map/fetch_service_paths_from_trace_ids.ts b/x-pack/plugins/apm/server/lib/service_map/fetch_service_paths_from_trace_ids.ts index 64de74fb9023b1..6047b97651e6ad 100644 --- a/x-pack/plugins/apm/server/lib/service_map/fetch_service_paths_from_trace_ids.ts +++ b/x-pack/plugins/apm/server/lib/service_map/fetch_service_paths_from_trace_ids.ts @@ -211,7 +211,7 @@ export async function fetchServicePathsFromTraceIds( }, }, }, - }, + } as const, }, }; 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 bcddbff34a8f64..129a0ee73b8cb3 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 @@ -64,7 +64,7 @@ export async function getServiceAnomalies({ by_field_value: [TRANSACTION_REQUEST, TRANSACTION_PAGE_LOAD], }, }, - ] as estypes.QueryContainer[], + ] as estypes.QueryDslQueryContainer[], }, }, aggs: { @@ -74,7 +74,9 @@ export async function getServiceAnomalies({ sources: [ { serviceName: { terms: { field: 'partition_field_value' } } }, { jobId: { terms: { field: 'job_id' } } }, - ] as Array>, + ] as Array< + Record + >, }, aggs: { metrics: { 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 c1dfed377a7638..9850c36c573dd7 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 @@ -224,7 +224,9 @@ function getMemoryStats({ script, }: { additionalFilters: ESFilter[]; - script: typeof percentCgroupMemoryUsedScript; + script: + | typeof percentCgroupMemoryUsedScript + | typeof percentSystemMemoryUsedScript; }) => { return withApmSpan('get_avg_memory_for_service_map_node', async () => { const response = await apmEventClient.search({ diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/create_agent_config_index.ts b/x-pack/plugins/apm/server/lib/settings/agent_configuration/create_agent_config_index.ts index 7ec850717dab1c..f43938891f1f00 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/create_agent_config_index.ts +++ b/x-pack/plugins/apm/server/lib/settings/agent_configuration/create_agent_config_index.ts @@ -36,10 +36,11 @@ const mappings: Mappings = { dynamic_templates: [ { // force string to keyword (instead of default of text + keyword) + // @ts-expect-error @elastic/elasticsearch expects here mapping: MappingPropertyBase strings: { match_mapping_type: 'string', mapping: { - type: 'keyword', + type: 'keyword' as const, ignore_above: 1024, }, }, diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/create_custom_link_index.ts b/x-pack/plugins/apm/server/lib/settings/custom_link/create_custom_link_index.ts index 3965e363499fc7..085bb2b4be40df 100644 --- a/x-pack/plugins/apm/server/lib/settings/custom_link/create_custom_link_index.ts +++ b/x-pack/plugins/apm/server/lib/settings/custom_link/create_custom_link_index.ts @@ -6,7 +6,7 @@ */ import { ElasticsearchClient, Logger } from 'src/core/server'; -import { PropertyBase } from '@elastic/elasticsearch/api/types'; +import { estypes } from '@elastic/elasticsearch'; import { createOrUpdateIndex, Mappings, @@ -47,7 +47,7 @@ const mappings: Mappings = { }, }, // FIXME: PropertyBase type is missing .fields - } as PropertyBase, + } as estypes.MappingPropertyBase, url: { type: 'keyword', }, diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.ts b/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.ts index f6b41f462c99ff..0eac2e08d0901e 100644 --- a/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.ts +++ b/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.ts @@ -6,7 +6,7 @@ */ import * as t from 'io-ts'; -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { CustomLink, CustomLinkES, @@ -32,7 +32,7 @@ export function listCustomLinks({ should: [ { term: { [key]: value } }, { bool: { must_not: [{ exists: { field: key } }] } }, - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }; }); diff --git a/x-pack/plugins/apm/server/lib/traces/get_trace_items.ts b/x-pack/plugins/apm/server/lib/traces/get_trace_items.ts index a946fa66a3b92e..157f09978eaec6 100644 --- a/x-pack/plugins/apm/server/lib/traces/get_trace_items.ts +++ b/x-pack/plugins/apm/server/lib/traces/get_trace_items.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { ProcessorEvent } from '../../../common/processor_event'; import { TRACE_ID, @@ -76,7 +76,7 @@ export async function getTraceItems( filter: [ { term: { [TRACE_ID]: traceId } }, ...rangeQuery(start, end), - ] as QueryContainer[], + ] as QueryDslQueryContainer[], should: { exists: { field: PARENT_ID }, }, diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/get_transaction_group_stats.ts b/x-pack/plugins/apm/server/lib/transaction_groups/get_transaction_group_stats.ts index 86be82faee5782..8156d52d984dfe 100644 --- a/x-pack/plugins/apm/server/lib/transaction_groups/get_transaction_group_stats.ts +++ b/x-pack/plugins/apm/server/lib/transaction_groups/get_transaction_group_stats.ts @@ -23,7 +23,10 @@ type BucketKey = string | Record; function mergeRequestWithAggs< TRequestBase extends TransactionGroupRequestBase, - TAggregationMap extends Record + TAggregationMap extends Record< + string, + estypes.AggregationsAggregationContainer + > >(request: TRequestBase, aggs: TAggregationMap) { return merge({}, request, { body: { diff --git a/x-pack/plugins/apm/server/lib/transactions/distribution/get_buckets/index.ts b/x-pack/plugins/apm/server/lib/transactions/distribution/get_buckets/index.ts index 1a586d1d4dbb6a..3b4319c37996dc 100644 --- a/x-pack/plugins/apm/server/lib/transactions/distribution/get_buckets/index.ts +++ b/x-pack/plugins/apm/server/lib/transactions/distribution/get_buckets/index.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { withApmSpan } from '../../../../utils/with_apm_span'; import { SERVICE_NAME, @@ -86,7 +86,7 @@ export async function getBuckets({ ...rangeQuery(start, end), ...environmentQuery(environment), ...kqlQuery(kuery), - ] as QueryContainer[]; + ] as QueryDslQueryContainer[]; async function getSamplesForDistributionBuckets() { const response = await withApmSpan( @@ -106,7 +106,7 @@ export async function getBuckets({ should: [ { term: { [TRACE_ID]: traceId } }, { term: { [TRANSACTION_ID]: transactionId } }, - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }, aggs: { 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 8b068fd6bd2fb2..b105f3b5c0a307 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 @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { ESSearchResponse } from '../../../../../../../typings/elasticsearch'; import { PromiseReturnType } from '../../../../../observability/typings/common'; import { rangeQuery } from '../../../../server/utils/queries'; @@ -44,7 +44,7 @@ export function anomalySeriesFetcher({ { term: { partition_field_value: serviceName } }, { term: { by_field_value: transactionType } }, ...rangeQuery(start, end, 'timestamp'), - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }, aggs: { diff --git a/x-pack/plugins/apm/server/projections/metrics.ts b/x-pack/plugins/apm/server/projections/metrics.ts index 68056f091c8738..9a757893337e5a 100644 --- a/x-pack/plugins/apm/server/projections/metrics.ts +++ b/x-pack/plugins/apm/server/projections/metrics.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { Setup, SetupTimeRange } from '../../server/lib/helpers/setup_request'; import { SERVICE_NAME, @@ -52,7 +52,7 @@ export function getMetricsProjection({ ...rangeQuery(start, end), ...environmentQuery(environment), ...kqlQuery(kuery), - ] as QueryContainer[]; + ] as QueryDslQueryContainer[]; return { apm: { diff --git a/x-pack/plugins/apm/server/projections/transactions.ts b/x-pack/plugins/apm/server/projections/transactions.ts index dd16b0b910abfe..3e830403debb0d 100644 --- a/x-pack/plugins/apm/server/projections/transactions.ts +++ b/x-pack/plugins/apm/server/projections/transactions.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { Setup, SetupTimeRange } from '../../server/lib/helpers/setup_request'; import { SERVICE_NAME, @@ -62,7 +62,7 @@ export function getTransactionsProjection({ ...rangeQuery(start, end), ...environmentQuery(environment), ...kqlQuery(kuery), - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }; return { diff --git a/x-pack/plugins/apm/server/projections/typings.ts b/x-pack/plugins/apm/server/projections/typings.ts index bb90aa0bf5eb4b..60a3317af1864d 100644 --- a/x-pack/plugins/apm/server/projections/typings.ts +++ b/x-pack/plugins/apm/server/projections/typings.ts @@ -16,7 +16,7 @@ export type Projection = Omit & { aggs?: { [key: string]: { terms: AggregationOptionsByType['terms'] & { field: string }; - aggs?: Record; + aggs?: Record; }; }; }; diff --git a/x-pack/plugins/apm/server/utils/queries.ts b/x-pack/plugins/apm/server/utils/queries.ts index 7255e7ed75a630..f21ef9de0283f4 100644 --- a/x-pack/plugins/apm/server/utils/queries.ts +++ b/x-pack/plugins/apm/server/utils/queries.ts @@ -13,9 +13,11 @@ import { } from '../../common/environment_filter_values'; export { kqlQuery, rangeQuery } from '../../../observability/server'; -type QueryContainer = ESFilter; +type QueryDslQueryContainer = ESFilter; -export function environmentQuery(environment?: string): QueryContainer[] { +export function environmentQuery( + environment?: string +): QueryDslQueryContainer[] { if (!environment || environment === ENVIRONMENT_ALL.value) { return []; } diff --git a/x-pack/plugins/canvas/types/strategy.ts b/x-pack/plugins/canvas/types/strategy.ts index 1c94059f0c9ca8..d7115a3e4372f2 100644 --- a/x-pack/plugins/canvas/types/strategy.ts +++ b/x-pack/plugins/canvas/types/strategy.ts @@ -6,7 +6,7 @@ */ import { ApiResponse } from '@elastic/elasticsearch/lib/Transport'; -import { QuerySqlResponse } from '@elastic/elasticsearch/api/types'; +import { estypes } from '@elastic/elasticsearch'; import { IKibanaSearchRequest } from 'src/plugins/data/common'; import { ExpressionValueFilter } from '.'; export interface EssqlSearchStrategyRequest extends IKibanaSearchRequest { @@ -27,5 +27,5 @@ export interface EssqlSearchStrategyResponse { }>; rows: any[]; - rawResponse: ApiResponse; + rawResponse: ApiResponse; } diff --git a/x-pack/plugins/cases/server/services/cases/index.ts b/x-pack/plugins/cases/server/services/cases/index.ts index 196314a0ecbfb5..5618f6c83ff060 100644 --- a/x-pack/plugins/cases/server/services/cases/index.ts +++ b/x-pack/plugins/cases/server/services/cases/index.ts @@ -16,7 +16,7 @@ import { SavedObjectsFindResult, } from 'kibana/server'; -import { AggregationContainer } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { nodeBuilder, KueryNode } from '../../../../../../src/plugins/data/common'; import { SecurityPluginSetup } from '../../../../security/server'; @@ -218,7 +218,9 @@ export class CasesService { private readonly authentication?: SecurityPluginSetup['authc'] ) {} - private buildCaseIdsAggs = (size: number = 100): Record => ({ + private buildCaseIdsAggs = ( + size: number = 100 + ): Record => ({ references: { nested: { path: `${CASE_COMMENT_SAVED_OBJECT}.references`, diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/constants.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/constants.ts index 59010cb9ab8b66..df1e19e264c756 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/constants.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/constants.ts @@ -9,14 +9,6 @@ import { i18n } from '@kbn/i18n'; import { AdvanceRoleType } from '../../types'; -export const EMPTY_ROLE_MAPPINGS_BODY = i18n.translate( - 'xpack.enterpriseSearch.appSearch.roleMapping.emptyRoleMappingsBody', - { - defaultMessage: - 'All users who successfully authenticate will be assigned the Owner role and have access to all engines. Add a new role to override the default.', - } -); - export const DELETE_ROLE_MAPPING_MESSAGE = i18n.translate( 'xpack.enterpriseSearch.appSearch.deleteRoleMappingMessage', { diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/role_mappings.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/role_mappings.test.tsx index 4ccb1fec0f034f..9559df2c1f9815 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/role_mappings.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/role_mappings.test.tsx @@ -12,10 +12,8 @@ import React from 'react'; import { shallow } from 'enzyme'; -import { EuiButton, EuiEmptyPrompt } from '@elastic/eui'; - import { Loading } from '../../../shared/loading'; -import { RoleMappingsTable } from '../../../shared/role_mapping'; +import { RoleMappingsTable, RoleMappingsHeading } from '../../../shared/role_mapping'; import { wsRoleMapping } from '../../../shared/role_mapping/__mocks__/roles'; import { RoleMapping } from './role_mapping'; @@ -53,13 +51,6 @@ describe('RoleMappings', () => { expect(wrapper.find(Loading)).toHaveLength(1); }); - it('renders empty state', () => { - setMockValues({ ...mockValues, roleMappings: [] }); - const wrapper = shallow(); - - expect(wrapper.find(EuiEmptyPrompt)).toHaveLength(1); - }); - it('renders RoleMapping flyout', () => { setMockValues({ ...mockValues, roleMappingFlyoutOpen: true }); const wrapper = shallow(); @@ -67,10 +58,9 @@ describe('RoleMappings', () => { expect(wrapper.find(RoleMapping)).toHaveLength(1); }); - it('handles button click', () => { - setMockValues({ ...mockValues, roleMappings: [] }); + it('handles onClick', () => { const wrapper = shallow(); - wrapper.find(EuiEmptyPrompt).dive().find(EuiButton).simulate('click'); + wrapper.find(RoleMappingsHeading).prop('onClick')(); expect(initializeRoleMapping).toHaveBeenCalled(); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/role_mappings.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/role_mappings.tsx index 61ed70f515f6f3..78d0a5cbc8638e 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/role_mappings.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/role_mappings/role_mappings.tsx @@ -9,27 +9,13 @@ import React, { useEffect } from 'react'; import { useActions, useValues } from 'kea'; -import { - EuiButton, - EuiEmptyPrompt, - EuiPageContent, - EuiPageContentBody, - EuiPageHeader, - EuiPanel, -} from '@elastic/eui'; - import { FlashMessages } from '../../../shared/flash_messages'; import { SetAppSearchChrome as SetPageChrome } from '../../../shared/kibana_chrome'; import { Loading } from '../../../shared/loading'; -import { RoleMappingsTable } from '../../../shared/role_mapping'; -import { - EMPTY_ROLE_MAPPINGS_TITLE, - ROLE_MAPPING_ADD_BUTTON, - ROLE_MAPPINGS_TITLE, - ROLE_MAPPINGS_DESCRIPTION, -} from '../../../shared/role_mapping/constants'; +import { RoleMappingsTable, RoleMappingsHeading } from '../../../shared/role_mapping'; +import { ROLE_MAPPINGS_TITLE } from '../../../shared/role_mapping/constants'; -import { ROLE_MAPPINGS_ENGINE_ACCESS_HEADING, EMPTY_ROLE_MAPPINGS_BODY } from './constants'; +import { ROLE_MAPPINGS_ENGINE_ACCESS_HEADING } from './constants'; import { RoleMapping } from './role_mapping'; import { RoleMappingsLogic } from './role_mappings_logic'; @@ -54,47 +40,26 @@ export const RoleMappings: React.FC = () => { if (dataLoading) return ; - const addMappingButton = ( - initializeRoleMapping()}> - {ROLE_MAPPING_ADD_BUTTON} - - ); - - const roleMappingEmptyState = ( - - {EMPTY_ROLE_MAPPINGS_TITLE}} - body={

{EMPTY_ROLE_MAPPINGS_BODY}

} - actions={addMappingButton} + const roleMappingsSection = ( + <> + initializeRoleMapping()} /> + -
- ); - - const roleMappingsTable = ( - + ); return ( <> - - {roleMappingFlyoutOpen && } - 0}> - - - {roleMappings.length === 0 ? roleMappingEmptyState : roleMappingsTable} - - + + {roleMappingsSection} ); }; diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/constants.ts b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/constants.ts index 47201988e8732e..be0c860627f799 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/constants.ts +++ b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/constants.ts @@ -7,6 +7,8 @@ import { i18n } from '@kbn/i18n'; +import { ProductName } from '../types'; + export const ANY_AUTH_PROVIDER = '*'; export const ANY_AUTH_PROVIDER_OPTION_LABEL = i18n.translate( @@ -104,7 +106,7 @@ export const DELETE_ROLE_MAPPING_BUTTON = i18n.translate( export const FILTER_ROLE_MAPPINGS_PLACEHOLDER = i18n.translate( 'xpack.enterpriseSearch.roleMapping.filterRoleMappingsPlaceholder', { - defaultMessage: 'Filter roles...', + defaultMessage: 'Filter role mappings', } ); @@ -125,21 +127,6 @@ export const MANAGE_ROLE_MAPPING_TITLE = i18n.translate( { defaultMessage: 'Manage role mapping' } ); -export const EMPTY_ROLE_MAPPINGS_TITLE = i18n.translate( - 'xpack.enterpriseSearch.roleMapping.emptyRoleMappingsTitle', - { - defaultMessage: 'No role mappings yet', - } -); - -export const ROLE_MAPPINGS_DESCRIPTION = i18n.translate( - 'xpack.enterpriseSearch.roleMapping.roleMappingsDescription', - { - defaultMessage: - 'Define role mappings for elasticsearch-native and elasticsearch-saml authentication.', - } -); - export const ROLE_MAPPING_NOT_FOUND = i18n.translate( 'xpack.enterpriseSearch.roleMapping.notFoundMessage', { @@ -168,13 +155,6 @@ export const ROLE_MAPPING_FLYOUT_DESCRIPTION = i18n.translate( } ); -export const ROLE_MAPPING_ADD_BUTTON = i18n.translate( - 'xpack.enterpriseSearch.roleMapping.roleMappingAddButton', - { - defaultMessage: 'Add mapping', - } -); - export const ROLE_MAPPING_FLYOUT_CREATE_BUTTON = i18n.translate( 'xpack.enterpriseSearch.roleMapping.roleMappingFlyoutCreateButton', { @@ -198,3 +178,25 @@ export const UPDATE_ROLE_MAPPING = i18n.translate( 'xpack.enterpriseSearch.roleMapping.updateRoleMappingButtonLabel', { defaultMessage: 'Update role mapping' } ); + +export const ROLE_MAPPINGS_HEADING_TITLE = i18n.translate( + 'xpack.enterpriseSearch.roleMapping.roleMappingsHeadingTitle', + { defaultMessage: 'Role mappings' } +); + +export const ROLE_MAPPINGS_HEADING_DESCRIPTION = (productName: ProductName) => + i18n.translate('xpack.enterpriseSearch.roleMapping.roleMappingsHeadingDescription', { + defaultMessage: + 'Role mappings provide an interface to associate native or SAML-governed role attributes with {productName} permissions.', + values: { productName }, + }); + +export const ROLE_MAPPINGS_HEADING_DOCS_LINK = i18n.translate( + 'xpack.enterpriseSearch.roleMapping.roleMappingsHeadingDocsLink', + { defaultMessage: 'Learn more about role mappings' } +); + +export const ROLE_MAPPINGS_HEADING_BUTTON = i18n.translate( + 'xpack.enterpriseSearch.roleMapping.roleMappingsHeadingButton', + { defaultMessage: 'Create a new role mapping' } +); diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/index.ts b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/index.ts index 6f67bc682f3336..0f9362157f50ad 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/index.ts +++ b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/index.ts @@ -10,3 +10,4 @@ export { RoleMappingsTable } from './role_mappings_table'; export { RoleOptionLabel } from './role_option_label'; export { RoleSelector } from './role_selector'; export { RoleMappingFlyout } from './role_mapping_flyout'; +export { RoleMappingsHeading } from './role_mappings_heading'; diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/role_mappings_heading.test.tsx b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/role_mappings_heading.test.tsx new file mode 100644 index 00000000000000..f0bf86fb306c65 --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/role_mappings_heading.test.tsx @@ -0,0 +1,25 @@ +/* + * 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 from 'react'; + +import { shallow } from 'enzyme'; + +import { EuiTitle, EuiLink, EuiButton, EuiText } from '@elastic/eui'; + +import { RoleMappingsHeading } from './role_mappings_heading'; + +describe('RoleMappingsHeading', () => { + it('renders ', () => { + const wrapper = shallow(); + + expect(wrapper.find(EuiTitle)).toHaveLength(1); + expect(wrapper.find(EuiText)).toHaveLength(1); + expect(wrapper.find(EuiLink)).toHaveLength(1); + expect(wrapper.find(EuiButton)).toHaveLength(1); + }); +}); diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/role_mappings_heading.tsx b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/role_mappings_heading.tsx new file mode 100644 index 00000000000000..b2143c6ff44028 --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/role_mappings_heading.tsx @@ -0,0 +1,62 @@ +/* + * 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 from 'react'; + +import { + EuiButton, + EuiFlexGroup, + EuiFlexItem, + EuiLink, + EuiSpacer, + EuiText, + EuiTitle, +} from '@elastic/eui'; + +import { ProductName } from '../types'; + +import { + ROLE_MAPPINGS_HEADING_TITLE, + ROLE_MAPPINGS_HEADING_DESCRIPTION, + ROLE_MAPPINGS_HEADING_DOCS_LINK, + ROLE_MAPPINGS_HEADING_BUTTON, +} from './constants'; + +interface Props { + productName: ProductName; + onClick(): void; +} + +// TODO: Replace EuiLink href with acutal docs link when available +const ROLE_MAPPINGS_DOCS_HREF = '#TODO'; + +export const RoleMappingsHeading: React.FC = ({ productName, onClick }) => ( + <> + + + +

{ROLE_MAPPINGS_HEADING_TITLE}

+
+ + +

+ {ROLE_MAPPINGS_HEADING_DESCRIPTION(productName)}{' '} + + {ROLE_MAPPINGS_HEADING_DOCS_LINK} + +

+
+
+ + + {ROLE_MAPPINGS_HEADING_BUTTON} + + +
+ + +); diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/role_mappings_table.tsx b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/role_mappings_table.tsx index d5d6d8b9cd227b..f185e9ffb418ee 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/role_mappings_table.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/shared/role_mapping/role_mappings_table.tsx @@ -10,8 +10,6 @@ import React, { Fragment, useState } from 'react'; import { EuiButtonIcon, EuiFieldSearch, - EuiFlexGroup, - EuiFlexItem, EuiIconTip, EuiSpacer, EuiTable, @@ -54,7 +52,6 @@ interface Props { accessItemKey: 'groups' | 'engines'; accessHeader: string; roleMappings: Array; - addMappingButton: React.ReactNode; accessAllEngines?: boolean; shouldShowAuthProvider?: boolean; initializeRoleMapping(roleMappingId: string): void; @@ -72,7 +69,6 @@ export const RoleMappingsTable: React.FC = ({ accessItemKey, accessHeader, roleMappings, - addMappingButton, shouldShowAuthProvider, initializeRoleMapping, handleDeleteMapping, @@ -117,16 +113,11 @@ export const RoleMappingsTable: React.FC = ({ return ( <> - - - updateValue(e.target.value)} - /> - - {addMappingButton} - + updateValue(e.target.value)} + /> {filteredResults.length > 0 ? ( diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/types.ts b/x-pack/plugins/enterprise_search/public/applications/shared/types.ts index 2cdadc1c6b0d30..f450ca556ebe25 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/types.ts +++ b/x-pack/plugins/enterprise_search/public/applications/shared/types.ts @@ -35,3 +35,5 @@ export interface RoleMapping { content: string; }; } + +export type ProductName = 'App Search' | 'Workplace Search'; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/constants.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/constants.ts index 62494b447efa0b..92c8b7827b9b67 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/constants.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/constants.ts @@ -73,14 +73,6 @@ export const GROUP_ASSIGNMENT_LABEL = i18n.translate( } ); -export const EMPTY_ROLE_MAPPINGS_BODY = i18n.translate( - 'xpack.enterpriseSearch.workplaceSearch.roleMapping.emptyRoleMappingsBody', - { - defaultMessage: - 'New team members are assigned the admin role by default. An admin can access everything. Create a new role to override the default.', - } -); - export const ROLE_MAPPINGS_TABLE_HEADER = i18n.translate( 'xpack.enterpriseSearch.workplaceSearch.roleMapping.roleMappingsTableHeader', { diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings.test.tsx index d7be753eec173e..9559df2c1f9815 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings.test.tsx @@ -12,10 +12,8 @@ import React from 'react'; import { shallow } from 'enzyme'; -import { EuiEmptyPrompt, EuiButton } from '@elastic/eui'; - import { Loading } from '../../../shared/loading'; -import { RoleMappingsTable } from '../../../shared/role_mapping'; +import { RoleMappingsTable, RoleMappingsHeading } from '../../../shared/role_mapping'; import { wsRoleMapping } from '../../../shared/role_mapping/__mocks__/roles'; import { RoleMapping } from './role_mapping'; @@ -53,13 +51,6 @@ describe('RoleMappings', () => { expect(wrapper.find(Loading)).toHaveLength(1); }); - it('renders empty state', () => { - setMockValues({ ...mockValues, roleMappings: [] }); - const wrapper = shallow(); - - expect(wrapper.find(EuiEmptyPrompt)).toHaveLength(1); - }); - it('renders RoleMapping flyout', () => { setMockValues({ ...mockValues, roleMappingFlyoutOpen: true }); const wrapper = shallow(); @@ -67,10 +58,9 @@ describe('RoleMappings', () => { expect(wrapper.find(RoleMapping)).toHaveLength(1); }); - it('handles button click', () => { - setMockValues({ ...mockValues, roleMappings: [] }); + it('handles onClick', () => { const wrapper = shallow(); - wrapper.find(EuiEmptyPrompt).dive().find(EuiButton).simulate('click'); + wrapper.find(RoleMappingsHeading).prop('onClick')(); expect(initializeRoleMapping).toHaveBeenCalled(); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings.tsx index e5a9a31d463b89..46c426c3dad2a5 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings.tsx @@ -9,21 +9,13 @@ import React, { useEffect } from 'react'; import { useActions, useValues } from 'kea'; -import { EuiButton, EuiEmptyPrompt, EuiPanel } from '@elastic/eui'; - import { FlashMessages } from '../../../shared/flash_messages'; import { SetWorkplaceSearchChrome as SetPageChrome } from '../../../shared/kibana_chrome'; import { Loading } from '../../../shared/loading'; -import { RoleMappingsTable } from '../../../shared/role_mapping'; -import { - EMPTY_ROLE_MAPPINGS_TITLE, - ROLE_MAPPING_ADD_BUTTON, - ROLE_MAPPINGS_TITLE, - ROLE_MAPPINGS_DESCRIPTION, -} from '../../../shared/role_mapping/constants'; -import { ViewContentHeader } from '../../components/shared/view_content_header'; +import { RoleMappingsTable, RoleMappingsHeading } from '../../../shared/role_mapping'; +import { ROLE_MAPPINGS_TITLE } from '../../../shared/role_mapping/constants'; -import { EMPTY_ROLE_MAPPINGS_BODY, ROLE_MAPPINGS_TABLE_HEADER } from './constants'; +import { ROLE_MAPPINGS_TABLE_HEADER } from './constants'; import { RoleMapping } from './role_mapping'; import { RoleMappingsLogic } from './role_mappings_logic'; @@ -46,43 +38,26 @@ export const RoleMappings: React.FC = () => { if (dataLoading) return ; - const addMappingButton = ( - initializeRoleMapping()}> - {ROLE_MAPPING_ADD_BUTTON} - - ); - const emptyPrompt = ( - - {EMPTY_ROLE_MAPPINGS_TITLE}} - body={

{EMPTY_ROLE_MAPPINGS_BODY}

} - actions={addMappingButton} + const roleMappingsSection = ( + <> + initializeRoleMapping()} /> + -
- ); - const roleMappingsTable = ( - + ); return ( <> - - {roleMappingFlyoutOpen && } -
- - {roleMappings.length === 0 ? emptyPrompt : roleMappingsTable} -
+ + {roleMappingsSection} ); }; diff --git a/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts b/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts index dd6ac6350d6e34..e42e24e4b47d41 100644 --- a/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts +++ b/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts @@ -240,7 +240,7 @@ export class ClusterClientAdapter { +): maybeDocument is estypes.MgetHit { return '_id' in maybeDocument && '_source' in maybeDocument; } -export type ESAgentDocumentResult = estypes.MultiGetHit; +export type ESAgentDocumentResult = estypes.MgetHit; export async function getAgentDocuments( esClient: ElasticsearchClient, agentIds: string[] diff --git a/x-pack/plugins/fleet/server/services/agents/helpers.ts b/x-pack/plugins/fleet/server/services/agents/helpers.ts index c4273a57ddffda..822a2a9df98d5e 100644 --- a/x-pack/plugins/fleet/server/services/agents/helpers.ts +++ b/x-pack/plugins/fleet/server/services/agents/helpers.ts @@ -11,7 +11,7 @@ import type { SearchHit } from '../../../../../../typings/elasticsearch'; import type { Agent, AgentSOAttributes, FleetServerAgent } from '../../types'; type FleetServerAgentESResponse = - | estypes.MultiGetHit + | estypes.MgetHit | estypes.SearchResponse['hits']['hits'][0] | SearchHit; diff --git a/x-pack/plugins/fleet/server/services/agents/reassign.test.ts b/x-pack/plugins/fleet/server/services/agents/reassign.test.ts index 63085b7729c4bc..a87432c6392492 100644 --- a/x-pack/plugins/fleet/server/services/agents/reassign.test.ts +++ b/x-pack/plugins/fleet/server/services/agents/reassign.test.ts @@ -85,7 +85,7 @@ describe('reassignAgents (plural)', () => { // calls ES update with correct values const calledWith = esClient.bulk.mock.calls[0][0]; // only 1 are regular and bulk write two line per update - expect(calledWith.body.length).toBe(2); + expect(calledWith.body?.length).toBe(2); // @ts-expect-error expect(calledWith.body[0].update._id).toEqual(agentInRegularDoc._id); }); diff --git a/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts b/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts index 33f12dc52dc009..3621bc5025ab3e 100644 --- a/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts +++ b/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts @@ -94,11 +94,11 @@ describe('unenrollAgents (plural)', () => { // calls ES update with correct values const calledWith = esClient.bulk.mock.calls[1][0]; const ids = calledWith?.body - .filter((i: any) => i.update !== undefined) + ?.filter((i: any) => i.update !== undefined) .map((i: any) => i.update._id); - const docs = calledWith?.body.filter((i: any) => i.doc).map((i: any) => i.doc); + const docs = calledWith?.body?.filter((i: any) => i.doc).map((i: any) => i.doc); expect(ids).toEqual(idsToUnenroll); - for (const doc of docs) { + for (const doc of docs!) { expect(doc).toHaveProperty('unenrollment_started_at'); } }); @@ -112,11 +112,11 @@ describe('unenrollAgents (plural)', () => { const onlyRegular = [agentInRegularDoc._id, agentInRegularDoc2._id]; const calledWith = esClient.bulk.mock.calls[1][0]; const ids = calledWith?.body - .filter((i: any) => i.update !== undefined) + ?.filter((i: any) => i.update !== undefined) .map((i: any) => i.update._id); - const docs = calledWith?.body.filter((i: any) => i.doc).map((i: any) => i.doc); + const docs = calledWith?.body?.filter((i: any) => i.doc).map((i: any) => i.doc); expect(ids).toEqual(onlyRegular); - for (const doc of docs) { + for (const doc of docs!) { expect(doc).toHaveProperty('unenrollment_started_at'); } }); @@ -150,11 +150,11 @@ describe('unenrollAgents (plural)', () => { const onlyRegular = [agentInRegularDoc._id, agentInRegularDoc2._id]; const calledWith = esClient.bulk.mock.calls[0][0]; const ids = calledWith?.body - .filter((i: any) => i.update !== undefined) + ?.filter((i: any) => i.update !== undefined) .map((i: any) => i.update._id); - const docs = calledWith?.body.filter((i: any) => i.doc).map((i: any) => i.doc); + const docs = calledWith?.body?.filter((i: any) => i.doc).map((i: any) => i.doc); expect(ids).toEqual(onlyRegular); - for (const doc of docs) { + for (const doc of docs!) { expect(doc).toHaveProperty('unenrolled_at'); } }); @@ -167,11 +167,11 @@ describe('unenrollAgents (plural)', () => { // calls ES update with correct values const calledWith = esClient.bulk.mock.calls[1][0]; const ids = calledWith?.body - .filter((i: any) => i.update !== undefined) + ?.filter((i: any) => i.update !== undefined) .map((i: any) => i.update._id); - const docs = calledWith?.body.filter((i: any) => i.doc).map((i: any) => i.doc); + const docs = calledWith?.body?.filter((i: any) => i.doc).map((i: any) => i.doc); expect(ids).toEqual(idsToUnenroll); - for (const doc of docs) { + for (const doc of docs!) { expect(doc).toHaveProperty('unenrollment_started_at'); } }); @@ -205,11 +205,11 @@ describe('unenrollAgents (plural)', () => { // calls ES update with correct values const calledWith = esClient.bulk.mock.calls[0][0]; const ids = calledWith?.body - .filter((i: any) => i.update !== undefined) + ?.filter((i: any) => i.update !== undefined) .map((i: any) => i.update._id); - const docs = calledWith?.body.filter((i: any) => i.doc).map((i: any) => i.doc); + const docs = calledWith?.body?.filter((i: any) => i.doc).map((i: any) => i.doc); expect(ids).toEqual(idsToUnenroll); - for (const doc of docs) { + for (const doc of docs!) { expect(doc).toHaveProperty('unenrolled_at'); } }); 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 511a0abecbc180..f9aab997f063c6 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 @@ -197,7 +197,6 @@ export async function generateEnrollmentAPIKey( .createApiKey({ body: { name, - // @ts-expect-error Metadata in api keys metadata: { managed_by: 'fleet', managed: true, diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts index 8c58238588b2f0..552e486552a786 100644 --- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts +++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts @@ -142,6 +142,7 @@ describe('EPM install', () => { it('tests installPackage remove the aliases property if the property existed', async () => { const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser; + // @ts-expect-error not full interface esClient.indices.getIndexTemplate.mockImplementation(() => elasticsearchServiceMock.createSuccessTransportRequestPromise({ index_templates: [ diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts index 9e8277eb6171f3..d202dab54f5bdc 100644 --- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts +++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts @@ -183,6 +183,7 @@ function putComponentTemplate( }; return { + // @ts-expect-error body expected to be ClusterPutComponentTemplateRequest clusterPromise: esClient.cluster.putComponentTemplate(esClientParams, { ignore: [404] }), name, }; diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts index 5dd2755390ecb1..07d0df021c827b 100644 --- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts +++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts @@ -527,7 +527,6 @@ const updateExistingDataStream = async ({ await esClient.indices.putMapping({ index: dataStreamName, body: mappings, - // @ts-expect-error @elastic/elasticsearch doesn't declare it on PutMappingRequest write_index_only: true, }); // if update fails, rollover data stream @@ -549,7 +548,7 @@ const updateExistingDataStream = async ({ try { await esClient.indices.putSettings({ index: dataStreamName, - body: { index: { default_pipeline: settings.index.default_pipeline } }, + body: { settings: { default_pipeline: settings.index.default_pipeline } }, }); } catch (err) { throw new Error(`could not update index template settings for ${dataStreamName}`); diff --git a/x-pack/plugins/index_lifecycle_management/server/routes/api/index/register_add_policy_route.ts b/x-pack/plugins/index_lifecycle_management/server/routes/api/index/register_add_policy_route.ts index 77f14decc56429..a18459d5d21b94 100644 --- a/x-pack/plugins/index_lifecycle_management/server/routes/api/index/register_add_policy_route.ts +++ b/x-pack/plugins/index_lifecycle_management/server/routes/api/index/register_add_policy_route.ts @@ -24,7 +24,6 @@ async function addLifecyclePolicy( }, }; - // @ts-expect-error @elastic/elasticsearch UpdateIndexSettingsRequest does not support index property return client.indices.putSettings({ index: indexName, body }); } diff --git a/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_add_policy_route.ts b/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_add_policy_route.ts index 4d467a807109a4..823b36e63a8739 100644 --- a/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_add_policy_route.ts +++ b/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_add_policy_route.ts @@ -80,6 +80,7 @@ async function updateIndexTemplate( if (isLegacy) { return client.indices.putTemplate({ name: templateName, body: indexTemplate }); } + // @ts-expect-error Type 'IndexSettings' is not assignable to type 'IndicesIndexSettings'. return client.indices.putIndexTemplate({ name: templateName, body: indexTemplate }); } 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 77c7947ce22c3d..ee831d9a98eb90 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 @@ -22,7 +22,7 @@ export interface ResolvedLogSourceConfiguration { tiebreakerField: string; messageField: string[]; fields: IndexPattern['fields']; - runtimeMappings: estypes.RuntimeFields; + runtimeMappings: estypes.MappingRuntimeFields; columns: LogSourceColumnConfiguration[]; } @@ -103,12 +103,12 @@ const resolveKibanaIndexPatternReference = async ( }; // this might take other sources of runtime fields into account in the future -const resolveRuntimeMappings = (indexPattern: IndexPattern): estypes.RuntimeFields => { +const resolveRuntimeMappings = (indexPattern: IndexPattern): estypes.MappingRuntimeFields => { const { runtimeFields } = indexPattern.getComputedFields(); const runtimeMappingsFromIndexPattern = (Object.entries(runtimeFields) as ObjectEntries< typeof runtimeFields - >).reduce( + >).reduce( (accumulatedMappings, [runtimeFieldName, runtimeFieldSpec]) => ({ ...accumulatedMappings, [runtimeFieldName]: { diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts index 9eadc3035588d7..9de6e574ecb5bf 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts @@ -19,7 +19,7 @@ interface RequestArgs { timestampField: string; startTime: number; endTime: number; - runtimeMappings: estypes.RuntimeFields; + runtimeMappings: estypes.MappingRuntimeFields; } export const callValidateDatasetsAPI = async (requestArgs: RequestArgs, fetch: HttpHandler) => { diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts index f9eb7609e00f35..a211fecc807faa 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts @@ -20,7 +20,7 @@ import { decodeOrThrow } from '../../../../../common/runtime_types'; interface RequestArgs { indices: string[]; fields: ValidationIndicesFieldSpecification[]; - runtimeMappings: estypes.RuntimeFields; + runtimeMappings: estypes.MappingRuntimeFields; } export const callValidateIndicesAPI = async (requestArgs: RequestArgs, fetch: HttpHandler) => { diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts index 36371b080ee450..4ae99b95cfff86 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts @@ -47,7 +47,7 @@ export interface ModuleDescriptor { validateSetupIndices: ( indices: string[], timestampField: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, fetch: HttpHandler ) => Promise; validateSetupDatasets: ( @@ -55,7 +55,7 @@ export interface ModuleDescriptor { timestampField: string, startTime: number, endTime: number, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, fetch: HttpHandler ) => Promise; } @@ -65,5 +65,5 @@ export interface ModuleSourceConfiguration { sourceId: string; spaceId: string; timestampField: string; - runtimeMappings: estypes.RuntimeFields; + runtimeMappings: estypes.MappingRuntimeFields; } diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts index 981b7b496b435b..af2bd1802042a4 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts @@ -136,7 +136,7 @@ const cleanUpModule = async (spaceId: string, sourceId: string, fetch: HttpHandl const validateSetupIndices = async ( indices: string[], timestampField: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, fetch: HttpHandler ) => { return await callValidateIndicesAPI( @@ -167,7 +167,7 @@ const validateSetupDatasets = async ( timestampField: string, startTime: number, endTime: number, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, fetch: HttpHandler ) => { return await callValidateDatasetsAPI( 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 a2ad5cd4f56c46..86e8e75dc3d411 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 @@ -26,7 +26,7 @@ export const useLogEntryCategoriesModule = ({ sourceId: string; spaceId: string; timestampField: string; - runtimeMappings: estypes.RuntimeFields; + runtimeMappings: estypes.MappingRuntimeFields; }) => { const sourceConfiguration: ModuleSourceConfiguration = useMemo( () => ({ diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts index 345f221f11c1f0..9704afd80e9ea6 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts @@ -128,7 +128,7 @@ const cleanUpModule = async (spaceId: string, sourceId: string, fetch: HttpHandl const validateSetupIndices = async ( indices: string[], timestampField: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, fetch: HttpHandler ) => { return await callValidateIndicesAPI( @@ -155,7 +155,7 @@ const validateSetupDatasets = async ( timestampField: string, startTime: number, endTime: number, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, fetch: HttpHandler ) => { return await callValidateDatasetsAPI( 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 b451cad1c8753a..0df5d9b446dbe6 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 @@ -25,7 +25,7 @@ export const useLogEntryRateModule = ({ sourceId: string; spaceId: string; timestampField: string; - runtimeMappings: estypes.RuntimeFields; + runtimeMappings: estypes.MappingRuntimeFields; }) => { const sourceConfiguration: ModuleSourceConfiguration = useMemo( () => ({ diff --git a/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts index d3ea162781b5d2..2aede2f6aad160 100644 --- a/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts @@ -161,7 +161,7 @@ export class KibanaFramework { apiResult = elasticsearch.client.asCurrentUser.msearch({ ...params, ...frozenIndicesParams, - } as estypes.MultiSearchRequest); + } as estypes.MsearchRequest); break; case 'fieldCaps': apiResult = elasticsearch.client.asCurrentUser.fieldCaps({ diff --git a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts index 1c1edb3ea83281..ffabd7ba65f035 100644 --- a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts +++ b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts @@ -24,7 +24,7 @@ import { GroupedSearchQueryResponse, } from '../../../../common/alerting/logs/log_threshold/types'; import { alertsMock } from '../../../../../alerting/server/mocks'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; // Mocks // const numericField = { @@ -70,7 +70,7 @@ const baseAlertParams: Pick = { const TIMESTAMP_FIELD = '@timestamp'; const FILEBEAT_INDEX = 'filebeat-*'; -const runtimeMappings: estypes.RuntimeFields = { +const runtimeMappings: estypes.MappingRuntimeFields = { runtime_field: { type: 'keyword', script: { diff --git a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts index 3e910e5dfbf460..a537801202217b 100644 --- a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts @@ -113,7 +113,7 @@ async function executeAlert( alertParams: CountAlertParams, timestampField: string, indexPattern: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, esClient: ElasticsearchClient, alertInstanceFactory: LogThresholdAlertServices['alertInstanceFactory'] ) { @@ -144,7 +144,7 @@ async function executeRatioAlert( alertParams: RatioAlertParams, timestampField: string, indexPattern: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, esClient: ElasticsearchClient, alertInstanceFactory: LogThresholdAlertServices['alertInstanceFactory'] ) { @@ -198,7 +198,7 @@ const getESQuery = ( alertParams: Omit & { criteria: CountCriteria }, timestampField: string, indexPattern: string, - runtimeMappings: estypes.RuntimeFields + runtimeMappings: estypes.MappingRuntimeFields ) => { return hasGroupBy(alertParams) ? getGroupedESQuery(alertParams, timestampField, indexPattern, runtimeMappings) @@ -433,7 +433,7 @@ export const getGroupedESQuery = ( params: Pick & { criteria: CountCriteria }, timestampField: string, index: string, - runtimeMappings: estypes.RuntimeFields + runtimeMappings: estypes.MappingRuntimeFields ): estypes.SearchRequest | undefined => { const { groupBy } = params; @@ -493,7 +493,7 @@ export const getUngroupedESQuery = ( params: Pick & { criteria: CountCriteria }, timestampField: string, index: string, - runtimeMappings: estypes.RuntimeFields + runtimeMappings: estypes.MappingRuntimeFields ): object => { const { rangeFilter, mustFilters, mustNotFilters } = buildFiltersFromCriteria( params, 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 387143ef9f9c42..ad8650bbb0fb65 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 @@ -277,7 +277,7 @@ export class InfraLogEntriesDomain { indexName: string, startTime: number, endTime: number, - runtimeMappings: estypes.RuntimeFields + runtimeMappings: estypes.MappingRuntimeFields ) { let datasetBuckets: LogEntryDatasetBucket[] = []; let afterLatestBatchKey: CompositeDatasetKey | undefined; diff --git a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts index 18e04aaf063d42..3431f3bfb0c8c7 100644 --- a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts +++ b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts @@ -15,7 +15,7 @@ export const createLogEntryDatasetsQuery = ( timestampField: string, startTime: number, endTime: number, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, size: number, afterKey?: CompositeDatasetKey ) => ({ diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts index 716ab400c01233..3210f01116f76f 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts @@ -387,7 +387,7 @@ export async function fetchLogEntryExamples( context: InfraPluginRequestHandlerContext & { infra: Required }, sourceId: string, indices: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, timestampField: string, tiebreakerField: string, startTime: number, 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 ee2441d5911341..7739f39cb56246 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 @@ -404,7 +404,7 @@ async function fetchTopLogEntryCategoryHistograms( async function fetchLogEntryCategoryExamples( requestContext: { core: { elasticsearch: { client: { asCurrentUser: ElasticsearchClient } } } }, indices: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, timestampField: string, tiebreakerField: string, startTime: number, diff --git a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts index f06dcd43a91568..0fef7dedfff0bc 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts @@ -12,7 +12,7 @@ import { defaultRequestParameters } from './common'; export const createLogEntryCategoryExamplesQuery = ( indices: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, timestampField: string, tiebreakerField: string, startTime: number, diff --git a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts index 1e8cbe247dd50b..ee339c9c6eb7ee 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts @@ -13,7 +13,7 @@ import { defaultRequestParameters } from './common'; export const createLogEntryExamplesQuery = ( indices: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, timestampField: string, tiebreakerField: string, startTime: number, diff --git a/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts b/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts index 950ecc98619ee1..ef789c1b41349a 100644 --- a/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts +++ b/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts @@ -43,7 +43,7 @@ export const initValidateLogAnalysisDatasetsRoute = ({ indexName, startTime, endTime, - runtimeMappings as estypes.RuntimeFields + runtimeMappings as estypes.MappingRuntimeFields ); return { diff --git a/x-pack/plugins/infra/server/services/log_entries/queries/log_entries.ts b/x-pack/plugins/infra/server/services/log_entries/queries/log_entries.ts index 6df17dbfd7bfdd..9022195dce85d9 100644 --- a/x-pack/plugins/infra/server/services/log_entries/queries/log_entries.ts +++ b/x-pack/plugins/infra/server/services/log_entries/queries/log_entries.ts @@ -29,7 +29,7 @@ export const createGetLogEntriesQuery = ( timestampField: string, tiebreakerField: string, fields: string[], - runtimeMappings?: estypes.RuntimeFields, + runtimeMappings?: estypes.MappingRuntimeFields, query?: JsonObject, highlightTerm?: string ): estypes.AsyncSearchSubmitRequest => { @@ -52,8 +52,8 @@ export const createGetLogEntriesQuery = ( ], }, }, - // @ts-expect-error @elastic/elasticsearch doesn't declare body.fields on AsyncSearchSubmitRequest fields, + // @ts-expect-error @elastic/elasticsearch doesn't declare "runtime_mappings" property runtime_mappings: runtimeMappings, _source: false, ...createSortClause(sortDirection, timestampField, tiebreakerField), diff --git a/x-pack/plugins/infra/server/services/log_entries/queries/log_entry.ts b/x-pack/plugins/infra/server/services/log_entries/queries/log_entry.ts index 6bef317d96ada0..8da2f1d685db34 100644 --- a/x-pack/plugins/infra/server/services/log_entries/queries/log_entry.ts +++ b/x-pack/plugins/infra/server/services/log_entries/queries/log_entry.ts @@ -18,7 +18,7 @@ export const createGetLogEntryQuery = ( logEntryId: string, timestampField: string, tiebreakerField: string, - runtimeMappings?: estypes.RuntimeFields + runtimeMappings?: estypes.MappingRuntimeFields ): estypes.AsyncSearchSubmitRequest => ({ index: logEntryIndex, terminate_after: 1, @@ -31,8 +31,8 @@ export const createGetLogEntryQuery = ( values: [logEntryId], }, }, - // @ts-expect-error @elastic/elasticsearch doesn't declare body.fields on AsyncSearchSubmitRequest fields: ['*'], + // @ts-expect-error @elastic/elasticsearch doesn't declare "runtime_mappings" property runtime_mappings: runtimeMappings, sort: [{ [timestampField]: 'desc' }, { [tiebreakerField]: 'desc' }], _source: false, diff --git a/x-pack/plugins/ingest_pipelines/common/lib/pipeline_serialization.ts b/x-pack/plugins/ingest_pipelines/common/lib/pipeline_serialization.ts index 5360e2713aee19..d2669e7c0012b0 100644 --- a/x-pack/plugins/ingest_pipelines/common/lib/pipeline_serialization.ts +++ b/x-pack/plugins/ingest_pipelines/common/lib/pipeline_serialization.ts @@ -5,10 +5,12 @@ * 2.0. */ -import { Pipeline as ESPipeline } from '@elastic/elasticsearch/api/types'; +import { estypes } from '@elastic/elasticsearch'; import { Pipeline, Processor } from '../types'; -export function deserializePipelines(pipelinesByName: { [key: string]: ESPipeline }): Pipeline[] { +export function deserializePipelines(pipelinesByName: { + [key: string]: estypes.IngestPipeline; +}): Pipeline[] { const pipelineNames: string[] = Object.keys(pipelinesByName); const deserializedPipelines = pipelineNames.map((name: string) => { diff --git a/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts b/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts index f697a38e21561e..c133b9237102a6 100644 --- a/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts +++ b/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { SimulatePipelineDocument } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema } from '@kbn/config-schema'; import { API_BASE_PATH } from '../../../common/constants'; @@ -38,7 +38,7 @@ export const registerSimulateRoute = ({ verbose, body: { pipeline, - docs: documents as SimulatePipelineDocument[], + docs: documents as estypes.IngestSimulatePipelineDocument[], }, }); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/mocks.ts b/x-pack/plugins/lens/public/indexpattern_datasource/mocks.ts index e71b26b9d4cd9b..4545e42b2ff997 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/mocks.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/mocks.ts @@ -71,7 +71,7 @@ export const createMockedIndexPatternWithoutType = ( searchable: true, aggregatable: true, scripted: true, - lang: 'painless', + lang: 'painless' as const, script: '1234', }, ].filter(({ type }) => type !== typeToFilter); @@ -145,7 +145,7 @@ export const createMockedIndexPattern = (): IndexPattern => { searchable: true, aggregatable: true, scripted: true, - lang: 'painless', + lang: 'painless' as const, script: '1234', }, ]; @@ -183,7 +183,7 @@ export const createMockedRestrictedIndexPattern = () => { searchable: true, scripted: true, esTypes: ['keyword'], - lang: 'painless', + lang: 'painless' as const, script: '1234', }, ]; diff --git a/x-pack/plugins/lens/server/routes/existing_fields.test.ts b/x-pack/plugins/lens/server/routes/existing_fields.test.ts index 57d8ebf678d614..703b946149e267 100644 --- a/x-pack/plugins/lens/server/routes/existing_fields.test.ts +++ b/x-pack/plugins/lens/server/routes/existing_fields.test.ts @@ -79,7 +79,7 @@ describe('existingFields', () => { const result = existingFields( [ { - // @ts-expect-error _mymeta is not defined on estypes.Hit + // @ts-expect-error _mymeta is not defined on estypes.SearchHit _mymeta: 'abc', ...searchResults({ bar: ['scriptvalue'] }), }, diff --git a/x-pack/plugins/lens/server/routes/existing_fields.ts b/x-pack/plugins/lens/server/routes/existing_fields.ts index d775113d83ff7b..f35b0a7f23179f 100644 --- a/x-pack/plugins/lens/server/routes/existing_fields.ts +++ b/x-pack/plugins/lens/server/routes/existing_fields.ts @@ -28,7 +28,7 @@ export interface Field { name: string; isScript: boolean; isMeta: boolean; - lang?: string; + lang?: estypes.ScriptLanguage; script?: string; runtimeField?: RuntimeField; } @@ -201,10 +201,9 @@ async function fetchIndexPatternStats({ _source: false, runtime_mappings: runtimeFields.reduce((acc, field) => { if (!field.runtimeField) return acc; - // @ts-expect-error @elastic/elasticsearch StoredScript.language is required acc[field.name] = field.runtimeField; return acc; - }, {} as Record), + }, {} as Record), script_fields: scriptedFields.reduce((acc, field) => { acc[field.name] = { script: { @@ -233,7 +232,7 @@ async function fetchIndexPatternStats({ /** * Exported only for unit tests. */ -export function existingFields(docs: estypes.Hit[], fields: Field[]): string[] { +export function existingFields(docs: estypes.SearchHit[], fields: Field[]): string[] { const missingFields = new Set(fields); for (const doc of docs) { diff --git a/x-pack/plugins/lens/server/routes/field_stats.ts b/x-pack/plugins/lens/server/routes/field_stats.ts index 6b7e197a4d5617..ef1043ddd3583f 100644 --- a/x-pack/plugins/lens/server/routes/field_stats.ts +++ b/x-pack/plugins/lens/server/routes/field_stats.ts @@ -79,14 +79,13 @@ export async function initFieldsRoute(setup: CoreSetup) { }, }; - const search = async (aggs: Record) => { + const search = async (aggs: Record) => { const { body: result } = await requestClient.search({ index: indexPattern.title, track_total_hits: true, body: { query, aggs, - // @ts-expect-error @elastic/elasticsearch StoredScript.language is required runtime_mappings: field.runtimeField ? { [fieldName]: field.runtimeField } : {}, }, size: 0, @@ -136,7 +135,9 @@ export async function initFieldsRoute(setup: CoreSetup) { } export async function getNumberHistogram( - aggSearchWithBody: (aggs: Record) => Promise, + aggSearchWithBody: ( + aggs: Record + ) => Promise, field: IFieldType, useTopHits = true ): Promise { @@ -245,7 +246,7 @@ export async function getNumberHistogram( } export async function getStringSamples( - aggSearchWithBody: (aggs: Record) => unknown, + aggSearchWithBody: (aggs: Record) => unknown, field: IFieldType, size = 10 ): Promise { @@ -285,7 +286,7 @@ export async function getStringSamples( // This one is not sampled so that it returns the full date range export async function getDateHistogram( - aggSearchWithBody: (aggs: Record) => unknown, + aggSearchWithBody: (aggs: Record) => unknown, field: IFieldType, range: { fromDate: string; toDate: string } ): Promise { @@ -332,7 +333,7 @@ function getFieldRef(field: IFieldType) { return field.scripted ? { script: { - lang: field.lang as string, + lang: field.lang!, source: field.script as string, }, } diff --git a/x-pack/plugins/lists/server/services/items/find_list_item.ts b/x-pack/plugins/lists/server/services/items/find_list_item.ts index 803cc34ed2a123..29bfdf8bf1d135 100644 --- a/x-pack/plugins/lists/server/services/items/find_list_item.ts +++ b/x-pack/plugins/lists/server/services/items/find_list_item.ts @@ -76,7 +76,7 @@ export const findListItem = async ({ const { body: respose } = await esClient.count({ body: { - // @ts-expect-error GetQueryFilterReturn is not assignable to QueryContainer + // @ts-expect-error GetQueryFilterReturn is not assignable to QueryDslQueryContainer query, }, ignore_unavailable: true, @@ -89,7 +89,7 @@ export const findListItem = async ({ // to explicitly define the type . const { body: response } = await esClient.search({ body: { - // @ts-expect-error GetQueryFilterReturn is not assignable to QueryContainer + // @ts-expect-error GetQueryFilterReturn is not assignable to QueryDslQueryContainer query, search_after: scroll.searchAfter, sort: getSortWithTieBreaker({ sortField, sortOrder }), diff --git a/x-pack/plugins/lists/server/services/lists/find_list.ts b/x-pack/plugins/lists/server/services/lists/find_list.ts index 1c7a5fe60b995e..ae28428d80a5c8 100644 --- a/x-pack/plugins/lists/server/services/lists/find_list.ts +++ b/x-pack/plugins/lists/server/services/lists/find_list.ts @@ -65,7 +65,7 @@ export const findList = async ({ const { body: totalCount } = await esClient.count({ body: { - // @ts-expect-error GetQueryFilterReturn is not compatible with QueryContainer + // @ts-expect-error GetQueryFilterReturn is not compatible with QueryDslQueryContainer query, }, ignore_unavailable: true, @@ -78,7 +78,7 @@ export const findList = async ({ // to explicitly define the type . const { body: response } = await esClient.search({ body: { - // @ts-expect-error GetQueryFilterReturn is not compatible with QueryContainer + // @ts-expect-error GetQueryFilterReturn is not compatible with QueryDslQueryContainer query, search_after: scroll.searchAfter, sort: getSortWithTieBreaker({ sortField, sortOrder }), diff --git a/x-pack/plugins/lists/server/services/utils/get_search_after_scroll.ts b/x-pack/plugins/lists/server/services/utils/get_search_after_scroll.ts index 4ddd3f1c73315e..e34b3080dd33ba 100644 --- a/x-pack/plugins/lists/server/services/utils/get_search_after_scroll.ts +++ b/x-pack/plugins/lists/server/services/utils/get_search_after_scroll.ts @@ -46,7 +46,7 @@ export const getSearchAfterScroll = async ({ const { body: response } = await esClient.search>({ body: { _source: getSourceWithTieBreaker({ sortField }), - // @ts-expect-error Filter is not assignale to QueryContainer + // @ts-expect-error Filter is not assignale to QueryDslQueryContainer query, search_after: newSearchAfter, sort: getSortWithTieBreaker({ sortField, sortOrder }), diff --git a/x-pack/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts b/x-pack/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts index dbcec20d3d8a84..8a513483f5b5e0 100644 --- a/x-pack/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts +++ b/x-pack/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts @@ -13,7 +13,7 @@ export const getSortWithTieBreaker = ({ }: { sortField: SortFieldOrUndefined; sortOrder: SortOrderOrUndefined; -}): estypes.SortCombinations[] => { +}): estypes.SearchSortCombinations[] => { const ascOrDesc = sortOrder ?? ('asc' as const); if (sortField != null) { return [{ [sortField]: ascOrDesc, tie_breaker_id: 'asc' as const }]; diff --git a/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts b/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts index 585eeeb118110b..79db56f9a7fe9e 100644 --- a/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts +++ b/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts @@ -20,7 +20,7 @@ export interface TransformElasticToListItemOptions { } export interface TransformElasticHitToListItemOptions { - hits: Array>; + hits: Array>; type: Type; } diff --git a/x-pack/plugins/logstash/server/models/cluster/cluster.test.ts b/x-pack/plugins/logstash/server/models/cluster/cluster.test.ts index 1e1afc33394f3e..10c1d1ba24ae00 100755 --- a/x-pack/plugins/logstash/server/models/cluster/cluster.test.ts +++ b/x-pack/plugins/logstash/server/models/cluster/cluster.test.ts @@ -13,7 +13,7 @@ describe('cluster', () => { describe('fromUpstreamJSON factory method', () => { const upstreamJSON = { cluster_uuid: 'S-S4NNZDRV-g9c-JrIhx6A', - } as estypes.RootNodeInfoResponse; + } as estypes.InfoResponse; it('returns correct Cluster instance', () => { const cluster = Cluster.fromUpstreamJSON(upstreamJSON); diff --git a/x-pack/plugins/logstash/server/models/cluster/cluster.ts b/x-pack/plugins/logstash/server/models/cluster/cluster.ts index 88789a2d29c891..2982284879c471 100755 --- a/x-pack/plugins/logstash/server/models/cluster/cluster.ts +++ b/x-pack/plugins/logstash/server/models/cluster/cluster.ts @@ -24,7 +24,7 @@ export class Cluster { } // generate Pipeline object from elasticsearch response - static fromUpstreamJSON(upstreamCluster: estypes.RootNodeInfoResponse) { + static fromUpstreamJSON(upstreamCluster: estypes.InfoResponse) { const uuid = upstreamCluster.cluster_uuid; return new Cluster({ uuid }); } diff --git a/x-pack/plugins/maps/server/mvt/get_tile.ts b/x-pack/plugins/maps/server/mvt/get_tile.ts index 95b8e043e0ce47..776d316440a561 100644 --- a/x-pack/plugins/maps/server/mvt/get_tile.ts +++ b/x-pack/plugins/maps/server/mvt/get_tile.ts @@ -218,7 +218,7 @@ export async function getTile({ // Todo: pass in epochMillies-fields const featureCollection = hitsToGeoJson( - // @ts-expect-error hitsToGeoJson should be refactored to accept estypes.Hit + // @ts-expect-error hitsToGeoJson should be refactored to accept estypes.SearchHit documentsResponse.rawResponse.hits.hits, (hit: Record) => { return flattenHit(geometryFieldName, hit); diff --git a/x-pack/plugins/metrics_entities/server/routes/post_transforms.ts b/x-pack/plugins/metrics_entities/server/routes/post_transforms.ts index d5b5648757e8bd..f5a46ec04611d5 100644 --- a/x-pack/plugins/metrics_entities/server/routes/post_transforms.ts +++ b/x-pack/plugins/metrics_entities/server/routes/post_transforms.ts @@ -37,9 +37,9 @@ export const postTransforms = (router: IRouter): void => { auto_start: autoStart = false, settings: { max_page_search_size: maxPageSearchSize = 500, - docs_per_second: docsPerSecond = null, + docs_per_second: docsPerSecond = undefined, } = { - docsPerSecond: null, + docsPerSecond: undefined, maxPageSearchSize: 500, }, frequency = '1m', diff --git a/x-pack/plugins/metrics_entities/server/services/install_transforms.ts b/x-pack/plugins/metrics_entities/server/services/install_transforms.ts index d0a81955ca1846..eec4f8d555356b 100644 --- a/x-pack/plugins/metrics_entities/server/services/install_transforms.ts +++ b/x-pack/plugins/metrics_entities/server/services/install_transforms.ts @@ -27,7 +27,7 @@ interface CreateTransformOptions { frequency: string; logger: Logger; query: object; - docsPerSecond: number | null; + docsPerSecond: number | undefined; maxPageSearchSize: number; sync: { time: { diff --git a/x-pack/plugins/metrics_entities/server/services/metrics_entities_client_types.ts b/x-pack/plugins/metrics_entities/server/services/metrics_entities_client_types.ts index 1ae9f0d7a2f53f..def26c5342ef94 100644 --- a/x-pack/plugins/metrics_entities/server/services/metrics_entities_client_types.ts +++ b/x-pack/plugins/metrics_entities/server/services/metrics_entities_client_types.ts @@ -21,7 +21,7 @@ export interface PostTransformsOptions { autoStart: boolean; frequency: string; indices: string[]; - docsPerSecond: number | null; + docsPerSecond: number | undefined; maxPageSearchSize: number; prefix: string; query: object; diff --git a/x-pack/plugins/metrics_entities/server/services/post_transforms.ts b/x-pack/plugins/metrics_entities/server/services/post_transforms.ts index 1850047ae1e9db..f14f53d78f10ed 100644 --- a/x-pack/plugins/metrics_entities/server/services/post_transforms.ts +++ b/x-pack/plugins/metrics_entities/server/services/post_transforms.ts @@ -20,7 +20,7 @@ interface PostTransformsOptions { autoStart: boolean; frequency: string; indices: string[]; - docsPerSecond: number | null; + docsPerSecond: number | undefined; kibanaVersion: string; maxPageSearchSize: number; query: object; diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed.ts index 440f4c6e55fb8b..e1a3f6044587bc 100644 --- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed.ts +++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed.ts @@ -9,15 +9,10 @@ import { estypes } from '@elastic/elasticsearch'; export type DatafeedId = string; -export type Datafeed = estypes.Datafeed; +export type Datafeed = estypes.MlDatafeed; -export type ChunkingConfig = estypes.ChunkingConfig; +export type ChunkingConfig = estypes.MlChunkingConfig; -export type Aggregation = Record; +export type Aggregation = Record; -// export type IndicesOptions = estypes.IndicesOptions; -export interface IndicesOptions { - allow_no_indices?: boolean; - expand_wildcards?: estypes.ExpandWildcards; - ignore_unavailable?: boolean; -} +export type IndicesOptions = estypes.MlDatafeedIndicesOptions; diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts index dd0d3a5001f842..4e23d97c0d1453 100644 --- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts +++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts @@ -7,4 +7,4 @@ import { estypes } from '@elastic/elasticsearch'; -export type DatafeedStats = estypes.DatafeedStats; +export type DatafeedStats = estypes.MlDatafeedStats; diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts index 68544e7cb828fc..2ef1d824180ad8 100644 --- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts +++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts @@ -10,23 +10,23 @@ import { estypes } from '@elastic/elasticsearch'; export type JobId = string; export type BucketSpan = string; -export type Job = estypes.Job; +export type Job = estypes.MlJob; -export type AnalysisConfig = estypes.AnalysisConfig; +export type AnalysisConfig = estypes.MlAnalysisConfig; -export type Detector = estypes.Detector; +export type Detector = estypes.MlDetector; -export type AnalysisLimits = estypes.AnalysisLimits; +export type AnalysisLimits = estypes.MlAnalysisLimits; -export type DataDescription = estypes.DataDescription; +export type DataDescription = estypes.MlDataDescription; -export type ModelPlotConfig = estypes.ModelPlotConfig; +export type ModelPlotConfig = estypes.MlModelPlotConfig; -export type CustomRule = estypes.DetectionRule; +export type CustomRule = estypes.MlDetectionRule; export interface PerPartitionCategorization { enabled?: boolean; stop_on_warn?: boolean; } -export type CustomSettings = estypes.CustomSettings; +export type CustomSettings = estypes.MlCustomSettings; diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts index a53f1f2486699b..5fc8b423a5ac22 100644 --- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts +++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts @@ -7,23 +7,14 @@ import { estypes } from '@elastic/elasticsearch'; -export type JobStats = estypes.JobStats & { - model_size_stats: ModelSizeStats; - timing_stats: TimingStats; -}; +export type JobStats = estypes.MlJobStats; -export type DataCounts = estypes.DataCounts; +export type DataCounts = estypes.MlDataCounts; -export type ModelSizeStats = estypes.ModelSizeStats & { - model_bytes_exceeded: number; - model_bytes_memory_limit: number; - peak_model_bytes?: number; -}; +export type ModelSizeStats = estypes.MlModelSizeStats; -export type TimingStats = estypes.TimingStats & { - total_bucket_processing_time_ms: number; -}; +export type TimingStats = estypes.MlTimingStats; -export type ForecastsStats = estypes.JobForecastStatistics; +export type ForecastsStats = estypes.MlJobForecastStatistics; -export type Node = estypes.DiscoveryNode; +export type Node = estypes.MlDiscoveryNode; diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/model_snapshot.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/model_snapshot.ts index f844c42f4ca6eb..0bb2162994c375 100644 --- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/model_snapshot.ts +++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/model_snapshot.ts @@ -5,18 +5,6 @@ * 2.0. */ -import { JobId } from './job'; -import { ModelSizeStats } from './job_stats'; +import { estypes } from '@elastic/elasticsearch'; -export interface ModelSnapshot { - job_id: JobId; - min_version: string; - timestamp: number; - description: string; - snapshot_id: string; - snapshot_doc_count: number; - model_size_stats: ModelSizeStats; - latest_record_time_stamp: number; - latest_result_time_stamp: number; - retain: boolean; -} +export type ModelSnapshot = estypes.MlModelSnapshot; diff --git a/x-pack/plugins/ml/common/types/data_frame_analytics.ts b/x-pack/plugins/ml/common/types/data_frame_analytics.ts index ff5069e7d59ad8..3305eeaaf47945 100644 --- a/x-pack/plugins/ml/common/types/data_frame_analytics.ts +++ b/x-pack/plugins/ml/common/types/data_frame_analytics.ts @@ -76,7 +76,7 @@ export interface DataFrameAnalyticsConfig { }; source: { index: IndexName | IndexName[]; - query?: estypes.QueryContainer; + query?: estypes.QueryDslQueryContainer; runtime_mappings?: RuntimeMappings; }; analysis: AnalysisConfig; diff --git a/x-pack/plugins/ml/common/types/es_client.ts b/x-pack/plugins/ml/common/types/es_client.ts index 249b3c150a082d..67adda6b24c18a 100644 --- a/x-pack/plugins/ml/common/types/es_client.ts +++ b/x-pack/plugins/ml/common/types/es_client.ts @@ -13,13 +13,15 @@ import type { JsonObject } from '../../../../../src/plugins/kibana_utils/common' import { isPopulatedObject } from '../util/object_utils'; -export function isMultiBucketAggregate(arg: unknown): arg is estypes.MultiBucketAggregate { +export function isMultiBucketAggregate( + arg: unknown +): arg is estypes.AggregationsMultiBucketAggregate { return isPopulatedObject(arg, ['buckets']); } export const ES_CLIENT_TOTAL_HITS_RELATION: Record< - Uppercase, - estypes.TotalHitsRelation + Uppercase, + estypes.SearchTotalHitsRelation > = { EQ: 'eq', GTE: 'gte', diff --git a/x-pack/plugins/ml/common/types/fields.ts b/x-pack/plugins/ml/common/types/fields.ts index cf017192353e90..33a4a94e539b87 100644 --- a/x-pack/plugins/ml/common/types/fields.ts +++ b/x-pack/plugins/ml/common/types/fields.ts @@ -28,7 +28,7 @@ export interface Field { aggregatable?: boolean; aggIds?: AggId[]; aggs?: Aggregation[]; - runtimeField?: estypes.RuntimeField; + runtimeField?: estypes.MappingRuntimeField; } export interface Aggregation { @@ -112,4 +112,4 @@ export interface AggCardinality { export type RollupFields = Record]>; -export type RuntimeMappings = estypes.RuntimeFields; +export type RuntimeMappings = estypes.MappingRuntimeFields; diff --git a/x-pack/plugins/ml/common/util/job_utils.ts b/x-pack/plugins/ml/common/util/job_utils.ts index e7608af553f600..2cb803af385798 100644 --- a/x-pack/plugins/ml/common/util/job_utils.ts +++ b/x-pack/plugins/ml/common/util/job_utils.ts @@ -78,7 +78,7 @@ export function isMappableJob(job: CombinedJob, detectorIndex: number): boolean * if composite is defined. * @param buckets */ -export function hasValidComposite(buckets: estypes.AggregationContainer) { +export function hasValidComposite(buckets: estypes.AggregationsAggregationContainer) { if ( isPopulatedObject(buckets, ['composite']) && isPopulatedObject(buckets.composite, ['sources']) && @@ -157,7 +157,7 @@ export function isSourceDataChartableForDetector(job: CombinedJob, detectorIndex } // if fieldName is an aggregated field under nested terms using bucket_script const aggregations = - getAggregations(aggs[aggBucketsName]) ?? {}; + getAggregations(aggs[aggBucketsName]) ?? {}; const foundField = findAggField(aggregations, dtr.field_name, false); if (foundField?.bucket_script !== undefined) { return false; diff --git a/x-pack/plugins/ml/common/util/runtime_field_utils.ts b/x-pack/plugins/ml/common/util/runtime_field_utils.ts index 7be2a3ec8c9e19..1fcf8e2e72b15e 100644 --- a/x-pack/plugins/ml/common/util/runtime_field_utils.ts +++ b/x-pack/plugins/ml/common/util/runtime_field_utils.ts @@ -11,7 +11,7 @@ import type { RuntimeMappings } from '../types/fields'; type RuntimeType = typeof RUNTIME_FIELD_TYPES[number]; -export function isRuntimeField(arg: unknown): arg is estypes.RuntimeField { +export function isRuntimeField(arg: unknown): arg is estypes.MappingRuntimeField { return ( ((isPopulatedObject(arg, ['type']) && Object.keys(arg).length === 1) || (isPopulatedObject(arg, ['type', 'script']) && diff --git a/x-pack/plugins/ml/public/application/components/data_grid/common.ts b/x-pack/plugins/ml/public/application/components/data_grid/common.ts index 24a3cfb70d18d7..a64594e86a7574 100644 --- a/x-pack/plugins/ml/public/application/components/data_grid/common.ts +++ b/x-pack/plugins/ml/public/application/components/data_grid/common.ts @@ -181,7 +181,7 @@ export const getDataGridSchemasFromFieldTypes = (fieldTypes: FieldTypes, results export const NON_AGGREGATABLE = 'non-aggregatable'; export const getDataGridSchemaFromESFieldType = ( - fieldType: ES_FIELD_TYPES | undefined | estypes.RuntimeField['type'] + fieldType: ES_FIELD_TYPES | undefined | estypes.MappingRuntimeField['type'] ): string | undefined => { // Built-in values are ['boolean', 'currency', 'datetime', 'numeric', 'json'] // To fall back to the default string schema it needs to be undefined. diff --git a/x-pack/plugins/ml/public/application/components/data_grid/types.ts b/x-pack/plugins/ml/public/application/components/data_grid/types.ts index 865e09e72b40c6..9dcd6abb432b33 100644 --- a/x-pack/plugins/ml/public/application/components/data_grid/types.ts +++ b/x-pack/plugins/ml/public/application/components/data_grid/types.ts @@ -27,7 +27,7 @@ export type DataGridItem = Record; // `undefined` is used to indicate a non-initialized state. export type ChartsVisible = boolean | undefined; -export type RowCountRelation = estypes.TotalHitsRelation | undefined; +export type RowCountRelation = estypes.SearchTotalHitsRelation | undefined; export type IndexPagination = Pick; diff --git a/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/chart_loader.ts b/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/chart_loader.ts index 15979751f40d69..a9217d884fd32e 100644 --- a/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/chart_loader.ts +++ b/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/chart_loader.ts @@ -31,7 +31,6 @@ export function chartLoaderProvider(mlResultsService: MlResultsService) { job.data_counts.latest_record_timestamp, intervalMs, job.datafeed_config.runtime_mappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options job.datafeed_config.indices_options ); if (resp.error !== undefined) { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts index 88f403cdf0c449..920f56b3767473 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts @@ -67,7 +67,7 @@ export const getIndexData = async ( setRowCount(typeof resp.hits.total === 'number' ? resp.hits.total : resp.hits.total.value); setRowCountRelation( typeof resp.hits.total === 'number' - ? ('eq' as estypes.TotalHitsRelation) + ? ('eq' as estypes.SearchTotalHitsRelation) : resp.hits.total.relation ); setTableItems( diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts index 79986e8ddb098e..72853ec23fd36a 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts @@ -18,7 +18,7 @@ export const CATEGORICAL_TYPES = new Set(['ip', 'keyword']); // Regression supports numeric fields. Classification supports categorical, numeric, and boolean. export const shouldAddAsDepVarOption = ( fieldId: string, - fieldType: ES_FIELD_TYPES | estypes.RuntimeField['type'], + fieldType: ES_FIELD_TYPES | estypes.MappingRuntimeField['type'], jobType: AnalyticsJobType ) => { if (fieldId === EVENT_RATE_FIELD_ID) return false; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts index f3b51acf093adc..ddf88ce79ab5b0 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts @@ -45,7 +45,9 @@ interface MLEuiDataGridColumn extends EuiDataGridColumn { function getRuntimeFieldColumns(runtimeMappings: RuntimeMappings) { return Object.keys(runtimeMappings).map((id) => { const field = runtimeMappings[id]; - const schema = getDataGridSchemaFromESFieldType(field.type as estypes.RuntimeField['type']); + const schema = getDataGridSchemaFromESFieldType( + field.type as estypes.MappingRuntimeField['type'] + ); return { id, schema, isExpandable: schema !== 'boolean', isRuntimeFieldColumn: true }; }); } @@ -194,7 +196,7 @@ export const useIndexData = ( setRowCount(typeof resp.hits.total === 'number' ? resp.hits.total : resp.hits.total.value); setRowCountRelation( typeof resp.hits.total === 'number' - ? ('eq' as estypes.TotalHitsRelation) + ? ('eq' as estypes.SearchTotalHitsRelation) : resp.hits.total.relation ); setTableItems(docs); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts index 45b26226def8f8..35847839b02a02 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts @@ -29,7 +29,7 @@ export interface RichDetector { byField: SplitField; overField: SplitField; partitionField: SplitField; - excludeFrequent: estypes.ExcludeFrequent | null; + excludeFrequent: estypes.MlExcludeFrequent | null; description: string | null; customRules: CustomRule[] | null; useNull: boolean | null; @@ -58,7 +58,7 @@ export class AdvancedJobCreator extends JobCreator { byField: SplitField, overField: SplitField, partitionField: SplitField, - excludeFrequent: estypes.ExcludeFrequent | null, + excludeFrequent: estypes.MlExcludeFrequent | null, description: string | null, useNull: boolean | null ) { @@ -87,7 +87,7 @@ export class AdvancedJobCreator extends JobCreator { byField: SplitField, overField: SplitField, partitionField: SplitField, - excludeFrequent: estypes.ExcludeFrequent | null, + excludeFrequent: estypes.MlExcludeFrequent | null, description: string | null, index: number, useNull: boolean | null @@ -120,7 +120,7 @@ export class AdvancedJobCreator extends JobCreator { byField: SplitField, overField: SplitField, partitionField: SplitField, - excludeFrequent: estypes.ExcludeFrequent | null, + excludeFrequent: estypes.MlExcludeFrequent | null, description: string | null, customRules: CustomRule[] | null, useNull: boolean | null @@ -193,7 +193,6 @@ export class AdvancedJobCreator extends JobCreator { timeFieldName: this.timeFieldName, query: this.query, runtimeMappings: this.datafeedConfig.runtime_mappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options indicesOptions: this.datafeedConfig.indices_options, }); this.setTimeRange(start.epoch, end.epoch); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts index fe0329851758cd..d4a410bcda24cd 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts @@ -226,6 +226,7 @@ export class JobCreator { } public get groups(): string[] { + // @ts-expect-error @elastic-elasticsearch FIXME groups is optional return this._job_config.groups; } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/filter_runtime_mappings.test.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/filter_runtime_mappings.test.ts index 7f1ee2349c2c1b..f81362ad83288a 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/filter_runtime_mappings.test.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/filter_runtime_mappings.test.ts @@ -54,19 +54,19 @@ function getDatafeed(): Datafeed { runtime_mappings: { responsetime_big: { type: 'double', - // @ts-expect-error @elastic/elasticsearch StoredScript.language is required script: { source: "emit(doc['responsetime'].value * 100.0)", }, }, airline_lower: { type: 'keyword', - // @ts-expect-error @elastic/elasticsearch StoredScript.language is required script: { source: "emit(doc['airline'].value.toLowerCase())", }, }, }, + chunking_config: { mode: 'auto' }, + delayed_data_check_config: { enabled: false }, }; } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/categorization_examples_loader.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/categorization_examples_loader.ts index b51cd9b99792b9..641eda3dbf3e81 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/categorization_examples_loader.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/categorization_examples_loader.ts @@ -52,7 +52,6 @@ export class CategorizationExamplesLoader { this._jobCreator.end, analyzer, this._jobCreator.runtimeMappings ?? undefined, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options this._jobCreator.datafeedConfig.indices_options ); return resp; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts index 6d5fa26af70241..a01581f7526c5a 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts @@ -257,7 +257,6 @@ export class ResultsLoader { const fieldValues = await this._chartLoader.loadFieldExampleValues( this._jobCreator.splitField, this._jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options this._jobCreator.datafeedConfig.indices_options ); if (fieldValues.length > 0) { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx index 2b1a35bcb8c46e..237af335ffa51c 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx @@ -173,7 +173,7 @@ export const AdvancedDetectorModal: FC = ({ partitionField, excludeFrequent: excludeFrequentOption.label !== '' - ? (excludeFrequentOption.label as estypes.ExcludeFrequent) + ? (excludeFrequentOption.label as estypes.MlExcludeFrequent) : null, description: descriptionOption !== '' ? descriptionOption : null, customRules: null, @@ -349,7 +349,7 @@ function createFieldOption(field: Field | null): EuiComboBoxOptionOption { } function createExcludeFrequentOption( - excludeFrequent: estypes.ExcludeFrequent | null + excludeFrequent: estypes.MlExcludeFrequent | null ): EuiComboBoxOptionOption { if (excludeFrequent === null) { return emptyOption; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts index 113bde6fbf93d9..85083146c13789 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts @@ -42,7 +42,6 @@ export function useEstimateBucketSpan() { splitField: undefined, timeField: mlContext.currentIndexPattern.timeFieldName, runtimeMappings: jobCreator.runtimeMappings ?? undefined, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options indicesOptions: jobCreator.datafeedConfig.indices_options, }; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/metric_selection_summary.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/metric_selection_summary.tsx index c553da93a4bc0a..9d848542452167 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/metric_selection_summary.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/metric_selection_summary.tsx @@ -56,7 +56,6 @@ export const CategorizationDetectorsSummary: FC = () => { jobCreator.end, chartInterval.getInterval().asMilliseconds(), jobCreator.runtimeMappings ?? undefined, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); setEventRateChartData(resp); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx index 6cbf96fcb04e80..58252feca4b530 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx @@ -114,7 +114,6 @@ export const MultiMetricDetectors: FC = ({ setIsValid }) => { .loadFieldExampleValues( splitField, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ) .then(setFieldValues) @@ -146,7 +145,6 @@ export const MultiMetricDetectors: FC = ({ setIsValid }) => { fieldValues.length > 0 ? fieldValues[0] : null, cs.intervalMs, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); setLineChartsData(resp); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection_summary.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection_summary.tsx index dc76fc01781123..a4c344d16482be 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection_summary.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection_summary.tsx @@ -44,7 +44,6 @@ export const MultiMetricDetectorsSummary: FC = () => { const tempFieldValues = await chartLoader.loadFieldExampleValues( jobCreator.splitField, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); setFieldValues(tempFieldValues); @@ -79,7 +78,6 @@ export const MultiMetricDetectorsSummary: FC = () => { fieldValues.length > 0 ? fieldValues[0] : null, cs.intervalMs, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); setLineChartsData(resp); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx index c5efd4b226d5cc..1be487d5b7eec3 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx @@ -161,7 +161,6 @@ export const PopulationDetectors: FC = ({ setIsValid }) => { jobCreator.splitField, cs.intervalMs, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); @@ -185,7 +184,6 @@ export const PopulationDetectors: FC = ({ setIsValid }) => { fields: await chartLoader.loadFieldExampleValues( field, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ), }; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx index 31b436944a5b08..55a9d37d1115cc 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx @@ -79,7 +79,6 @@ export const PopulationDetectorsSummary: FC = () => { jobCreator.splitField, cs.intervalMs, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); @@ -103,7 +102,6 @@ export const PopulationDetectorsSummary: FC = () => { fields: await chartLoader.loadFieldExampleValues( field, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ), }; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection.tsx index b2a97d8e0589a8..d41234bbedd815 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection.tsx @@ -94,7 +94,6 @@ export const SingleMetricDetectors: FC = ({ setIsValid }) => { null, cs.intervalMs, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); if (resp[DTR_IDX] !== undefined) { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection_summary.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection_summary.tsx index 5e64f4ef189845..ced94b2095f722 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection_summary.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection_summary.tsx @@ -60,7 +60,6 @@ export const SingleMetricDetectorsSummary: FC = () => { null, cs.intervalMs, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); if (resp[DTR_IDX] !== undefined) { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/time_range_step/time_range.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/time_range_step/time_range.tsx index 7e7b919f677ab1..66c92d5c808512 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/time_range_step/time_range.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/time_range_step/time_range.tsx @@ -49,7 +49,6 @@ export const TimeRangeStep: FC = ({ setCurrentStep, isCurrentStep }) jobCreator.end, chartInterval.getInterval().asMilliseconds(), jobCreator.runtimeMappings ?? undefined, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); setEventRateChartData(resp); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx index 6ce808ed36b154..d2780691e551d9 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx @@ -51,9 +51,9 @@ export const EditJob: FC = ({ job, jobOverride, existingGroupIds, ); const handleValidation = () => { - const jobGroupsValidationResult = formState.jobGroups - .map((group) => groupValidator(group)) - .filter((result) => result !== null); + const jobGroupsValidationResult = + formState.jobGroups ?? + [].map((group) => groupValidator(group)).filter((result) => result !== null); setValidationResult({ jobGroups: jobGroupsValidationResult, @@ -92,7 +92,7 @@ export const EditJob: FC = ({ job, jobOverride, existingGroupIds, { setFormState({ jobGroups: value, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx index 311e291cf25194..b97c16e02d9007 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx @@ -87,11 +87,12 @@ export const JobItem: FC = memo( - {jobGroups.map((group) => ( - - {group} - - ))} + {jobGroups ?? + [].map((group) => ( + + {group} + + ))} {setupResult && setupResult.error && ( diff --git a/x-pack/plugins/ml/server/lib/ml_client/ml_client.ts b/x-pack/plugins/ml/server/lib/ml_client/ml_client.ts index 6e76a536feb253..0a9c76893dd0be 100644 --- a/x-pack/plugins/ml/server/lib/ml_client/ml_client.ts +++ b/x-pack/plugins/ml/server/lib/ml_client/ml_client.ts @@ -242,6 +242,7 @@ export function getMlClient( }>(...p); const jobs = await jobSavedObjectService.filterJobsForSpace( 'data-frame-analytics', + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete body.data_frame_analytics, 'id' ); @@ -494,12 +495,13 @@ function getDFAJobIdsFromRequest([params]: MlGetDFAParams): string[] { } function getADJobIdsFromRequest([params]: MlGetADParams): string[] { - const ids = params?.job_id?.split(','); + const ids = typeof params?.job_id === 'string' ? params?.job_id.split(',') : params?.job_id; return ids || []; } function getDatafeedIdsFromRequest([params]: MlGetDatafeedParams): string[] { - const ids = params?.datafeed_id?.split(','); + const ids = + typeof params?.datafeed_id === 'string' ? params?.datafeed_id.split(',') : params?.datafeed_id; return ids || []; } diff --git a/x-pack/plugins/ml/server/lib/query_utils.ts b/x-pack/plugins/ml/server/lib/query_utils.ts index dd4dc01498dbba..e801130643345d 100644 --- a/x-pack/plugins/ml/server/lib/query_utils.ts +++ b/x-pack/plugins/ml/server/lib/query_utils.ts @@ -44,7 +44,7 @@ export function buildBaseFilterCriteria( export function buildSamplerAggregation( aggs: any, samplerShardSize: number -): Record { +): Record { if (samplerShardSize < 1) { return aggs; } diff --git a/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts b/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts index 458a34346bed96..791ba6d79ab5af 100644 --- a/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts +++ b/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts @@ -10,7 +10,7 @@ import { difference } from 'lodash'; import { EventManager } from './event_manager'; import type { MlClient } from '../../lib/ml_client'; -type ScheduledEvent = estypes.ScheduledEvent; +type ScheduledEvent = estypes.MlCalendarEvent; interface BasicCalendar { job_ids: string[]; diff --git a/x-pack/plugins/ml/server/models/calendar/event_manager.ts b/x-pack/plugins/ml/server/models/calendar/event_manager.ts index c870d67524135d..d30297eab5c150 100644 --- a/x-pack/plugins/ml/server/models/calendar/event_manager.ts +++ b/x-pack/plugins/ml/server/models/calendar/event_manager.ts @@ -9,7 +9,7 @@ import { estypes } from '@elastic/elasticsearch'; import { GLOBAL_CALENDAR } from '../../../common/constants/calendars'; import type { MlClient } from '../../lib/ml_client'; -type ScheduledEvent = estypes.ScheduledEvent; +type ScheduledEvent = estypes.MlCalendarEvent; export class EventManager { private _mlClient: MlClient; diff --git a/x-pack/plugins/ml/server/models/data_frame_analytics/analytics_manager.ts b/x-pack/plugins/ml/server/models/data_frame_analytics/analytics_manager.ts index a9c1d95d933a9f..41b8e6dfe96c44 100644 --- a/x-pack/plugins/ml/server/models/data_frame_analytics/analytics_manager.ts +++ b/x-pack/plugins/ml/server/models/data_frame_analytics/analytics_manager.ts @@ -67,6 +67,7 @@ export class AnalyticsManager { async setInferenceModels() { try { const models = await this.getAnalyticsModels(); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete this.inferenceModels = models; } catch (error) { // eslint-disable-next-line @@ -77,6 +78,7 @@ export class AnalyticsManager { async setJobStats() { try { const jobStats = await this.getAnalyticsStats(); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete this.jobStats = jobStats; } catch (error) { // eslint-disable-next-line @@ -133,8 +135,10 @@ export class AnalyticsManager { if (analyticsId !== undefined) { const jobStats = this.findJobStats(analyticsId); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete jobData = { ...jobData, stats: { ...jobStats } }; } else { + // @ts-expect-error @elastic-elasticsearch Data frame types incompletes jobData = jobData.map((job: any) => { const jobStats = this.findJobStats(job.id); return { ...job, stats: { ...jobStats } }; @@ -270,6 +274,7 @@ export class AnalyticsManager { // fetch model data and create model elements let data = await this.getAnalyticsModelData(modelId); const modelNodeId = `${data.model_id}-${JOB_MAP_NODE_TYPES.TRAINED_MODEL}`; + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete const sourceJobId = data?.metadata?.analytics_config?.id; let nextLinkId: string | undefined; let nextType: JobMapNodeTypes | undefined; @@ -288,17 +293,22 @@ export class AnalyticsManager { // fetch source job data and create elements if (sourceJobId !== undefined) { try { + // @ts-expect-error @elastic-elasticsearch Data frame types incompletes data = await this.getAnalyticsData(sourceJobId); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete nextLinkId = data?.source?.index[0]; nextType = JOB_MAP_NODE_TYPES.INDEX; + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete previousNodeId = `${data.id}-${JOB_MAP_NODE_TYPES.ANALYTICS}`; resultElements.push({ data: { id: previousNodeId, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete label: data.id, type: JOB_MAP_NODE_TYPES.ANALYTICS, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete analysisType: getAnalysisType(data?.analysis), }, }); @@ -332,16 +342,20 @@ export class AnalyticsManager { const modelElements = []; const details: any = {}; const data = await this.getAnalyticsData(jobId); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete const nextLinkId = data?.source?.index[0]; const nextType: JobMapNodeTypes = JOB_MAP_NODE_TYPES.INDEX; + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete const previousNodeId = `${data.id}-${JOB_MAP_NODE_TYPES.ANALYTICS}`; resultElements.push({ data: { id: previousNodeId, + // @ts-expect-error @elastic-elasticsearch Data frame types incompletes label: data.id, type: JOB_MAP_NODE_TYPES.ANALYTICS, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete analysisType: getAnalysisType(data?.analysis), isRoot: true, }, @@ -530,20 +544,27 @@ export class AnalyticsManager { const jobs = await this.getAnalyticsData(); const comparator = rootTransform !== undefined ? rootTransform : rootIndexPattern; + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete for (let i = 0; i < jobs.length; i++) { if ( + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete jobs[i]?.source?.index[0] === comparator && + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete this.isDuplicateElement(jobs[i].id, result.elements) === false ) { + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete const nodeId = `${jobs[i].id}-${JOB_MAP_NODE_TYPES.ANALYTICS}`; result.elements.push({ data: { id: nodeId, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete label: jobs[i].id, type: JOB_MAP_NODE_TYPES.ANALYTICS, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete analysisType: getAnalysisType(jobs[i]?.analysis), }, }); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete result.details[nodeId] = jobs[i]; const source = `${comparator}-${JOB_MAP_NODE_TYPES.INDEX}`; result.elements.push({ @@ -555,6 +576,7 @@ export class AnalyticsManager { }); // Get inference model for analytics job and create model node ({ modelElement, modelDetails, edgeElement } = this.getAnalyticsModelElements( + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete jobs[i].id )); if (isAnalyticsMapNodeElement(modelElement)) { @@ -590,10 +612,14 @@ export class AnalyticsManager { if (analyticsId !== undefined) { const jobData = await this.getAnalyticsData(analyticsId); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete const currentJobNodeId = `${jobData.id}-${JOB_MAP_NODE_TYPES.ANALYTICS}`; + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete rootIndex = Array.isArray(jobData?.dest?.index) - ? jobData?.dest?.index[0] - : jobData?.dest?.index; + ? // @ts-expect-error @elastic-elasticsearch Data frame types incomplete + jobData?.dest?.index[0] + : // @ts-expect-error @elastic-elasticsearch Data frame types incomplete + jobData?.dest?.index; rootIndexNodeId = `${rootIndex}-${JOB_MAP_NODE_TYPES.INDEX}`; // Fetch inference model for incoming job id and add node and edge @@ -632,21 +658,28 @@ export class AnalyticsManager { rootIndexNodeId = `${rootIndex}-${JOB_MAP_NODE_TYPES.INDEX}`; } + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete for (let i = 0; i < jobs.length; i++) { if ( + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete jobs[i]?.source?.index[0] === rootIndex && + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete this.isDuplicateElement(jobs[i].id, result.elements) === false ) { // Create node for associated job + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete const nodeId = `${jobs[i].id}-${JOB_MAP_NODE_TYPES.ANALYTICS}`; result.elements.push({ data: { id: nodeId, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete label: jobs[i].id, type: JOB_MAP_NODE_TYPES.ANALYTICS, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete analysisType: getAnalysisType(jobs[i]?.analysis), }, }); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete result.details[nodeId] = jobs[i]; result.elements.push({ diff --git a/x-pack/plugins/ml/server/models/fields_service/fields_service.ts b/x-pack/plugins/ml/server/models/fields_service/fields_service.ts index cfe0bcc5326303..e608bfeb622d8c 100644 --- a/x-pack/plugins/ml/server/models/fields_service/fields_service.ts +++ b/x-pack/plugins/ml/server/models/fields_service/fields_service.ts @@ -185,7 +185,6 @@ export function fieldsServiceProvider({ asCurrentUser }: IScopedClusterClient) { } = await asCurrentUser.search({ index, body, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options ...(datafeedConfig?.indices_options ?? {}), }); @@ -407,7 +406,6 @@ export function fieldsServiceProvider({ asCurrentUser }: IScopedClusterClient) { } = await asCurrentUser.search({ index, body, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options ...(datafeedConfig?.indices_options ?? {}), }); diff --git a/x-pack/plugins/ml/server/models/filter/filter_manager.ts b/x-pack/plugins/ml/server/models/filter/filter_manager.ts index 1429324a6d9c8b..f48b71dedf3ee2 100644 --- a/x-pack/plugins/ml/server/models/filter/filter_manager.ts +++ b/x-pack/plugins/ml/server/models/filter/filter_manager.ts @@ -79,16 +79,16 @@ export class FilterManager { if ( results[FILTERS] && - (results[FILTERS].body as estypes.GetFiltersResponse).filters.length + (results[FILTERS].body as estypes.MlGetFiltersResponse).filters.length ) { let filtersInUse: FiltersInUse = {}; - if (results[JOBS] && (results[JOBS].body as estypes.GetJobsResponse).jobs) { + if (results[JOBS] && (results[JOBS].body as estypes.MlGetJobsResponse).jobs) { filtersInUse = this.buildFiltersInUse( - (results[JOBS].body as estypes.GetJobsResponse).jobs + (results[JOBS].body as estypes.MlGetJobsResponse).jobs ); } - const filter = (results[FILTERS].body as estypes.GetFiltersResponse).filters[0]; + const filter = (results[FILTERS].body as estypes.MlGetFiltersResponse).filters[0]; return { ...filter, used_by: filtersInUse[filter.filter_id], @@ -121,8 +121,10 @@ export class FilterManager { // Build a map of filter_ids against jobs and detectors using that filter. let filtersInUse: FiltersInUse = {}; - if (results[JOBS] && (results[JOBS].body as estypes.GetJobsResponse).jobs) { - filtersInUse = this.buildFiltersInUse((results[JOBS].body as estypes.GetJobsResponse).jobs); + if (results[JOBS] && (results[JOBS].body as estypes.MlGetJobsResponse).jobs) { + filtersInUse = this.buildFiltersInUse( + (results[JOBS].body as estypes.MlGetJobsResponse).jobs + ); } // For each filter, return just @@ -131,16 +133,18 @@ export class FilterManager { // item_count // jobs using the filter const filterStats: FilterStats[] = []; - if (results[FILTERS] && (results[FILTERS].body as estypes.GetFiltersResponse).filters) { - (results[FILTERS].body as estypes.GetFiltersResponse).filters.forEach((filter: Filter) => { - const stats: FilterStats = { - filter_id: filter.filter_id, - description: filter.description, - item_count: filter.items.length, - used_by: filtersInUse[filter.filter_id], - }; - filterStats.push(stats); - }); + if (results[FILTERS] && (results[FILTERS].body as estypes.MlGetFiltersResponse).filters) { + (results[FILTERS].body as estypes.MlGetFiltersResponse).filters.forEach( + (filter: Filter) => { + const stats: FilterStats = { + filter_id: filter.filter_id, + description: filter.description, + item_count: filter.items.length, + used_by: filtersInUse[filter.filter_id], + }; + filterStats.push(stats); + } + ); } return filterStats; diff --git a/x-pack/plugins/ml/server/models/job_service/datafeeds.ts b/x-pack/plugins/ml/server/models/job_service/datafeeds.ts index 72255e168249a1..5dfe1b5934fe9f 100644 --- a/x-pack/plugins/ml/server/models/job_service/datafeeds.ts +++ b/x-pack/plugins/ml/server/models/job_service/datafeeds.ts @@ -28,8 +28,8 @@ export interface MlDatafeedsStatsResponse { interface Results { [id: string]: { - started?: estypes.StartDatafeedResponse['started']; - stopped?: estypes.StopDatafeedResponse['stopped']; + started?: estypes.MlStartDatafeedResponse['started']; + stopped?: estypes.MlStopDatafeedResponse['stopped']; error?: any; }; } @@ -246,7 +246,6 @@ export function datafeedsProvider(client: IScopedClusterClient, mlClient: MlClie job.data_description.time_field, query, datafeed.runtime_mappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options datafeed.indices_options ); @@ -378,7 +377,6 @@ export function datafeedsProvider(client: IScopedClusterClient, mlClient: MlClie const data = { index: datafeed.indices, body, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options ...(datafeed.indices_options ?? {}), }; diff --git a/x-pack/plugins/ml/server/models/job_service/jobs.ts b/x-pack/plugins/ml/server/models/job_service/jobs.ts index a838db443bebcf..b7f8ce569641ed 100644 --- a/x-pack/plugins/ml/server/models/job_service/jobs.ts +++ b/x-pack/plugins/ml/server/models/job_service/jobs.ts @@ -195,7 +195,6 @@ export function jobsProvider( processed_record_count: job.data_counts?.processed_record_count, earliestStartTimestampMs: getEarliestDatafeedStartTime( dataCounts?.latest_record_timestamp, - // @ts-expect-error @elastic/elasticsearch data counts missing is missing latest_bucket_timestamp dataCounts?.latest_bucket_timestamp, parseTimeIntervalForJob(job.analysis_config?.bucket_span) ), @@ -211,7 +210,6 @@ export function jobsProvider( earliestTimestampMs: dataCounts?.earliest_record_timestamp, latestResultsTimestampMs: getLatestDataOrBucketTimestamp( dataCounts?.latest_record_timestamp, - // @ts-expect-error @elastic/elasticsearch data counts missing is missing latest_bucket_timestamp dataCounts?.latest_bucket_timestamp ), isSingleMetricViewerJob: errorMessage === undefined, @@ -254,7 +252,6 @@ export function jobsProvider( if (dataCounts !== undefined) { timeRange.to = getLatestDataOrBucketTimestamp( dataCounts.latest_record_timestamp as number, - // @ts-expect-error @elastic/elasticsearch data counts missing is missing latest_bucket_timestamp dataCounts.latest_bucket_timestamp as number ); timeRange.from = dataCounts.earliest_record_timestamp; @@ -398,7 +395,6 @@ export function jobsProvider( if (jobStatsResults && jobStatsResults.jobs) { const jobStats = jobStatsResults.jobs.find((js) => js.job_id === tempJob.job_id); if (jobStats !== undefined) { - // @ts-expect-error @elastic-elasticsearch JobStats type is incomplete tempJob = { ...tempJob, ...jobStats }; if (jobStats.node) { tempJob.node = jobStats.node; @@ -411,7 +407,6 @@ export function jobsProvider( const latestBucketTimestamp = latestBucketTimestampByJob && latestBucketTimestampByJob[tempJob.job_id]; if (latestBucketTimestamp) { - // @ts-expect-error @elastic/elasticsearch data counts missing is missing latest_bucket_timestamp tempJob.data_counts.latest_bucket_timestamp = latestBucketTimestamp; } } @@ -467,7 +462,6 @@ export function jobsProvider( const jobIds: string[] = []; try { const { body } = await asInternalUser.tasks.list({ - // @ts-expect-error @elastic-elasticsearch expects it to be a string actions, detailed, }); diff --git a/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts index 49c09742985d4d..fad388f791f087 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts @@ -114,7 +114,7 @@ class FieldsService { this._savedObjectsClient ); const rollupConfigs: - | estypes.RollupCapabilitiesJob[] + | estypes.RollupGetRollupCapabilitiesRollupCapabilitySummary[] | null = await rollupService.getRollupJobs(); // if a rollup index has been specified, yet there are no @@ -137,7 +137,9 @@ class FieldsService { } } -function combineAllRollupFields(rollupConfigs: estypes.RollupCapabilitiesJob[]): RollupFields { +function combineAllRollupFields( + rollupConfigs: estypes.RollupGetRollupCapabilitiesRollupCapabilitySummary[] +): RollupFields { const rollupFields: RollupFields = {}; rollupConfigs.forEach((conf) => { Object.keys(conf.fields).forEach((fieldName) => { diff --git a/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts index d83f7afb4cdf6c..5f5ae16ed97334 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts @@ -27,7 +27,9 @@ export async function rollupServiceProvider( const rollupIndexPatternObject = await loadRollupIndexPattern(indexPattern, savedObjectsClient); let jobIndexPatterns: string[] = [indexPattern]; - async function getRollupJobs(): Promise { + async function getRollupJobs(): Promise< + estypes.RollupGetRollupCapabilitiesRollupCapabilitySummary[] | null + > { if (rollupIndexPatternObject !== null) { const parsedTypeMetaData = JSON.parse(rollupIndexPatternObject.attributes.typeMeta); const rollUpIndex: string = parsedTypeMetaData.params.rollup_index; diff --git a/x-pack/plugins/ml/server/models/job_validation/job_validation.ts b/x-pack/plugins/ml/server/models/job_validation/job_validation.ts index 00a51d1e4e1530..80eba7b864051c 100644 --- a/x-pack/plugins/ml/server/models/job_validation/job_validation.ts +++ b/x-pack/plugins/ml/server/models/job_validation/job_validation.ts @@ -69,7 +69,6 @@ export async function validateJob( timeField, job.datafeed_config.query, job.datafeed_config.runtime_mappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options job.datafeed_config.indices_options ); diff --git a/x-pack/plugins/ml/server/routes/anomaly_detectors.ts b/x-pack/plugins/ml/server/routes/anomaly_detectors.ts index 5205ea7353ac61..c5be5e1c9ef2d0 100644 --- a/x-pack/plugins/ml/server/routes/anomaly_detectors.ts +++ b/x-pack/plugins/ml/server/routes/anomaly_detectors.ts @@ -284,7 +284,7 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) { }, routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { try { - const options: estypes.CloseJobRequest = { + const options: estypes.MlCloseJobRequest = { job_id: request.params.jobId, }; const force = request.query.force; @@ -323,7 +323,7 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) { }, routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { try { - const options: estypes.DeleteJobRequest = { + const options: estypes.MlDeleteJobRequest = { job_id: request.params.jobId, wait_for_completion: false, }; @@ -517,13 +517,11 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) { try { const { body } = await mlClient.getOverallBuckets({ job_id: request.params.jobId, - body: { - top_n: request.body.topN, - bucket_span: request.body.bucketSpan, - start: request.body.start !== undefined ? String(request.body.start) : undefined, - end: request.body.end !== undefined ? String(request.body.end) : undefined, - overall_score: request.body.overall_score ?? 0, - }, + top_n: request.body.topN, + bucket_span: request.body.bucketSpan, + start: request.body.start !== undefined ? String(request.body.start) : undefined, + end: request.body.end !== undefined ? String(request.body.end) : undefined, + overall_score: request.body.overall_score ?? 0, }); return response.ok({ body, diff --git a/x-pack/plugins/ml/server/routes/data_frame_analytics.ts b/x-pack/plugins/ml/server/routes/data_frame_analytics.ts index f6dc21538ffa01..2ed4fd6fcd31a4 100644 --- a/x-pack/plugins/ml/server/routes/data_frame_analytics.ts +++ b/x-pack/plugins/ml/server/routes/data_frame_analytics.ts @@ -265,6 +265,7 @@ export function dataFrameAnalyticsRoutes({ router, mlLicense, routeGuard }: Rout const { body } = await mlClient.putDataFrameAnalytics( { id: analyticsId, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete body: request.body, }, getAuthorizationHeader(request) @@ -301,6 +302,7 @@ export function dataFrameAnalyticsRoutes({ router, mlLicense, routeGuard }: Rout try { const { body } = await mlClient.evaluateDataFrame( { + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete body: request.body, }, getAuthorizationHeader(request) @@ -338,6 +340,7 @@ export function dataFrameAnalyticsRoutes({ router, mlLicense, routeGuard }: Rout try { const { body } = await mlClient.explainDataFrameAnalytics( { + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete body: request.body, }, getAuthorizationHeader(request) diff --git a/x-pack/plugins/ml/server/routes/datafeeds.ts b/x-pack/plugins/ml/server/routes/datafeeds.ts index 2013af3ee87352..9f908bf61a35d9 100644 --- a/x-pack/plugins/ml/server/routes/datafeeds.ts +++ b/x-pack/plugins/ml/server/routes/datafeeds.ts @@ -247,7 +247,7 @@ export function dataFeedRoutes({ router, routeGuard }: RouteInitialization) { }, routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { try { - const options: estypes.DeleteDatafeedRequest = { + const options: estypes.MlDeleteDatafeedRequest = { datafeed_id: request.params.datafeedId, }; const force = request.query.force; diff --git a/x-pack/plugins/ml/server/routes/trained_models.ts b/x-pack/plugins/ml/server/routes/trained_models.ts index c4b2d63b05d13e..106010d0f75503 100644 --- a/x-pack/plugins/ml/server/routes/trained_models.ts +++ b/x-pack/plugins/ml/server/routes/trained_models.ts @@ -39,6 +39,7 @@ export function trainedModelsRoutes({ router, routeGuard }: RouteInitialization) const { modelId } = request.params; const { with_pipelines: withPipelines, ...query } = request.query; const { body } = await mlClient.getTrainedModels({ + // @ts-expect-error @elastic-elasticsearch not sure why this is an error, size is a number size: 1000, ...query, ...(modelId ? { model_id: modelId } : {}), diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_available_ccs.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_available_ccs.test.ts index 603c66d2d05f2b..ca8270590da546 100644 --- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_available_ccs.test.ts +++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_available_ccs.test.ts @@ -26,7 +26,7 @@ describe('fetchAvailableCcs', () => { elasticsearchClientMock.createSuccessTransportRequestPromise({ [connectedRemote]: { connected: true, - } as estypes.RemoteInfo, + } as estypes.ClusterRemoteInfoClusterRemoteInfo, }) ); @@ -41,7 +41,7 @@ describe('fetchAvailableCcs', () => { elasticsearchClientMock.createSuccessTransportRequestPromise({ [disconnectedRemote]: { connected: false, - } as estypes.RemoteInfo, + } as estypes.ClusterRemoteInfoClusterRemoteInfo, }) ); diff --git a/x-pack/plugins/observability/server/lib/annotations/mappings.ts b/x-pack/plugins/observability/server/lib/annotations/mappings.ts index da72afdbecb33a..3313c411b58890 100644 --- a/x-pack/plugins/observability/server/lib/annotations/mappings.ts +++ b/x-pack/plugins/observability/server/lib/annotations/mappings.ts @@ -6,7 +6,7 @@ */ export const mappings = { - dynamic: 'strict' as const, + dynamic: 'strict', properties: { annotation: { properties: { @@ -45,4 +45,4 @@ export const mappings = { }, }, }, -}; +} as const; diff --git a/x-pack/plugins/observability/server/utils/create_or_update_index.ts b/x-pack/plugins/observability/server/utils/create_or_update_index.ts index 19b14ef8b24375..7451314ad248c8 100644 --- a/x-pack/plugins/observability/server/utils/create_or_update_index.ts +++ b/x-pack/plugins/observability/server/utils/create_or_update_index.ts @@ -4,12 +4,12 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { CreateIndexRequest, PutMappingRequest } from '@elastic/elasticsearch/api/types'; +import { estypes } from '@elastic/elasticsearch'; import pRetry from 'p-retry'; import { Logger, ElasticsearchClient } from 'src/core/server'; -export type Mappings = Required['body']['mappings'] & - Required['body']; +export type Mappings = Required['body']['mappings'] & + Required['body']; export async function createOrUpdateIndex({ index, @@ -71,7 +71,7 @@ function createNewIndex({ }: { index: string; client: ElasticsearchClient; - mappings: Required['body']['mappings']; + mappings: Required['body']['mappings']; }) { return client.indices.create({ index, @@ -90,7 +90,7 @@ function updateExistingIndex({ }: { index: string; client: ElasticsearchClient; - mappings: PutMappingRequest['body']; + mappings: estypes.IndicesPutMappingRequest['body']; }) { return client.indices.putMapping({ index, diff --git a/x-pack/plugins/observability/server/utils/queries.ts b/x-pack/plugins/observability/server/utils/queries.ts index b7412120365c6f..2ee3291e7fb625 100644 --- a/x-pack/plugins/observability/server/utils/queries.ts +++ b/x-pack/plugins/observability/server/utils/queries.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { ALERT_STATUS } from '@kbn/rule-data-utils/target/technical_field_names'; import { esKuery } from '../../../../../src/plugins/data/server'; import { AlertStatus } from '../../common/typings'; @@ -18,7 +18,11 @@ export function alertStatusQuery(status: AlertStatus) { return [{ term: { [ALERT_STATUS]: status } }]; } -export function rangeQuery(start?: number, end?: number, field = '@timestamp'): QueryContainer[] { +export function rangeQuery( + start?: number, + end?: number, + field = '@timestamp' +): estypes.QueryDslQueryContainer[] { return [ { range: { @@ -32,7 +36,7 @@ export function rangeQuery(start?: number, end?: number, field = '@timestamp'): ]; } -export function kqlQuery(kql?: string): QueryContainer[] { +export function kqlQuery(kql?: string): estypes.QueryDslQueryContainer[] { if (!kql) { return []; } diff --git a/x-pack/plugins/osquery/common/search_strategy/osquery/index.ts b/x-pack/plugins/osquery/common/search_strategy/osquery/index.ts index d07af8c878c510..fb3bd92abb4c91 100644 --- a/x-pack/plugins/osquery/common/search_strategy/osquery/index.ts +++ b/x-pack/plugins/osquery/common/search_strategy/osquery/index.ts @@ -37,7 +37,7 @@ export type FactoryQueryTypes = OsqueryQueries; export interface RequestBasicOptions extends IEsSearchRequest { filterQuery: ESQuery | string | undefined; - aggregations?: Record; + aggregations?: Record; docValueFields?: DocValueFields[]; factoryQueryType?: FactoryQueryTypes; } diff --git a/x-pack/plugins/osquery/public/agents/helpers.ts b/x-pack/plugins/osquery/public/agents/helpers.ts index a79933db0ceb08..df966a01f1de1e 100644 --- a/x-pack/plugins/osquery/public/agents/helpers.ts +++ b/x-pack/plugins/osquery/public/agents/helpers.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Aggregate, TermsAggregate } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { euiPaletteColorBlindBehindText } from '@elastic/eui'; import { PaginationInputPaginated, @@ -40,11 +40,11 @@ export const getNumOverlapped = ( }); return sum; }; -export const processAggregations = (aggs: Record) => { +export const processAggregations = (aggs: Record) => { const platforms: Group[] = []; const overlap: Overlap = {}; - const platformTerms = aggs.platforms as TermsAggregate; - const policyTerms = aggs.policies as TermsAggregate; + const platformTerms = aggs.platforms as estypes.AggregationsTermsAggregate; + const policyTerms = aggs.policies as estypes.AggregationsTermsAggregate; const policies = policyTerms?.buckets.map((o) => ({ name: o.key, id: o.key, size: o.doc_count })) ?? []; diff --git a/x-pack/plugins/osquery/public/agents/types.ts b/x-pack/plugins/osquery/public/agents/types.ts index 302b2686d511eb..bfe59c91d007d5 100644 --- a/x-pack/plugins/osquery/public/agents/types.ts +++ b/x-pack/plugins/osquery/public/agents/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { TermsAggregate } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { EuiComboBoxOptionOption } from '@elastic/eui'; import { Agent } from '../../common/shared_imports'; @@ -15,7 +15,7 @@ interface BaseDataPoint { } export type AggregationDataPoint = BaseDataPoint & { - [key: string]: TermsAggregate; + [key: string]: estypes.AggregationsTermsAggregate; }; export interface Group { diff --git a/x-pack/plugins/osquery/server/search_strategy/osquery/factory/actions/results/query.action_results.dsl.ts b/x-pack/plugins/osquery/server/search_strategy/osquery/factory/actions/results/query.action_results.dsl.ts index e8a8fbd63a84db..d74067bff02519 100644 --- a/x-pack/plugins/osquery/server/search_strategy/osquery/factory/actions/results/query.action_results.dsl.ts +++ b/x-pack/plugins/osquery/server/search_strategy/osquery/factory/actions/results/query.action_results.dsl.ts @@ -52,7 +52,7 @@ export const buildActionResultsQuery = ({ lang: 'painless', source: "if (doc['error.keyword'].size()==0) { return 'success' } else { return 'error' }", - }, + } as const, }, }, }, diff --git a/x-pack/plugins/reporting/server/lib/store/mapping.ts b/x-pack/plugins/reporting/server/lib/store/mapping.ts index c35540f3869a03..ce8f768ef077fb 100644 --- a/x-pack/plugins/reporting/server/lib/store/mapping.ts +++ b/x-pack/plugins/reporting/server/lib/store/mapping.ts @@ -63,4 +63,4 @@ export const mapping = { content: { type: 'object', enabled: false }, }, }, -}; +} as const; diff --git a/x-pack/plugins/rollup/server/collectors/helpers.ts b/x-pack/plugins/rollup/server/collectors/helpers.ts index 3ec457bc6191e6..1d1a8755aa5680 100644 --- a/x-pack/plugins/rollup/server/collectors/helpers.ts +++ b/x-pack/plugins/rollup/server/collectors/helpers.ts @@ -81,7 +81,6 @@ const getSavedObjectsList = async ({ ignore_unavailable: true, index: kibanaIndex, size: ES_MAX_RESULT_WINDOW_DEFAULT_VALUE, - // @ts-expect-error@elastic/elasticsearch _source does not exist in type SearchRequest _source: filterPath, }); return esResponse; diff --git a/x-pack/plugins/rule_registry/common/mapping_from_field_map.ts b/x-pack/plugins/rule_registry/common/mapping_from_field_map.ts index 17eb5ae8967af4..74681a6aad4ee6 100644 --- a/x-pack/plugins/rule_registry/common/mapping_from_field_map.ts +++ b/x-pack/plugins/rule_registry/common/mapping_from_field_map.ts @@ -5,11 +5,11 @@ * 2.0. */ -import { TypeMapping } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { set } from '@elastic/safer-lodash-set'; import { FieldMap } from './field_map/types'; -export function mappingFromFieldMap(fieldMap: FieldMap): TypeMapping { +export function mappingFromFieldMap(fieldMap: FieldMap): estypes.MappingTypeMapping { const mappings = { dynamic: 'strict' as const, properties: {}, diff --git a/x-pack/plugins/rule_registry/common/types.ts b/x-pack/plugins/rule_registry/common/types.ts index 299d2c300ab49c..858b1a5af431fd 100644 --- a/x-pack/plugins/rule_registry/common/types.ts +++ b/x-pack/plugins/rule_registry/common/types.ts @@ -7,7 +7,7 @@ import { estypes } from '@elastic/elasticsearch'; -export type PutIndexTemplateRequest = estypes.PutIndexTemplateRequest & { +export type PutIndexTemplateRequest = estypes.IndicesPutIndexTemplateRequest & { body?: { composed_of?: string[] }; }; @@ -16,6 +16,6 @@ export interface ClusterPutComponentTemplateBody { settings: { number_of_shards: number; }; - mappings: estypes.TypeMapping; + mappings: estypes.MappingTypeMapping; }; } diff --git a/x-pack/plugins/rule_registry/server/event_log/elasticsearch/index_management_gateway.ts b/x-pack/plugins/rule_registry/server/event_log/elasticsearch/index_management_gateway.ts index 96b5860e143eea..cb04a442d0b344 100644 --- a/x-pack/plugins/rule_registry/server/event_log/elasticsearch/index_management_gateway.ts +++ b/x-pack/plugins/rule_registry/server/event_log/elasticsearch/index_management_gateway.ts @@ -93,6 +93,7 @@ export class IndexManagementGateway { this.logger.debug(`Updating index template; name="${templateName}"`); try { + // @ts-expect-error settings is optional const { settings, ...templateWithoutSettings } = template; const es = await this.elasticsearch; diff --git a/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/ilm_policy.ts b/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/ilm_policy.ts index 00fc9131523ace..7663ea27fb0df6 100644 --- a/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/ilm_policy.ts +++ b/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/ilm_policy.ts @@ -8,7 +8,7 @@ import { estypes } from '@elastic/elasticsearch'; export interface IlmPolicy { - policy: estypes.Policy; + policy: estypes.IlmPolicy; } export const defaultIlmPolicy: IlmPolicy = { diff --git a/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/index_template.ts b/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/index_template.ts index caf71dadf6e1e5..0045bce3ed8735 100644 --- a/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/index_template.ts +++ b/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/index_template.ts @@ -9,7 +9,7 @@ import { estypes } from '@elastic/elasticsearch'; import { IndexNames } from './index_names'; import { IndexMappings } from './index_mappings'; -export type IndexTemplate = estypes.PutIndexTemplateRequest['body']; +export type IndexTemplate = estypes.IndicesPutTemplateRequest['body']; export const createIndexTemplate = ( names: IndexNames, @@ -39,6 +39,7 @@ export const createIndexTemplate = ( order: 'desc', }, }, + // @ts-expect-error IndexMappings is not assignale to estypes.MappingTypeMapping mappings: { ...mappings, _meta: { diff --git a/x-pack/plugins/rule_registry/server/event_log/log/event_query_builder.ts b/x-pack/plugins/rule_registry/server/event_log/log/event_query_builder.ts index 48228ce5352b7b..bf9aca74f78002 100644 --- a/x-pack/plugins/rule_registry/server/event_log/log/event_query_builder.ts +++ b/x-pack/plugins/rule_registry/server/event_log/log/event_query_builder.ts @@ -78,8 +78,8 @@ export class EventQueryBuilder implements IEventQueryBuilder { return new EventQuery({ indexReader, request }); } - private buildFilter(): estypes.QueryContainer[] { - const result: estypes.QueryContainer[] = []; + private buildFilter(): estypes.QueryDslQueryContainer[] { + const result: estypes.QueryDslQueryContainer[] = []; if (this.loggerName) { result.push({ diff --git a/x-pack/plugins/rule_registry/server/event_log/log/public_api.ts b/x-pack/plugins/rule_registry/server/event_log/log/public_api.ts index 7807dd9ca6b36b..7dcaee9d382b10 100644 --- a/x-pack/plugins/rule_registry/server/event_log/log/public_api.ts +++ b/x-pack/plugins/rule_registry/server/event_log/log/public_api.ts @@ -101,7 +101,7 @@ export interface IEventQueryBuilder { buildQuery(): IEventQuery; } -export type SortingParams = estypes.Sort; +export type SortingParams = estypes.SearchSort; export interface PaginationParams { page: number; diff --git a/x-pack/plugins/rule_registry/server/rule_data_client/index.ts b/x-pack/plugins/rule_registry/server/rule_data_client/index.ts index c13202d3dd4321..cb336580ca3540 100644 --- a/x-pack/plugins/rule_registry/server/rule_data_client/index.ts +++ b/x-pack/plugins/rule_registry/server/rule_data_client/index.ts @@ -4,8 +4,9 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ + import { isEmpty } from 'lodash'; -import { TypeMapping } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { ResponseError } from '@elastic/elasticsearch/lib/errors'; import { IndexPatternsFetcher } from '../../../../../src/plugins/data/server'; import { @@ -137,7 +138,7 @@ export class RuleDataClient implements IRuleDataClient { path: `/_index_template/_simulate_index/${concreteIndexName}`, }); - const mappings: TypeMapping = simulateResponse.template.mappings; + const mappings: estypes.MappingTypeMapping = simulateResponse.template.mappings; if (isEmpty(mappings)) { throw new Error( diff --git a/x-pack/plugins/rule_registry/server/rule_data_plugin_service/index.ts b/x-pack/plugins/rule_registry/server/rule_data_plugin_service/index.ts index 159e9b81525974..22435ef8c02038 100644 --- a/x-pack/plugins/rule_registry/server/rule_data_plugin_service/index.ts +++ b/x-pack/plugins/rule_registry/server/rule_data_plugin_service/index.ts @@ -110,7 +110,7 @@ export class RuleDataPluginService { return clusterClient.indices.putIndexTemplate(template); } - private async _createOrUpdateLifecyclePolicy(policy: estypes.PutLifecycleRequest) { + private async _createOrUpdateLifecyclePolicy(policy: estypes.IlmPutLifecycleRequest) { this.assertWriteEnabled(); const clusterClient = await this.getClusterClient(); @@ -130,7 +130,7 @@ export class RuleDataPluginService { return this._createOrUpdateIndexTemplate(template); } - async createOrUpdateLifecyclePolicy(policy: estypes.PutLifecycleRequest) { + async createOrUpdateLifecyclePolicy(policy: estypes.IlmPutLifecycleRequest) { await this.wait(); return this._createOrUpdateLifecyclePolicy(policy); } diff --git a/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts b/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts index e3a586062ae4c8..29849497e02ec5 100644 --- a/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts +++ b/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts @@ -17,7 +17,10 @@ export function defineGetBuiltinPrivilegesRoutes({ router }: RouteDefinitionPara // Exclude the `none` privilege, as it doesn't make sense as an option within the Kibana UI privileges.cluster = privileges.cluster.filter((privilege) => privilege !== 'none'); - privileges.index = privileges.index.filter((privilege) => privilege !== 'none'); + const indexPriviledges = Array.isArray(privileges.index) + ? privileges.index + : [privileges.index]; + privileges.index = indexPriviledges.filter((privilege) => privilege !== 'none'); return response.ok({ body: privileges }); } diff --git a/x-pack/plugins/security/server/routes/authorization/roles/put.ts b/x-pack/plugins/security/server/routes/authorization/roles/put.ts index 09bcb6b8c505ce..5a0934721e20ce 100644 --- a/x-pack/plugins/security/server/routes/authorization/roles/put.ts +++ b/x-pack/plugins/security/server/routes/authorization/roles/put.ts @@ -72,7 +72,6 @@ export function definePutRolesRoutes({ const body = transformPutPayloadToElasticsearchRole( request.body, authz.applicationName, - // @ts-expect-error @elastic/elasticsearch `XPackRole` type doesn't define `applications`. rawRoles[name] ? rawRoles[name].applications : [] ); diff --git a/x-pack/plugins/security/server/session_management/session_index.ts b/x-pack/plugins/security/server/session_management/session_index.ts index d7a4c3e2520bf2..9093d5d2e0db27 100644 --- a/x-pack/plugins/security/server/session_management/session_index.ts +++ b/x-pack/plugins/security/server/session_management/session_index.ts @@ -52,7 +52,7 @@ export function getSessionIndexTemplate(indexName: string) { }, }, mappings: { - dynamic: 'strict' as 'strict', + dynamic: 'strict', properties: { usernameHash: { type: 'keyword' }, provider: { properties: { name: { type: 'keyword' }, type: { type: 'keyword' } } }, @@ -61,7 +61,7 @@ export function getSessionIndexTemplate(indexName: string) { accessAgreementAcknowledged: { type: 'boolean' }, content: { type: 'binary' }, }, - }, + } as const, }); } diff --git a/x-pack/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts b/x-pack/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts index 6e508a099003a2..58e7539b1f617a 100644 --- a/x-pack/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts +++ b/x-pack/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts @@ -51,13 +51,16 @@ export class FleetAgentGenerator extends BaseDataGenerator { * @param [overrides] any partial value to the full document */ generateEsHit( - overrides: DeepPartial> = {} - ): estypes.Hit { + overrides: DeepPartial> = {} + ): estypes.SearchHit { const hostname = this.randomHostname(); const now = new Date().toISOString(); const osFamily = this.randomOSFamily(); - return merge, DeepPartial>>( + return merge< + estypes.SearchHit, + DeepPartial> + >( { _index: AGENTS_INDEX, _id: this.randomUUID(), diff --git a/x-pack/plugins/security_solution/common/endpoint/index_data.ts b/x-pack/plugins/security_solution/common/endpoint/index_data.ts index 021b9bcb1ecccf..4996d90288ca9a 100644 --- a/x-pack/plugins/security_solution/common/endpoint/index_data.ts +++ b/x-pack/plugins/security_solution/common/endpoint/index_data.ts @@ -121,7 +121,7 @@ async function indexHostDocs({ const kibanaVersion = await fetchKibanaVersion(kbnClient); let hostMetadata: HostMetadata; let wasAgentEnrolled = false; - let enrolledAgent: undefined | estypes.Hit; + let enrolledAgent: undefined | estypes.SearchHit; for (let j = 0; j < numDocs; j++) { generator.updateHostData(); @@ -373,7 +373,7 @@ const indexFleetAgentForHost = async ( endpointHost: HostMetadata, agentPolicyId: string, kibanaVersion: string = '8.0.0' -): Promise> => { +): Promise> => { const agentDoc = fleetAgentGenerator.generateEsHit({ _source: { local_metadata: { diff --git a/x-pack/plugins/security_solution/common/search_strategy/common/index.ts b/x-pack/plugins/security_solution/common/search_strategy/common/index.ts index e27e9b5173fd59..4fcfbdac3c1b4c 100644 --- a/x-pack/plugins/security_solution/common/search_strategy/common/index.ts +++ b/x-pack/plugins/security_solution/common/search_strategy/common/index.ts @@ -70,7 +70,7 @@ export interface PaginationInputPaginated { querySize: number; } -export type DocValueFields = estypes.DocValueField; +export type DocValueFields = estypes.SearchDocValueField; export interface Explanation { value: number; diff --git a/x-pack/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts b/x-pack/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts index 34b32115a089d8..e8578b4c070633 100644 --- a/x-pack/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts +++ b/x-pack/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts @@ -25,5 +25,5 @@ export interface HostDetailsRequestOptions extends Partial { }); it('properly transforms the response', async () => { + // @ts-expect-error mocking only what we need esClient.indices.getMapping.mockResolvedValue({ body: { - // @ts-expect-error mocking only what we need index1: { mappings: { _meta: { version: 3 } } }, }, }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/migration_cleanup.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/migration_cleanup.ts index 9c40778d46704e..00446a204ca895 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/migration_cleanup.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/migration_cleanup.ts @@ -86,7 +86,7 @@ export const applyMigrationCleanupPolicy = async ({ await esClient.indices.putSettings({ index, body: { - index: { + settings: { lifecycle: { name: getMigrationCleanupPolicyName(alias), }, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/reference_rules/query.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/reference_rules/query.ts index 3911dcabc34de8..04bfa78f883f01 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/reference_rules/query.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/reference_rules/query.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema } from '@kbn/config-schema'; import { Logger } from '@kbn/logging'; import { ESSearchRequest } from 'typings/elasticsearch'; @@ -60,7 +60,7 @@ export const createQueryAlertType = (ruleDataClient: RuleDataClient, logger: Log indexPattern, { query: customQuery, language: 'kuery' }, [] - ) as QueryContainer; + ) as estypes.QueryDslQueryContainer; const query: ESSearchRequest = { body: { query: esQuery, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.ts index 04144395803619..7b27d22d9b3873 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.ts @@ -5,7 +5,6 @@ * 2.0. */ import type { estypes } from '@elastic/elasticsearch'; -import { SortResults } from '@elastic/elasticsearch/api/types'; import { isEmpty } from 'lodash'; import { SortOrderOrUndefined, @@ -13,14 +12,14 @@ import { } from '../../../../common/detection_engine/schemas/common/schemas'; interface BuildEventsSearchQuery { - aggregations?: Record; + aggregations?: Record; index: string[]; from: string; to: string; - filter: estypes.QueryContainer; + filter: estypes.QueryDslQueryContainer; size: number; sortOrder?: SortOrderOrUndefined; - searchAfterSortIds: SortResults | undefined; + searchAfterSortIds: estypes.SearchSortResults | undefined; timestampOverride: TimestampOverrideOrUndefined; } @@ -43,7 +42,7 @@ export const buildEventsSearchQuery = ({ format: 'strict_date_optional_time', })); - const rangeFilter: estypes.QueryContainer[] = + const rangeFilter: estypes.QueryDslQueryContainer[] = timestampOverride != null ? [ { @@ -93,7 +92,7 @@ export const buildEventsSearchQuery = ({ }, ]; - const filterWithTime: estypes.QueryContainer[] = [ + const filterWithTime: estypes.QueryDslQueryContainer[] = [ filter, { bool: { filter: [{ bool: { should: [...rangeFilter], minimum_should_match: 1 } }] } }, ]; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events.ts index a50d40e33a7171..da664f65c2d506 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events.ts @@ -16,7 +16,7 @@ import { FilterEventsOptions } from './types'; export const filterEvents = ({ events, fieldAndSetTuples, -}: FilterEventsOptions): Array> => { +}: FilterEventsOptions): Array> => { return events.filter((item) => { return fieldAndSetTuples .map((tuple) => { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events_against_list.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events_against_list.ts index 5907cbdfb7fdd5..fffe971753f87f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events_against_list.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events_against_list.ts @@ -58,9 +58,9 @@ export const filterEventsAgainstList = async ({ return listItem.entries.every((entry) => entriesList.is(entry)); }); - const res = await valueListExceptionItems.reduce>>>( + const res = await valueListExceptionItems.reduce>>>( async ( - filteredAccum: Promise>>, + filteredAccum: Promise>>, exceptionItem: ExceptionListItemSchema ) => { const events = await filteredAccum; @@ -78,7 +78,7 @@ export const filterEventsAgainstList = async ({ ); return filteredEvents; }, - Promise.resolve>>(eventSearchResult.hits.hits) + Promise.resolve>>(eventSearchResult.hits.hits) ); return { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/types.ts index 1252ca3f5faa57..160506b965bf0e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/types.ts @@ -20,7 +20,7 @@ export interface FilterEventsAgainstListOptions { } export interface CreateSetToFilterAgainstOptions { - events: Array>; + events: Array>; field: string; listId: string; listType: Type; @@ -30,12 +30,12 @@ export interface CreateSetToFilterAgainstOptions { } export interface FilterEventsOptions { - events: Array>; + events: Array>; fieldAndSetTuples: FieldSet[]; } export interface CreateFieldAndSetTuplesOptions { - events: Array>; + events: Array>; exceptionItem: ExceptionListItemSchema; listClient: ListClient; logger: Logger; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts index 08f8abe384d0f7..b0dcc1810a6396 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts @@ -6,7 +6,7 @@ */ import { identity } from 'lodash'; -import { SortResults } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { singleSearchAfter } from './single_search_after'; import { singleBulkCreate } from './single_bulk_create'; import { filterEventsAgainstList } from './filters/filter_events_against_list'; @@ -44,7 +44,7 @@ export const searchAfterAndBulkCreate = async ({ let toReturn = createSearchAfterReturnType(); // sortId tells us where to start our next consecutive search_after query - let sortIds: SortResults | undefined; + let sortIds: estypes.SearchSortResults | undefined; let hasSortId = true; // default to true so we execute the search on initial run // signalsCreatedCount keeps track of how many signals we have created, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.test.ts index 66f7d41df94ab6..823d694f36514d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.test.ts @@ -157,7 +157,7 @@ describe('signal_rule_alert_type', () => { (mlExecutor as jest.Mock).mockClear(); (mlExecutor as jest.Mock).mockResolvedValue(executorReturnValue); (parseScheduleDates as jest.Mock).mockReturnValue(moment(100)); - const value: Partial> = { + const value: Partial> = { statusCode: 200, body: { indices: ['index1', 'index2', 'index3', 'index4'], @@ -174,7 +174,7 @@ describe('signal_rule_alert_type', () => { }, }; alertServices.scopedClusterClient.asCurrentUser.fieldCaps.mockResolvedValue( - value as ApiResponse + value as ApiResponse ); const ruleAlert = getAlertMock(getQueryRuleParams()); alertServices.savedObjectsClient.get.mockResolvedValue({ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts index ae22964eced927..6436da40088b35 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts @@ -6,7 +6,6 @@ */ import type { estypes } from '@elastic/elasticsearch'; import { performance } from 'perf_hooks'; -import { SearchRequest, SortResults } from '@elastic/elasticsearch/api/types'; import { AlertInstanceContext, AlertInstanceState, @@ -23,8 +22,8 @@ import { } from '../../../../common/detection_engine/schemas/common/schemas'; interface SingleSearchAfterParams { - aggregations?: Record; - searchAfterSortIds: SortResults | undefined; + aggregations?: Record; + searchAfterSortIds: estypes.SearchSortResults | undefined; index: string[]; from: string; to: string; @@ -32,7 +31,7 @@ interface SingleSearchAfterParams { logger: Logger; pageSize: number; sortOrder?: SortOrderOrUndefined; - filter: estypes.QueryContainer; + filter: estypes.QueryDslQueryContainer; timestampOverride: TimestampOverrideOrUndefined; buildRuleMessage: BuildRuleMessage; } @@ -73,7 +72,7 @@ export const singleSearchAfter = async ({ const { body: nextSearchAfterResult, } = await services.scopedClusterClient.asCurrentUser.search( - searchAfterQuery as SearchRequest + searchAfterQuery as estypes.SearchRequest ); const end = performance.now(); const searchErrors = createErrorsFromShard({ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/create_threat_signals.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/create_threat_signals.ts index ade85db0e4ba6c..b3e0e376c7794a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/create_threat_signals.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/create_threat_signals.ts @@ -154,7 +154,7 @@ export const createThreatSignals = async ({ language: threatLanguage, threatFilters, index: threatIndex, - // @ts-expect-error@elastic/elasticsearch SortResults might contain null + // @ts-expect-error@elastic/elasticsearch SearchSortResults might contain null searchAfter: threatList.hits.hits[threatList.hits.hits.length - 1].sort, sortField: undefined, sortOrder: undefined, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/get_threat_list.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/get_threat_list.ts index c3d3d6c6a99e13..3ff23e27547b46 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/get_threat_list.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/get_threat_list.ts @@ -54,7 +54,7 @@ export const getThreatList = async ({ ); const { body: response } = await esClient.search({ body: { - // @ts-expect-error ESBoolQuery is not assignale to QueryContainer + // @ts-expect-error ESBoolQuery is not assignale to QueryDslQueryContainer query: queryFilter, fields: [ { @@ -125,7 +125,7 @@ export const getThreatListCount = async ({ ); const { body: response } = await esClient.count({ body: { - // @ts-expect-error ESBoolQuery is not assignale to QueryContainer + // @ts-expect-error ESBoolQuery is not assignale to QueryDslQueryContainer query: queryFilter, }, ignore_unavailable: true, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/types.ts index 094c4d74d8ac72..acb64f826f3f24 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/types.ts @@ -167,7 +167,7 @@ export interface ThreatListDoc { * This is an ECS document being returned, but the user could return or use non-ecs based * documents potentially. */ -export type ThreatListItem = estypes.Hit; +export type ThreatListItem = estypes.SearchHit; export interface ThreatIndicator { [key: string]: unknown; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts index 8f34e58ebc85bc..4205c2d6d8b2c5 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts @@ -153,9 +153,9 @@ export interface GetResponse { } export type SignalSearchResponse = estypes.SearchResponse; -export type SignalSourceHit = estypes.Hit; +export type SignalSourceHit = estypes.SearchHit; export type WrappedSignalHit = BaseHit; -export type BaseSignalHit = estypes.Hit; +export type BaseSignalHit = estypes.SearchHit; export type EqlSignalSearchResponse = EqlSearchResponse; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts index dde9986e8bdf58..1de76f64fabec0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts @@ -13,7 +13,6 @@ import type { estypes } from '@elastic/elasticsearch'; import { chunk, isEmpty, partition } from 'lodash'; import { ApiResponse, Context } from '@elastic/elasticsearch/lib/Transport'; -import { SortResults } from '@elastic/elasticsearch/api/types'; import type { ListArray, ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; import { MAX_EXCEPTION_LIST_SIZE } from '@kbn/securitysolution-list-constants'; import { hasLargeValueList } from '@kbn/securitysolution-list-utils'; @@ -875,10 +874,10 @@ export const isMachineLearningParams = (params: RuleParams): params is MachineLe * Ref: https://github.com/elastic/elasticsearch/issues/28806#issuecomment-369303620 * * return stringified Long.MAX_VALUE if we receive Number.MAX_SAFE_INTEGER - * @param sortIds SortResults | undefined + * @param sortIds estypes.SearchSortResults | undefined * @returns SortResults */ -export const getSafeSortIds = (sortIds: SortResults | undefined) => { +export const getSafeSortIds = (sortIds: estypes.SearchSortResults | undefined) => { return sortIds?.map((sortId) => { // haven't determined when we would receive a null value for a sort id // but in case we do, default to sending the stringified Java max_int diff --git a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query.dsl.ts b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query.dsl.ts index e960067713bda2..325d45e04b2b03 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query.dsl.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query.dsl.ts @@ -75,7 +75,7 @@ export const buildQuery = ({ order: [ { 'successes.doc_count': 'desc' as const }, { 'failures.doc_count': 'desc' as const }, - ] as estypes.TermsAggregationOrder, + ] as estypes.AggregationsTermsAggregationOrder, }, aggs: { failures: { diff --git a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query_entities.dsl.ts b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query_entities.dsl.ts index 51d80152d65c04..d320130115588d 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query_entities.dsl.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query_entities.dsl.ts @@ -52,7 +52,10 @@ export const buildQueryEntities = ({ terms: { size: querySize, field: 'user.name', - order: [{ successes: 'desc' }, { failures: 'desc' }] as estypes.TermsAggregationOrder, + order: [ + { successes: 'desc' }, + { failures: 'desc' }, + ] as estypes.AggregationsTermsAggregationOrder, }, aggs: { failures: { diff --git a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/overview/query.overview_host.dsl.ts b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/overview/query.overview_host.dsl.ts index 897ae633076a21..a0ae368ac0fe28 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/overview/query.overview_host.dsl.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/overview/query.overview_host.dsl.ts @@ -293,6 +293,6 @@ export const buildOverviewHostQuery = ({ }, } as const; - // @ts-expect-error @elastic-elasticsearch readonly [] is not assignable to mutable QueryContainer[] + // @ts-expect-error @elastic-elasticsearch readonly [] is not assignable to mutable QueryDslQueryContainer[] return dslQuery; }; diff --git a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/dsl/query.dsl.ts b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/dsl/query.dsl.ts index 1df0d60d54a88a..5d4f45c68160a8 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/dsl/query.dsl.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/dsl/query.dsl.ts @@ -68,7 +68,7 @@ export const buildQuery = ({ { _key: 'asc' as const, }, - ] as estypes.TermsAggregationOrder, + ] as estypes.AggregationsTermsAggregationOrder, }, aggregations: { process: { @@ -120,7 +120,7 @@ export const buildQuery = ({ 'event.action': 'executed', }, }, - ] as estypes.QueryContainer[], + ] as estypes.QueryDslQueryContainer[], }, }, { @@ -146,7 +146,7 @@ export const buildQuery = ({ 'event.action': 'process_started', }, }, - ] as estypes.QueryContainer[], + ] as estypes.QueryDslQueryContainer[], }, }, { diff --git a/x-pack/plugins/snapshot_restore/server/routes/api/policy.ts b/x-pack/plugins/snapshot_restore/server/routes/api/policy.ts index 77264c4bffc9a2..52e4e7011f0d41 100644 --- a/x-pack/plugins/snapshot_restore/server/routes/api/policy.ts +++ b/x-pack/plugins/snapshot_restore/server/routes/api/policy.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { PutSnapshotLifecycleRequest } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema, TypeOf } from '@kbn/config-schema'; import { SlmPolicyEs, PolicyIndicesResponse } from '../../../common/types'; @@ -103,7 +103,7 @@ export function registerPolicyRoutes({ const response = await clusterClient.asCurrentUser.slm.putLifecycle({ policy_id: name, // TODO: bring {@link SlmPolicyEs['policy']} in line with {@link PutSnapshotLifecycleRequest['body']} - body: (serializePolicy(policy) as unknown) as PutSnapshotLifecycleRequest['body'], + body: (serializePolicy(policy) as unknown) as estypes.SlmPutLifecycleRequest['body'], }); return res.ok({ body: response.body }); @@ -133,7 +133,7 @@ export function registerPolicyRoutes({ const response = await clusterClient.asCurrentUser.slm.putLifecycle({ policy_id: name, // TODO: bring {@link SlmPolicyEs['policy']} in line with {@link PutSnapshotLifecycleRequest['body']} - body: (serializePolicy(policy) as unknown) as PutSnapshotLifecycleRequest['body'], + body: (serializePolicy(policy) as unknown) as estypes.SlmPutLifecycleRequest['body'], }); return res.ok({ body: response.body }); @@ -205,6 +205,7 @@ export function registerPolicyRoutes({ name: '*', expand_wildcards: 'all', }); + // @ts-expect-error Type 'ResolveIndexAliasItem[]' is not comparable to type 'IndexAndAliasFromEs[]'. const resolvedIndicesResponse = response.body as ResolveIndexResponseFromES; const body: PolicyIndicesResponse = { diff --git a/x-pack/plugins/snapshot_restore/server/routes/api/repositories.ts b/x-pack/plugins/snapshot_restore/server/routes/api/repositories.ts index 96099e3fbb1eb5..4254562a0a8862 100644 --- a/x-pack/plugins/snapshot_restore/server/routes/api/repositories.ts +++ b/x-pack/plugins/snapshot_restore/server/routes/api/repositories.ts @@ -116,7 +116,6 @@ export function registerRepositoriesRoutes({ snapshot: '_all', }); - // @ts-expect-error @elastic/elasticsearch remove this "as unknown" workaround when the types for this endpoint are correct. Track progress at https://github.com/elastic/elastic-client-generator/issues/250. const { responses: snapshotResponses } = response.body; if (repositoryByName[name]) { diff --git a/x-pack/plugins/snapshot_restore/server/routes/api/restore.ts b/x-pack/plugins/snapshot_restore/server/routes/api/restore.ts index b7281fee04c538..eb77c5e2d833f8 100644 --- a/x-pack/plugins/snapshot_restore/server/routes/api/restore.ts +++ b/x-pack/plugins/snapshot_restore/server/routes/api/restore.ts @@ -6,7 +6,7 @@ */ import { schema, TypeOf } from '@kbn/config-schema'; -import { RestoreRequest } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { SnapshotRestore, SnapshotRestoreShardEs } from '../../../common/types'; import { serializeRestoreSettings } from '../../../common/lib'; @@ -108,7 +108,7 @@ export function registerRestoreRoutes({ repository, snapshot, // TODO: Bring {@link RestoreSettingsEs} in line with {@link RestoreRequest['body']} - body: serializeRestoreSettings(restoreSettings) as RestoreRequest['body'], + body: serializeRestoreSettings(restoreSettings) as estypes.SnapshotRestoreRequest['body'], }); return res.ok({ body: response.body }); diff --git a/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.ts b/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.ts index 8f6f44f63a556b..8ce33cb8cd05b8 100644 --- a/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.ts +++ b/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.ts @@ -73,7 +73,6 @@ export function registerSnapshotsRoutes({ ignore_unavailable: true, // Allow request to succeed even if some snapshots are unavailable. }); - // @ts-expect-error @elastic/elasticsearch remove this "as unknown" workaround when the types for this endpoint are correct. Track progress at https://github.com/elastic/elastic-client-generator/issues/250. const { responses: fetchedResponses } = response.body; // Decorate each snapshot with the repository with which it's associated. @@ -135,7 +134,6 @@ export function registerSnapshotsRoutes({ ignore_unavailable: true, }); - // @ts-expect-error @elastic/elasticsearch remove this "as unknown" workaround when the types for this endpoint are correct. Track progress at https://github.com/elastic/elastic-client-generator/issues/250. const { responses: snapshotsResponse } = response.body; const snapshotsList = @@ -144,7 +142,6 @@ export function registerSnapshotsRoutes({ return res.notFound({ body: 'Snapshot not found' }); } const selectedSnapshot = snapshotsList.find( - // @ts-expect-error @elastic/elasticsearch related to above incorrect type from client ({ snapshot: snapshotName }) => snapshot === snapshotName ) as SnapshotDetailsEs; @@ -154,9 +151,7 @@ export function registerSnapshotsRoutes({ } const successfulSnapshots = snapshotsList - // @ts-expect-error @elastic/elasticsearch related to above incorrect type from client .filter(({ state }) => state === 'SUCCESS') - // @ts-expect-error @elastic/elasticsearch related to above incorrect type from client .sort((a, b) => { return +new Date(b.end_time!) - +new Date(a.end_time!); }) as SnapshotDetailsEs[]; diff --git a/x-pack/plugins/spaces/server/saved_objects/mappings.ts b/x-pack/plugins/spaces/server/saved_objects/mappings.ts index 2b1763f1de5839..82a134bfdbf626 100644 --- a/x-pack/plugins/spaces/server/saved_objects/mappings.ts +++ b/x-pack/plugins/spaces/server/saved_objects/mappings.ts @@ -38,7 +38,7 @@ export const SpacesSavedObjectMappings = deepFreeze({ type: 'boolean', }, }, -}); +} as const); export const UsageStatsMappings = deepFreeze({ dynamic: false as false, // we aren't querying or aggregating over this data, so we don't need to specify any fields diff --git a/x-pack/plugins/stack_alerts/common/build_sorted_events_query.ts b/x-pack/plugins/stack_alerts/common/build_sorted_events_query.ts index 34851073bd8a2f..455307cb73a097 100644 --- a/x-pack/plugins/stack_alerts/common/build_sorted_events_query.ts +++ b/x-pack/plugins/stack_alerts/common/build_sorted_events_query.ts @@ -8,7 +8,7 @@ import { estypes } from '@elastic/elasticsearch'; import type { ESSearchRequest } from '../../../../typings/elasticsearch'; interface BuildSortedEventsQueryOpts { - aggs?: Record; + aggs?: Record; track_total_hits: boolean | number; index: estypes.Indices; size: number; diff --git a/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.tsx b/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.tsx index f89f1133d0248b..5111f427cd0d81 100644 --- a/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.tsx +++ b/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.tsx @@ -41,7 +41,7 @@ import { buildSortedEventsQuery } from '../../../common/build_sorted_events_quer import { EsQueryAlertParams } from './types'; import { IndexSelectPopover } from '../components/index_select_popover'; -function totalHitsToNumber(total: estypes.HitsMetadata['total']): number { +function totalHitsToNumber(total: estypes.SearchHitsMetadata['total']): number { return typeof total === 'number' ? total : total.value; } diff --git a/x-pack/plugins/stack_alerts/server/alert_types/es_query/action_context.ts b/x-pack/plugins/stack_alerts/server/alert_types/es_query/action_context.ts index bc5d5c41c5cce8..84a4569d9b8606 100644 --- a/x-pack/plugins/stack_alerts/server/alert_types/es_query/action_context.ts +++ b/x-pack/plugins/stack_alerts/server/alert_types/es_query/action_context.ts @@ -29,7 +29,7 @@ export interface EsQueryAlertActionContext extends AlertInstanceContext { // threshold conditions conditions: string; // query matches - hits: estypes.Hit[]; + hits: estypes.SearchHit[]; } export function addMessages( diff --git a/x-pack/plugins/stack_alerts/server/alert_types/es_query/alert_type.ts b/x-pack/plugins/stack_alerts/server/alert_types/es_query/alert_type.ts index ece193e07d776a..b81bc19d5c731e 100644 --- a/x-pack/plugins/stack_alerts/server/alert_types/es_query/alert_type.ts +++ b/x-pack/plugins/stack_alerts/server/alert_types/es_query/alert_type.ts @@ -220,7 +220,7 @@ export function getAlertType( `alert ${ES_QUERY_ID}:${alertId} "${name}" result - ${JSON.stringify(searchResult)}` ); - const numMatches = (searchResult.hits.total as estypes.TotalHits).value; + const numMatches = (searchResult.hits.total as estypes.SearchTotalHits).value; // apply the alert condition const conditionMet = compareFn(numMatches, params.threshold); diff --git a/x-pack/plugins/task_manager/server/monitoring/workload_statistics.test.ts b/x-pack/plugins/task_manager/server/monitoring/workload_statistics.test.ts index a4913fca19ee84..f3ee21bc7d7704 100644 --- a/x-pack/plugins/task_manager/server/monitoring/workload_statistics.test.ts +++ b/x-pack/plugins/task_manager/server/monitoring/workload_statistics.test.ts @@ -61,7 +61,7 @@ describe('Workload Statistics Aggregator', () => { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, }, - // The `FiltersAggregate` doesn't cover the case of a nested `AggregationContainer`, in which `FiltersAggregate` + // The `FiltersAggregate` doesn't cover the case of a nested `AggregationsAggregationContainer`, in which `FiltersAggregate` // would not have a `buckets` property, but rather a keyed property that's inferred from the request. // @ts-expect-error idleTasks: { @@ -238,7 +238,7 @@ describe('Workload Statistics Aggregator', () => { }, ], }, - // The `FiltersAggregate` doesn't cover the case of a nested `AggregationContainer`, in which `FiltersAggregate` + // The `FiltersAggregate` doesn't cover the case of a nested `AggregationsAggregationContainer`, in which `FiltersAggregate` // would not have a `buckets` property, but rather a keyed property that's inferred from the request. // @ts-expect-error idleTasks: { @@ -944,7 +944,7 @@ function setTaskTypeCount( ...rest.hits, total: { value: buckets.reduce((sum, bucket) => sum + bucket.doc_count, 0), - relation: 'eq' as estypes.TotalHitsRelation, + relation: 'eq' as estypes.SearchTotalHitsRelation, }, }, aggregations: { diff --git a/x-pack/plugins/task_manager/server/monitoring/workload_statistics.ts b/x-pack/plugins/task_manager/server/monitoring/workload_statistics.ts index 548539b0db3295..e251ce07679ffb 100644 --- a/x-pack/plugins/task_manager/server/monitoring/workload_statistics.ts +++ b/x-pack/plugins/task_manager/server/monitoring/workload_statistics.ts @@ -86,7 +86,6 @@ export interface WorkloadAggregation { // The type of a bucket in the scheduleDensity range aggregation type ScheduleDensityResult = AggregationResultOf< - // @ts-expect-error AggregationRange reqires from: number WorkloadAggregation['aggs']['idleTasks']['aggs']['scheduleDensity'], {} >['buckets'][0]; @@ -137,9 +136,7 @@ export function createWorkloadAggregator( field: 'task.runAt', ranges: [ { - // @ts-expect-error @elastic/elasticsearch The `AggregationRange` type only supports `double` for `from` and `to` but it can be a string too for time based ranges from: `now`, - // @ts-expect-error @elastic/elasticsearch The `AggregationRange` type only supports `double` for `from` and `to` but it can be a string too for time based ranges to: `now+${asInterval(scheduleDensityBuckets * pollInterval)}`, }, ], @@ -355,7 +352,7 @@ export function summarizeWorkloadStat( } function hasAggregations( - aggregations?: Record + aggregations?: Record ): aggregations is WorkloadAggregationResponse { return !!( aggregations?.taskType && @@ -368,9 +365,9 @@ export interface WorkloadAggregationResponse { taskType: TaskTypeAggregation; schedule: ScheduleAggregation; idleTasks: IdleTasksAggregation; - [otherAggs: string]: estypes.Aggregate; + [otherAggs: string]: estypes.AggregationsAggregate; } -export interface TaskTypeAggregation extends estypes.FiltersAggregate { +export interface TaskTypeAggregation extends estypes.AggregationsFiltersAggregate { buckets: Array<{ doc_count: number; key: string | number; @@ -386,7 +383,7 @@ export interface TaskTypeAggregation extends estypes.FiltersAggregate { doc_count_error_upper_bound?: number | undefined; sum_other_doc_count?: number | undefined; } -export interface ScheduleAggregation extends estypes.FiltersAggregate { +export interface ScheduleAggregation extends estypes.AggregationsFiltersAggregate { buckets: Array<{ doc_count: number; key: string | number; @@ -411,7 +408,7 @@ export type ScheduleDensityHistogram = DateRangeBucket & { >; }; }; -export interface IdleTasksAggregation extends estypes.FiltersAggregate { +export interface IdleTasksAggregation extends estypes.AggregationsFiltersAggregate { doc_count: number; scheduleDensity: { buckets: ScheduleDensityHistogram[]; diff --git a/x-pack/plugins/task_manager/server/queries/mark_available_tasks_as_claimed.ts b/x-pack/plugins/task_manager/server/queries/mark_available_tasks_as_claimed.ts index 2437e893abf373..1793ede8161df9 100644 --- a/x-pack/plugins/task_manager/server/queries/mark_available_tasks_as_claimed.ts +++ b/x-pack/plugins/task_manager/server/queries/mark_available_tasks_as_claimed.ts @@ -30,7 +30,7 @@ export function taskWithLessThanMaxAttempts(type: string, maxAttempts: number): }; } -export function tasksOfType(taskTypes: string[]): estypes.QueryContainer { +export function tasksOfType(taskTypes: string[]): estypes.QueryDslQueryContainer { return { bool: { should: [...taskTypes].map((type) => ({ term: { 'task.taskType': type } })), @@ -40,7 +40,7 @@ export function tasksOfType(taskTypes: string[]): estypes.QueryContainer { export function tasksClaimedByOwner( taskManagerId: string, - ...taskFilters: estypes.QueryContainer[] + ...taskFilters: estypes.QueryDslQueryContainer[] ) { return mustBeAllOf( { @@ -104,7 +104,7 @@ if (doc['task.runAt'].size()!=0) { }; export const SortByRunAtAndRetryAt = (SortByRunAtAndRetryAtScript as unknown) as Record< string, - estypes.Sort + estypes.SearchSort >; export const updateFieldsAndMarkAsFailed = ( diff --git a/x-pack/plugins/task_manager/server/queries/query_clauses.ts b/x-pack/plugins/task_manager/server/queries/query_clauses.ts index 97c41295eece32..5f7cc8ed2bdb34 100644 --- a/x-pack/plugins/task_manager/server/queries/query_clauses.ts +++ b/x-pack/plugins/task_manager/server/queries/query_clauses.ts @@ -8,10 +8,10 @@ import { estypes } from '@elastic/elasticsearch'; export interface MustCondition { - bool: Pick; + bool: Pick; } export interface MustNotCondition { - bool: Pick; + bool: Pick; } export interface ScriptBasedSortClause { @@ -24,7 +24,7 @@ export interface ScriptBasedSortClause { export interface ScriptClause { source: string; - lang: string; + lang: estypes.ScriptLanguage; params?: { [field: string]: | string @@ -35,16 +35,16 @@ export interface ScriptClause { }; } -export type PinnedQuery = Pick; +export type PinnedQuery = Pick; -type BoolClause = Pick; +type BoolClause = Pick; export function matchesClauses(...clauses: BoolClause[]): BoolClause { return { bool: Object.assign({}, ...clauses.map((clause) => clause.bool)), }; } -export function shouldBeOneOf(...should: estypes.QueryContainer[]) { +export function shouldBeOneOf(...should: estypes.QueryDslQueryContainer[]) { return { bool: { should, @@ -52,7 +52,7 @@ export function shouldBeOneOf(...should: estypes.QueryContainer[]) { }; } -export function mustBeAllOf(...must: estypes.QueryContainer[]) { +export function mustBeAllOf(...must: estypes.QueryDslQueryContainer[]) { return { bool: { must, @@ -60,7 +60,7 @@ export function mustBeAllOf(...must: estypes.QueryContainer[]) { }; } -export function filterDownBy(...filter: estypes.QueryContainer[]) { +export function filterDownBy(...filter: estypes.QueryDslQueryContainer[]) { return { bool: { filter, @@ -69,9 +69,9 @@ export function filterDownBy(...filter: estypes.QueryContainer[]) { } export function asPinnedQuery( - ids: estypes.PinnedQuery['ids'], - organic: estypes.PinnedQuery['organic'] -): Pick { + ids: estypes.QueryDslPinnedQuery['ids'], + organic: estypes.QueryDslPinnedQuery['organic'] +): Pick { return { pinned: { ids, diff --git a/x-pack/plugins/task_manager/server/saved_objects/index.ts b/x-pack/plugins/task_manager/server/saved_objects/index.ts index 33b57b62b31aa2..c032e8d658a400 100644 --- a/x-pack/plugins/task_manager/server/saved_objects/index.ts +++ b/x-pack/plugins/task_manager/server/saved_objects/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { SavedObjectsServiceSetup } from 'kibana/server'; +import type { SavedObjectsServiceSetup, SavedObjectsTypeMappingDefinition } from 'kibana/server'; import mappings from './mappings.json'; import { migrations } from './migrations'; import { TaskManagerConfig } from '../config.js'; @@ -19,7 +19,7 @@ export function setupSavedObjects( namespaceType: 'agnostic', hidden: true, convertToAliasScript: `ctx._id = ctx._source.type + ':' + ctx._id; ctx._source.remove("kibana")`, - mappings: mappings.task, + mappings: mappings.task as SavedObjectsTypeMappingDefinition, migrations, indexPattern: config.index, }); diff --git a/x-pack/plugins/task_manager/server/task_store.test.ts b/x-pack/plugins/task_manager/server/task_store.test.ts index 2d2bd81af96e5c..f3b4014c9c9199 100644 --- a/x-pack/plugins/task_manager/server/task_store.test.ts +++ b/x-pack/plugins/task_manager/server/task_store.test.ts @@ -208,7 +208,7 @@ describe('TaskStore', () => { }); }); - async function testFetch(opts?: SearchOpts, hits: Array> = []) { + async function testFetch(opts?: SearchOpts, hits: Array> = []) { esClient.search.mockResolvedValue(asApiResponse({ hits: { hits, total: hits.length } })); const result = await store.fetch(opts); diff --git a/x-pack/plugins/task_manager/server/task_store.ts b/x-pack/plugins/task_manager/server/task_store.ts index 0eeccd0af75f77..ce01660134683e 100644 --- a/x-pack/plugins/task_manager/server/task_store.ts +++ b/x-pack/plugins/task_manager/server/task_store.ts @@ -46,14 +46,14 @@ export interface StoreOpts { export interface SearchOpts { search_after?: Array; size?: number; - sort?: estypes.Sort; - query?: estypes.QueryContainer; + sort?: estypes.SearchSort; + query?: estypes.QueryDslQueryContainer; seq_no_primary_term?: boolean; } export interface AggregationOpts { - aggs: Record; - query?: estypes.QueryContainer; + aggs: Record; + query?: estypes.QueryDslQueryContainer; size?: number; } diff --git a/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_license.ts b/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_license.ts index 3db9f06bd8bf6a..ad7d5439f87659 100644 --- a/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_license.ts +++ b/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_license.ts @@ -7,7 +7,7 @@ import type { estypes } from '@elastic/elasticsearch'; import { ElasticsearchClient } from 'src/core/server'; -export type ESLicense = estypes.LicenseInformation; +export type ESLicense = estypes.LicenseGetLicenseInformation; let cachedLicense: ESLicense | undefined; diff --git a/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.test.ts b/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.test.ts index 86d1554a4fd579..75b9c736de9016 100644 --- a/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.test.ts +++ b/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.test.ts @@ -91,7 +91,7 @@ function mockEsClient() { cluster_uuid: 'test', cluster_name: 'test', version: { number: '8.0.0' } as estypes.ElasticsearchVersionInfo, - } as estypes.RootNodeInfoResponse, + } as estypes.InfoResponse, } ); diff --git a/x-pack/plugins/transform/common/api_schemas/type_guards.ts b/x-pack/plugins/transform/common/api_schemas/type_guards.ts index 4b66de9be20d28..1f27f1798c8e72 100644 --- a/x-pack/plugins/transform/common/api_schemas/type_guards.ts +++ b/x-pack/plugins/transform/common/api_schemas/type_guards.ts @@ -74,7 +74,7 @@ export const isEsSearchResponseWithAggregations = ( export const isMultiBucketAggregate = ( arg: unknown -): arg is estypes.MultiBucketAggregate => { +): arg is estypes.AggregationsMultiBucketAggregate => { return isPopulatedObject(arg, ['buckets']); }; diff --git a/x-pack/plugins/transform/public/app/hooks/use_index_data.ts b/x-pack/plugins/transform/public/app/hooks/use_index_data.ts index bd1ecd79f4d12d..55a304207a1c70 100644 --- a/x-pack/plugins/transform/public/app/hooks/use_index_data.ts +++ b/x-pack/plugins/transform/public/app/hooks/use_index_data.ts @@ -206,7 +206,7 @@ export const useIndexData = ( setRowCount(typeof resp.hits.total === 'number' ? resp.hits.total : resp.hits.total.value); setRowCountRelation( typeof resp.hits.total === 'number' - ? ('eq' as estypes.TotalHitsRelation) + ? ('eq' as estypes.SearchTotalHitsRelation) : resp.hits.total.relation ); setTableItems(docs); diff --git a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_term_form.tsx b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_term_form.tsx index 358bb9dcafa967..da7100a31167a5 100644 --- a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_term_form.tsx +++ b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_term_form.tsx @@ -69,7 +69,9 @@ export const FilterTermForm: FilterAggConfigTerm['aggTypeConfig']['FilterAggForm if ( !( isEsSearchResponseWithAggregations(response) && - isMultiBucketAggregate(response.aggregations.field_values) + isMultiBucketAggregate( + response.aggregations.field_values + ) ) ) { toastNotifications.addWarning( diff --git a/x-pack/plugins/transform/server/routes/api/field_histograms.ts b/x-pack/plugins/transform/server/routes/api/field_histograms.ts index bb2a1b278a5c20..bfe2f470785690 100644 --- a/x-pack/plugins/transform/server/routes/api/field_histograms.ts +++ b/x-pack/plugins/transform/server/routes/api/field_histograms.ts @@ -41,7 +41,6 @@ export function registerFieldHistogramsRoutes({ router, license }: RouteDependen query, fields, samplerShardSize, - // @ts-expect-error script is not compatible with StoredScript from @elastic/elasticsearch: string is not supported runtimeMappings ); diff --git a/x-pack/plugins/transform/server/routes/api/transforms.ts b/x-pack/plugins/transform/server/routes/api/transforms.ts index 80f80d6f1d71bc..ea2bb28776ac2a 100644 --- a/x-pack/plugins/transform/server/routes/api/transforms.ts +++ b/x-pack/plugins/transform/server/routes/api/transforms.ts @@ -6,6 +6,7 @@ */ import { schema } from '@kbn/config-schema'; +import type { estypes } from '@elastic/elasticsearch'; import { ElasticsearchClient, @@ -252,7 +253,7 @@ export function registerTransformsRoutes(routeDependencies: RouteDependencies) { const { body, } = await ctx.core.elasticsearch.client.asCurrentUser.transform.updateTransform({ - // @ts-expect-error query doesn't satisfy QueryContainer from @elastic/elasticsearch + // @ts-expect-error query doesn't satisfy QueryDslQueryContainer from @elastic/elasticsearch body: req.body, transform_id: transformId, }); @@ -570,7 +571,10 @@ const previewTransformHandler: RequestHandler< return acc; }, {} as Record); - body.generated_dest_index.mappings.properties = fields; + body.generated_dest_index.mappings!.properties = fields as Record< + string, + estypes.MappingProperty + >; } return res.ok({ body }); } catch (e) { diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index e8d47d4dfc17ee..c571e2da6f76f5 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -7902,7 +7902,6 @@ "xpack.enterpriseSearch.appSearch.result.documentDetailLink": "ドキュメントの詳細を表示", "xpack.enterpriseSearch.appSearch.result.hideAdditionalFields": "追加フィールドを非表示", "xpack.enterpriseSearch.appSearch.result.title": "ドキュメント{id}", - "xpack.enterpriseSearch.appSearch.roleMapping.emptyRoleMappingsBody": "認証が成功したすべてのユーザーには所有者ロールが割り当てられ、すべてのエンジンにアクセスできます。デフォルト設定を無効にするには、新しいロールを追加します。", "xpack.enterpriseSearch.appSearch.roleMappingCreatedMessage": "ロールマッピングが正常に作成されました。", "xpack.enterpriseSearch.appSearch.roleMappingDeletedMessage": "ロールマッピングが正常に削除されました", "xpack.enterpriseSearch.appSearch.roleMappingsEngineAccessHeading": "エンジンアクセス", @@ -7992,7 +7991,6 @@ "xpack.enterpriseSearch.roleMapping.deleteRoleMappingButton": "マッピングを削除", "xpack.enterpriseSearch.roleMapping.deleteRoleMappingDescription": "マッピングの削除は永久的であり、元に戻すことはできません", "xpack.enterpriseSearch.roleMapping.deleteRoleMappingTitle": "このロールマッピングを削除", - "xpack.enterpriseSearch.roleMapping.emptyRoleMappingsTitle": "ロールマッピングがありません", "xpack.enterpriseSearch.roleMapping.externalAttributeLabel": "外部属性", "xpack.enterpriseSearch.roleMapping.filterRoleMappingsPlaceholder": "ロールをフィルタリング...", "xpack.enterpriseSearch.roleMapping.individualAuthProviderLabel": "個別の認証プロバイダーを選択", @@ -8000,7 +7998,6 @@ "xpack.enterpriseSearch.roleMapping.moResults.message": "'{filterValue}'の結果が見つかりません。", "xpack.enterpriseSearch.roleMapping.newRoleMappingTitle": "ロールマッピングを追加", "xpack.enterpriseSearch.roleMapping.roleLabel": "ロール", - "xpack.enterpriseSearch.roleMapping.roleMappingsDescription": "elasticsearch-nativeおよびelasticsearch-saml認証のロールマッピングを定義します。", "xpack.enterpriseSearch.roleMapping.roleMappingsTitle": "ユーザーとロール", "xpack.enterpriseSearch.roleMapping.saveRoleMappingButtonLabel": "ロールマッピングの保存", "xpack.enterpriseSearch.roleMapping.updateRoleMappingButtonLabel": "ロールマッピングを更新", @@ -8308,7 +8305,6 @@ "xpack.enterpriseSearch.workplaceSearch.roleMapping.adminRoleTypeDescription": "管理者は、コンテンツソース、グループ、ユーザー管理機能など、すべての組織レベルの設定に無制限にアクセスできます。", "xpack.enterpriseSearch.workplaceSearch.roleMapping.defaultGroupName": "デフォルト", "xpack.enterpriseSearch.workplaceSearch.roleMapping.deleteRoleMappingButtonMessage": "このマッピングを完全に削除しますか?このアクションは元に戻せません。一部のユーザーがアクセスを失う可能性があります。", - "xpack.enterpriseSearch.workplaceSearch.roleMapping.emptyRoleMappingsBody": "新しいチームメンバーにはデフォルトで管理者ロールが割り当てられます。管理者はすべてにアクセスできます。デフォルト設定を無効にするには、新しいロールを作成します。", "xpack.enterpriseSearch.workplaceSearch.roleMapping.groupAssignmentInvalidError": "1つ以上の割り当てられたグループが必要です。", "xpack.enterpriseSearch.workplaceSearch.roleMapping.roleMappingsTableHeader": "グループアクセス", "xpack.enterpriseSearch.workplaceSearch.roleMapping.userRoleTypeDescription": "ユーザーの機能アクセスは検索インターフェースと個人設定管理に制限されます。", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index db211f5a0f7867..bb0b740609594b 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -7970,7 +7970,6 @@ "xpack.enterpriseSearch.appSearch.result.hideAdditionalFields": "隐藏其他字段", "xpack.enterpriseSearch.appSearch.result.showAdditionalFields": "显示其他 {numberOfAdditionalFields, number} 个{numberOfAdditionalFields, plural, other {字段}}", "xpack.enterpriseSearch.appSearch.result.title": "文档 {id}", - "xpack.enterpriseSearch.appSearch.roleMapping.emptyRoleMappingsBody": "成功验证的所有用户将被分配所有者角色,可访问所有引擎。添加新角色以覆盖默认值。", "xpack.enterpriseSearch.appSearch.roleMappingCreatedMessage": "角色映射已成功创建。", "xpack.enterpriseSearch.appSearch.roleMappingDeletedMessage": "已成功删除角色映射", "xpack.enterpriseSearch.appSearch.roleMappingsEngineAccessHeading": "引擎访问", @@ -8060,7 +8059,6 @@ "xpack.enterpriseSearch.roleMapping.deleteRoleMappingButton": "删除映射", "xpack.enterpriseSearch.roleMapping.deleteRoleMappingDescription": "请注意,删除映射是永久性的,无法撤消", "xpack.enterpriseSearch.roleMapping.deleteRoleMappingTitle": "移除此角色映射", - "xpack.enterpriseSearch.roleMapping.emptyRoleMappingsTitle": "尚未有角色映射", "xpack.enterpriseSearch.roleMapping.externalAttributeLabel": "外部属性", "xpack.enterpriseSearch.roleMapping.filterRoleMappingsPlaceholder": "筛选角色......", "xpack.enterpriseSearch.roleMapping.individualAuthProviderLabel": "选择单个身份验证提供程序", @@ -8068,7 +8066,6 @@ "xpack.enterpriseSearch.roleMapping.moResults.message": "找不到“{filterValue}”的结果", "xpack.enterpriseSearch.roleMapping.newRoleMappingTitle": "添加角色映射", "xpack.enterpriseSearch.roleMapping.roleLabel": "角色", - "xpack.enterpriseSearch.roleMapping.roleMappingsDescription": "为 elasticsearch-native 和 elasticsearch-saml 身份验证定义角色映射。", "xpack.enterpriseSearch.roleMapping.roleMappingsTitle": "用户和角色", "xpack.enterpriseSearch.roleMapping.saveRoleMappingButtonLabel": "保存角色映射", "xpack.enterpriseSearch.roleMapping.updateRoleMappingButtonLabel": "更新角色映射", @@ -8376,7 +8373,6 @@ "xpack.enterpriseSearch.workplaceSearch.roleMapping.adminRoleTypeDescription": "管理员对所有组织范围设置 (包括内容源、组和用户管理功能) 具有完全权限。", "xpack.enterpriseSearch.workplaceSearch.roleMapping.defaultGroupName": "默认", "xpack.enterpriseSearch.workplaceSearch.roleMapping.deleteRoleMappingButtonMessage": "确定要永久删除此映射?此操作不可逆转,且某些用户可能会失去访问权限。", - "xpack.enterpriseSearch.workplaceSearch.roleMapping.emptyRoleMappingsBody": "默认情况下,会为新团队成员分配管理员角色。管理员可以访问任何内容。超级新角色以覆盖默认值。", "xpack.enterpriseSearch.workplaceSearch.roleMapping.groupAssignmentInvalidError": "至少需要一个分配的组。", "xpack.enterpriseSearch.workplaceSearch.roleMapping.roleMappingsTableHeader": "组访问权限", "xpack.enterpriseSearch.workplaceSearch.roleMapping.userRoleTypeDescription": "用户的功能访问权限仅限于搜索界面和个人设置管理。", diff --git a/x-pack/plugins/upgrade_assistant/server/lib/es_migration_apis.test.ts b/x-pack/plugins/upgrade_assistant/server/lib/es_migration_apis.test.ts index 2620fe31d62777..d78af9162e9242 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/es_migration_apis.test.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/es_migration_apis.test.ts @@ -35,6 +35,7 @@ describe('getUpgradeAssistantStatus', () => { asApiResponse(deprecationsResponse) ); + // @ts-expect-error not full interface of response esClient.asCurrentUser.indices.resolveIndex.mockResolvedValue(asApiResponse(resolvedIndices)); it('calls /_migration/deprecations', async () => { diff --git a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.test.ts b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.test.ts index 5e994f76f927c9..30093a9fb6e508 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.test.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.test.ts @@ -40,6 +40,7 @@ describe('transformFlatSettings', () => { 'index.number_of_shards': '5', // Blacklisted settings + // @ts-expect-error @elastic/elasticsearch doesn't declare it 'index.allocation.existing_shards_allocator': 'gateway_allocator', 'index.blocks.write': 'true', 'index.creation_date': '1547052614626', @@ -89,6 +90,7 @@ describe('transformFlatSettings', () => { 'index.number_of_shards': '5', // Deprecated settings + // @ts-expect-error @elastic/elasticsearch doesn't declare it 'index.soft_deletes.enabled': 'true', 'index.translog.retention.size': '5b', }, @@ -112,6 +114,7 @@ describe('transformFlatSettings', () => { 'index.number_of_shards': '5', // Deprecated settings + // @ts-expect-error @elastic/elasticsearch doesn't declare it 'index.soft_deletes.enabled': 'true', 'index.translog.retention.age': '5d', }, @@ -216,6 +219,7 @@ describe('transformFlatSettings', () => { getReindexWarnings({ settings: { // Deprecated settings + // @ts-expect-error @elastic/elasticsearch doesn't declare it 'index.force_memory_term_dictionary': '1024', 'index.max_adjacency_matrix_filters': 'true', 'index.soft_deletes.enabled': 'true', diff --git a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.ts b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.ts index 5ee067f3640f32..0fb531b286854d 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.ts @@ -104,11 +104,14 @@ export const getDeprecatedSettingWarning = ( }); // Translog settings are only marked as deprecated if soft deletes is enabled + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting if (settings['index.soft_deletes.enabled'] === 'true') { + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting if (settings['index.translog.retention.size']) { deprecatedSettingsInUse.push('index.translog.retention.size'); } + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting if (settings['index.translog.retention.age']) { deprecatedSettingsInUse.push('index.translog.retention.age'); } @@ -183,12 +186,17 @@ const removeDeprecatedSettings = (settings: FlatSettings['settings']) => { const updatedSettings = { ...settings }; // Translog settings are only marked as deprecated if soft deletes is enabled + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting if (updatedSettings['index.soft_deletes.enabled'] === 'true') { + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting if (updatedSettings['index.translog.retention.size']) { + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting delete updatedSettings['index.translog.retention.size']; } + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting if (settings['index.translog.retention.age']) { + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting delete updatedSettings['index.translog.retention.age']; } } diff --git a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts index ae0a6f97e29d55..7a5bf1c1876980 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts @@ -793,7 +793,7 @@ describe('reindexService', () => { expect(updatedOp.attributes.lastCompletedStep).toEqual(ReindexStep.readonly); expect(clusterClient.asCurrentUser.indices.putSettings).toHaveBeenCalledWith({ index: 'myIndex', - body: { index: { blocks: { write: true } } }, + body: { settings: { blocks: { write: true } } }, }); }); @@ -885,7 +885,7 @@ describe('reindexService', () => { // Original index should have been set back to allow reads. expect(clusterClient.asCurrentUser.indices.putSettings).toHaveBeenCalledWith({ index: 'myIndex', - body: { index: { blocks: { write: false } } }, + body: { settings: { blocks: { write: false } } }, }); }); }); diff --git a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.ts b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.ts index b9d5b42a65250f..1bf45e3a4a038b 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.ts @@ -226,7 +226,7 @@ export const reindexServiceFactory = ( if (reindexOp.attributes.lastCompletedStep >= ReindexStep.readonly) { await esClient.indices.putSettings({ index: reindexOp.attributes.indexName, - body: { index: { blocks: { write: false } } }, + body: { settings: { blocks: { write: false } } }, }); } @@ -290,7 +290,7 @@ export const reindexServiceFactory = ( const { indexName } = reindexOp.attributes; const { body: putReadonly } = await esClient.indices.putSettings({ index: indexName, - body: { index: { blocks: { write: true } } }, + body: { settings: { blocks: { write: true } } }, }); if (!putReadonly.acknowledged) { diff --git a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/types.ts b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/types.ts index 569316e276e430..ddff137772ae8a 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/types.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/types.ts @@ -4,6 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ +import type { estypes } from '@elastic/elasticsearch'; interface Mapping { type?: string; @@ -19,10 +20,8 @@ interface MetaProperties { } export interface FlatSettings { - settings: { - [key: string]: string; - }; - mappings: { + settings: estypes.IndicesIndexState['settings']; + mappings?: { properties?: MappingProperties; _meta?: MetaProperties; }; @@ -30,10 +29,8 @@ export interface FlatSettings { // Specific to 7.x-8 upgrade export interface FlatSettingsWithTypeName { - settings: { - [key: string]: string; - }; - mappings: { + settings: estypes.IndicesIndexState['settings']; + mappings?: { [typeName: string]: { properties?: MappingProperties; _meta?: MetaProperties; diff --git a/x-pack/plugins/upgrade_assistant/server/routes/update_index_settings.ts b/x-pack/plugins/upgrade_assistant/server/routes/update_index_settings.ts index 4bdf3c7f56cacb..b90ff4281644bf 100644 --- a/x-pack/plugins/upgrade_assistant/server/routes/update_index_settings.ts +++ b/x-pack/plugins/upgrade_assistant/server/routes/update_index_settings.ts @@ -45,7 +45,7 @@ export function registerUpdateSettingsRoute({ router }: RouteDependencies) { const { body: settingsResponse } = await client.asCurrentUser.indices.putSettings({ index: indexName, body: { - index: settingsToDelete, + settings: settingsToDelete, }, }); diff --git a/x-pack/plugins/uptime/server/lib/requests/get_journey_details.ts b/x-pack/plugins/uptime/server/lib/requests/get_journey_details.ts index 560653950c6f88..6081cc3a7b7c8c 100644 --- a/x-pack/plugins/uptime/server/lib/requests/get_journey_details.ts +++ b/x-pack/plugins/uptime/server/lib/requests/get_journey_details.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { UMElasticsearchQueryFn } from '../adapters/framework'; import { SyntheticsJourneyApiResponse } from '../../../common/runtime_types'; @@ -31,7 +31,7 @@ export const getJourneyDetails: UMElasticsearchQueryFn< 'synthetics.type': 'journey/start', }, }, - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }, size: 1, @@ -56,7 +56,7 @@ export const getJourneyDetails: UMElasticsearchQueryFn< 'synthetics.type': 'journey/start', }, }, - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }, _source: ['@timestamp', 'monitor.check_group'], diff --git a/x-pack/plugins/uptime/server/lib/requests/get_journey_failed_steps.ts b/x-pack/plugins/uptime/server/lib/requests/get_journey_failed_steps.ts index 5c4e263468947b..d14a723d27628d 100644 --- a/x-pack/plugins/uptime/server/lib/requests/get_journey_failed_steps.ts +++ b/x-pack/plugins/uptime/server/lib/requests/get_journey_failed_steps.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { SearchHit } from '../../../../../../typings/elasticsearch'; import { asMutableArray } from '../../../common/utils/as_mutable_array'; import { UMElasticsearchQueryFn } from '../adapters/framework'; @@ -38,7 +38,7 @@ export const getJourneyFailedSteps: UMElasticsearchQueryFn = a { range: { '@timestamp': { gte: from, lte: to } } }, ...(monitorId ? [{ term: { 'monitor.id': monitorId } }] : []), ...(status ? [{ term: { 'monitor.status': status } }] : []), - ] as QueryContainer[], + ] as QueryDslQueryContainer[], ...REMOVE_NON_SUMMARY_BROWSER_CHECKS, }, }, diff --git a/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts b/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts index f686d978ec710e..621fdf0d15861f 100644 --- a/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts +++ b/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts @@ -5,16 +5,16 @@ * 2.0. */ -import { ScrollResponse, Hit } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { IScopedClusterClient } from 'kibana/server'; import { get } from 'lodash'; import { ES_SCROLL_SETTINGS } from '../../../common/constants'; export function fetchAllFromScroll( - searchResults: ScrollResponse, + searchResults: estypes.ScrollResponse, dataClient: IScopedClusterClient, - hits: Hit[] = [] -): Promise { + hits: estypes.SearchHit[] = [] +): Promise { const newHits = get(searchResults, 'hits.hits', []); const scrollId = get(searchResults, '_scroll_id'); @@ -25,7 +25,7 @@ export function fetchAllFromScroll( .scroll({ body: { scroll: ES_SCROLL_SETTINGS.KEEPALIVE, - scroll_id: scrollId, + scroll_id: scrollId!, }, }) .then(({ body: innerResponse }) => { diff --git a/x-pack/plugins/watcher/server/routes/api/indices/register_get_route.ts b/x-pack/plugins/watcher/server/routes/api/indices/register_get_route.ts index 915871185af857..f69ee60f9cd735 100644 --- a/x-pack/plugins/watcher/server/routes/api/indices/register_get_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/indices/register_get_route.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { MultiBucketAggregate } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema } from '@kbn/config-schema'; import { IScopedClusterClient } from 'kibana/server'; import { reduce, size } from 'lodash'; @@ -64,7 +64,9 @@ async function getIndices(dataClient: IScopedClusterClient, pattern: string, lim if (response.statusCode === 404 || !response.body.aggregations) { return []; } - const indices = response.body.aggregations.indices as MultiBucketAggregate<{ key: unknown }>; + const indices = response.body.aggregations.indices as estypes.AggregationsMultiBucketAggregate<{ + key: unknown; + }>; return indices.buckets ? indices.buckets.map((bucket) => bucket.key) : []; } diff --git a/x-pack/plugins/watcher/server/routes/api/watches/register_delete_route.ts b/x-pack/plugins/watcher/server/routes/api/watches/register_delete_route.ts index e47d451c227e5f..b7c09361774abc 100644 --- a/x-pack/plugins/watcher/server/routes/api/watches/register_delete_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/watches/register_delete_route.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { DeleteWatchResponse } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema } from '@kbn/config-schema'; import { IScopedClusterClient } from 'kibana/server'; import { RouteDependencies } from '../../../types'; @@ -14,7 +14,10 @@ const bodySchema = schema.object({ watchIds: schema.arrayOf(schema.string()), }); -type DeleteWatchPromiseArray = Promise<{ success?: DeleteWatchResponse; error?: any }>; +type DeleteWatchPromiseArray = Promise<{ + success?: estypes.WatcherDeleteWatchResponse; + error?: any; +}>; function deleteWatches(dataClient: IScopedClusterClient, watchIds: string[]) { const deletePromises = watchIds.map((watchId) => { diff --git a/x-pack/test/accessibility/apps/ml.ts b/x-pack/test/accessibility/apps/ml.ts index 41f8d5e56f8e6a..5436f74a2b8f9a 100644 --- a/x-pack/test/accessibility/apps/ml.ts +++ b/x-pack/test/accessibility/apps/ml.ts @@ -114,7 +114,6 @@ export default function ({ getService }: FtrProviderContext) { description: 'Test calendar', }); await ml.api.createCalendarEvents(calendarId, [ - // @ts-expect-error not full interface { description: eventDescription, start_time: '1513641600000', diff --git a/x-pack/test/api_integration/apis/lens/telemetry.ts b/x-pack/test/api_integration/apis/lens/telemetry.ts index 32b6a446a57b29..be1760d129df71 100644 --- a/x-pack/test/api_integration/apis/lens/telemetry.ts +++ b/x-pack/test/api_integration/apis/lens/telemetry.ts @@ -41,7 +41,6 @@ export default ({ getService }: FtrProviderContext) => { beforeEach(async () => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:lens-ui-telemetry', wait_for_completion: true, refresh: true, @@ -52,7 +51,6 @@ export default ({ getService }: FtrProviderContext) => { afterEach(async () => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:lens-ui-telemetry', wait_for_completion: true, refresh: true, diff --git a/x-pack/test/api_integration/apis/ml/calendars/create_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/create_calendars.ts index 01b87e6059a29d..fac62237aa74e5 100644 --- a/x-pack/test/api_integration/apis/ml/calendars/create_calendars.ts +++ b/x-pack/test/api_integration/apis/ml/calendars/create_calendars.ts @@ -52,11 +52,7 @@ export default ({ getService }: FtrProviderContext) => { expect(createdCalendar.description).to.eql(requestBody.description); expect(createdCalendar.job_ids).to.eql(requestBody.job_ids); - await ml.api.waitForEventsToExistInCalendar( - calendarId, - // @ts-expect-error not full interface - requestBody.events - ); + await ml.api.waitForEventsToExistInCalendar(calendarId, requestBody.events); }); it('should not create new calendar for user without required permission', async () => { diff --git a/x-pack/test/api_integration/apis/ml/calendars/delete_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/delete_calendars.ts index dfbffad9dafdd0..a2e1709731aa74 100644 --- a/x-pack/test/api_integration/apis/ml/calendars/delete_calendars.ts +++ b/x-pack/test/api_integration/apis/ml/calendars/delete_calendars.ts @@ -34,7 +34,6 @@ export default ({ getService }: FtrProviderContext) => { beforeEach(async () => { await ml.api.createCalendar(calendarId, testCalendar); - // @ts-expect-error not full interface await ml.api.createCalendarEvents(calendarId, testEvents); }); diff --git a/x-pack/test/api_integration/apis/ml/calendars/get_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/get_calendars.ts index 175c678317e6c1..243a40abe97a4a 100644 --- a/x-pack/test/api_integration/apis/ml/calendars/get_calendars.ts +++ b/x-pack/test/api_integration/apis/ml/calendars/get_calendars.ts @@ -35,7 +35,6 @@ export default ({ getService }: FtrProviderContext) => { beforeEach(async () => { for (const testCalendar of testCalendars) { await ml.api.createCalendar(testCalendar.calendar_id, testCalendar); - // @ts-expect-error not full interface await ml.api.createCalendarEvents(testCalendar.calendar_id, testEvents); } }); @@ -55,7 +54,6 @@ export default ({ getService }: FtrProviderContext) => { expect(body).to.have.length(testCalendars.length); expect(body[0].events).to.have.length(testEvents.length); - // @ts-expect-error not full interface ml.api.assertAllEventsExistInCalendar(testEvents, body[0]); }); @@ -68,7 +66,6 @@ export default ({ getService }: FtrProviderContext) => { expect(body).to.have.length(testCalendars.length); expect(body[0].events).to.have.length(testEvents.length); - // @ts-expect-error not full interface ml.api.assertAllEventsExistInCalendar(testEvents, body[0]); }); @@ -92,7 +89,6 @@ export default ({ getService }: FtrProviderContext) => { beforeEach(async () => { await ml.api.createCalendar(calendarId, testCalendar); - // @ts-expect-error not full interface await ml.api.createCalendarEvents(calendarId, testEvents); }); @@ -110,7 +106,6 @@ export default ({ getService }: FtrProviderContext) => { expect(body.job_ids).to.eql(testCalendar.job_ids); expect(body.description).to.eql(testCalendar.description); expect(body.events).to.have.length(testEvents.length); - // @ts-expect-error not full interface ml.api.assertAllEventsExistInCalendar(testEvents, body); }); @@ -124,7 +119,6 @@ export default ({ getService }: FtrProviderContext) => { expect(body.job_ids).to.eql(testCalendar.job_ids); expect(body.description).to.eql(testCalendar.description); expect(body.events).to.have.length(testEvents.length); - // @ts-expect-error not full interface ml.api.assertAllEventsExistInCalendar(testEvents, body); }); diff --git a/x-pack/test/api_integration/apis/ml/calendars/helpers.ts b/x-pack/test/api_integration/apis/ml/calendars/helpers.ts index f80c985c2676eb..4667eb25437b1c 100644 --- a/x-pack/test/api_integration/apis/ml/calendars/helpers.ts +++ b/x-pack/test/api_integration/apis/ml/calendars/helpers.ts @@ -8,7 +8,7 @@ import { estypes } from '@elastic/elasticsearch'; import { Calendar } from '../../../../../plugins/ml/server/models/calendar'; -type ScheduledEvent = estypes.ScheduledEvent; +type ScheduledEvent = estypes.MlCalendarEvent; export const assertAllEventsExistInCalendar = ( eventsToCheck: ScheduledEvent[], diff --git a/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts index 4798a3407be115..1ca9a663199436 100644 --- a/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts +++ b/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts @@ -42,7 +42,6 @@ export default ({ getService }: FtrProviderContext) => { beforeEach(async () => { await ml.api.createCalendar(calendarId, originalCalendar); - // @ts-expect-error not full interface await ml.api.createCalendarEvents(calendarId, originalEvents); }); @@ -71,7 +70,6 @@ export default ({ getService }: FtrProviderContext) => { expect(updatedEvents).to.have.length(updateCalendarRequestBody.events.length); await ml.api.waitForEventsToExistInCalendar( updatedCalendar.calendar_id, - // @ts-expect-error not full interface updateCalendarRequestBody.events ); }); diff --git a/x-pack/test/api_integration/apis/ml/jobs/jobs_summary.ts b/x-pack/test/api_integration/apis/ml/jobs/jobs_summary.ts index a0c00770f84dc8..4e3be92a54b6a7 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/jobs_summary.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/jobs_summary.ts @@ -183,10 +183,10 @@ export default ({ getService }: FtrProviderContext) => { return body; } - function getGroups(jobs: Array<{ groups: string[] }>) { + function getGroups(jobs: Array<{ groups?: string[] }>) { const groupIds: string[] = []; jobs.forEach((job) => { - const groups = job.groups; + const groups = job.groups || []; groups.forEach((group) => { if (groupIds.indexOf(group) === -1) { groupIds.push(group); diff --git a/x-pack/test/api_integration/apis/security/roles.ts b/x-pack/test/api_integration/apis/security/roles.ts index 09b2d2eef9fbe4..440bb4ca32f189 100644 --- a/x-pack/test/api_integration/apis/security/roles.ts +++ b/x-pack/test/api_integration/apis/security/roles.ts @@ -312,7 +312,6 @@ export default function ({ getService }: FtrProviderContext) { metadata: { foo: 'test-metadata', }, - // @ts-expect-error @elastic/elasticsearch PutRoleRequest.body doesn't declare `transient_metadata` property transient_metadata: { enabled: true, }, diff --git a/x-pack/test/api_integration/apis/upgrade_assistant/upgrade_assistant.ts b/x-pack/test/api_integration/apis/upgrade_assistant/upgrade_assistant.ts index 7041427fb74d75..0eb0b98e29ffef 100644 --- a/x-pack/test/api_integration/apis/upgrade_assistant/upgrade_assistant.ts +++ b/x-pack/test/api_integration/apis/upgrade_assistant/upgrade_assistant.ts @@ -93,6 +93,7 @@ export default function ({ getService }: FtrProviderContext) { index: indexName, }); + // @ts-expect-error @elastic/elasticsearch supports flatten 'index.*' keys only const updatedIndexSettings = indexSettingsResponse[indexName].settings.index; // Verify number_of_shards and number_of_replicas are unchanged diff --git a/x-pack/test/apm_api_integration/tests/alerts/rule_registry.ts b/x-pack/test/apm_api_integration/tests/alerts/rule_registry.ts index eb10ff691d43b0..f6c51a7b04c1f0 100644 --- a/x-pack/test/apm_api_integration/tests/alerts/rule_registry.ts +++ b/x-pack/test/apm_api_integration/tests/alerts/rule_registry.ts @@ -612,7 +612,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { expect(errorOrUndefined).not.to.be(undefined); - expect(errorOrUndefined).to.be(`ResponseError: index_not_found_exception`); + expect(errorOrUndefined).to.contain('index_not_found_exception'); }); }); } diff --git a/x-pack/test/apm_api_integration/tests/service_overview/dependencies/es_utils.ts b/x-pack/test/apm_api_integration/tests/service_overview/dependencies/es_utils.ts index dbbc8ebc879587..b1663ea714056d 100644 --- a/x-pack/test/apm_api_integration/tests/service_overview/dependencies/es_utils.ts +++ b/x-pack/test/apm_api_integration/tests/service_overview/dependencies/es_utils.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { MappingTypeMapping } from '@elastic/elasticsearch/api/types'; import uuid from 'uuid'; export function createServiceDependencyDocs({ @@ -125,7 +126,7 @@ export function createServiceDependencyDocs({ ]; } -export const apmDependenciesMapping = { +export const apmDependenciesMapping: MappingTypeMapping = { properties: { '@timestamp': { type: 'date', diff --git a/x-pack/test/case_api_integration/common/lib/utils.ts b/x-pack/test/case_api_integration/common/lib/utils.ts index c66aeb67b3a5fc..9ed5d84e54621e 100644 --- a/x-pack/test/case_api_integration/common/lib/utils.ts +++ b/x-pack/test/case_api_integration/common/lib/utils.ts @@ -72,7 +72,7 @@ export const getSignalsWithES = async ({ es: KibanaClient; indices: string | string[]; ids: string | string[]; -}): Promise>>> => { +}): Promise>>> => { const signals: ApiResponse> = await es.search({ index: indices, body: { @@ -94,13 +94,13 @@ export const getSignalsWithES = async ({ return signals.body.hits.hits.reduce((acc, hit) => { let indexMap = acc.get(hit._index); if (indexMap === undefined) { - indexMap = new Map>([[hit._id, hit]]); + indexMap = new Map>([[hit._id, hit]]); } else { indexMap.set(hit._id, hit); } acc.set(hit._index, indexMap); return acc; - }, new Map>>()); + }, new Map>>()); }; interface SetStatusCasesParams { @@ -473,7 +473,6 @@ export const deleteAllCaseItems = async (es: KibanaClient) => { export const deleteCasesUserActions = async (es: KibanaClient): Promise => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:cases-user-actions', wait_for_completion: true, refresh: true, @@ -485,7 +484,6 @@ export const deleteCasesUserActions = async (es: KibanaClient): Promise => export const deleteCasesByESQuery = async (es: KibanaClient): Promise => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:cases', wait_for_completion: true, refresh: true, @@ -501,7 +499,6 @@ export const deleteCasesByESQuery = async (es: KibanaClient): Promise => { export const deleteSubCases = async (es: KibanaClient): Promise => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:cases-sub-case', wait_for_completion: true, refresh: true, @@ -513,7 +510,6 @@ export const deleteSubCases = async (es: KibanaClient): Promise => { export const deleteComments = async (es: KibanaClient): Promise => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:cases-comments', wait_for_completion: true, refresh: true, @@ -525,7 +521,6 @@ export const deleteComments = async (es: KibanaClient): Promise => { export const deleteConfiguration = async (es: KibanaClient): Promise => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:cases-configure', wait_for_completion: true, refresh: true, @@ -537,7 +532,6 @@ export const deleteConfiguration = async (es: KibanaClient): Promise => { export const deleteMappings = async (es: KibanaClient): Promise => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:cases-connector-mappings', wait_for_completion: true, refresh: true, diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_signals_migrations.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_signals_migrations.ts index 9bb3e776f45532..8c4ad5a2e81170 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_signals_migrations.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_signals_migrations.ts @@ -96,6 +96,7 @@ export default ({ getService }: FtrProviderContext): void => { .expect(200); const { body } = await es.indices.getSettings({ index: createdMigration.index }); + // @ts-expect-error @elastic/elasticsearch supports flatten 'index.*' keys only const indexSettings = body[createdMigration.index].settings.index; expect(indexSettings.lifecycle.name).to.eql( `${DEFAULT_SIGNALS_INDEX}-default-migration-cleanup` diff --git a/x-pack/test/detection_engine_api_integration/utils.ts b/x-pack/test/detection_engine_api_integration/utils.ts index 9c5beebd64b3d3..7456040a436a4b 100644 --- a/x-pack/test/detection_engine_api_integration/utils.ts +++ b/x-pack/test/detection_engine_api_integration/utils.ts @@ -412,7 +412,6 @@ export const downgradeImmutableRule = async (es: KibanaClient, ruleId: string): export const deleteAllTimelines = async (es: KibanaClient): Promise => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:siem-ui-timeline', wait_for_completion: true, refresh: true, @@ -429,7 +428,6 @@ export const deleteAllRulesStatuses = async (es: KibanaClient): Promise => return countDownES(async () => { return es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:siem-detection-engine-rule-status', wait_for_completion: true, refresh: true, diff --git a/x-pack/test/encrypted_saved_objects_api_integration/tests/encrypted_saved_objects_api.ts b/x-pack/test/encrypted_saved_objects_api_integration/tests/encrypted_saved_objects_api.ts index f6b0f4e8250973..9ee92a8a1848f7 100644 --- a/x-pack/test/encrypted_saved_objects_api_integration/tests/encrypted_saved_objects_api.ts +++ b/x-pack/test/encrypted_saved_objects_api_integration/tests/encrypted_saved_objects_api.ts @@ -442,7 +442,6 @@ export default function ({ getService }: FtrProviderContext) { afterEach(async () => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch `DeleteByQueryRequest` type doesn't define `q`. q: `type:${SAVED_OBJECT_WITH_SECRET_TYPE} OR type:${HIDDEN_SAVED_OBJECT_WITH_SECRET_TYPE} OR type:${SAVED_OBJECT_WITH_SECRET_AND_MULTIPLE_SPACES_TYPE} OR type:${SAVED_OBJECT_WITHOUT_SECRET_TYPE}`, refresh: true, body: {}, @@ -492,7 +491,6 @@ export default function ({ getService }: FtrProviderContext) { afterEach(async () => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch `DeleteByQueryRequest` type doesn't define `q`. q: `type:${SAVED_OBJECT_WITH_SECRET_TYPE} OR type:${HIDDEN_SAVED_OBJECT_WITH_SECRET_TYPE} OR type:${SAVED_OBJECT_WITH_SECRET_AND_MULTIPLE_SPACES_TYPE} OR type:${SAVED_OBJECT_WITHOUT_SECRET_TYPE}`, refresh: true, body: {}, diff --git a/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts b/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts index 25fb71ae42807d..b38458f7334c4c 100644 --- a/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts +++ b/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts @@ -177,7 +177,6 @@ export default function (providerContext: FtrProviderContext) { id: apiResponse.item.api_key_id, }); - // @ts-expect-error Metadata not yet in the client type expect(apiKeyRes.api_keys[0].metadata).eql({ policy_id: 'policy1', managed_by: 'fleet', diff --git a/x-pack/test/functional/apps/ml/permissions/full_ml_access.ts b/x-pack/test/functional/apps/ml/permissions/full_ml_access.ts index a203b078774c7c..87f74363413d3c 100644 --- a/x-pack/test/functional/apps/ml/permissions/full_ml_access.ts +++ b/x-pack/test/functional/apps/ml/permissions/full_ml_access.ts @@ -136,7 +136,6 @@ export default function ({ getService }: FtrProviderContext) { description: 'Test calendar', }); await ml.api.createCalendarEvents(calendarId, [ - // @ts-expect-error not full interface { description: eventDescription, start_time: '1513641600000', diff --git a/x-pack/test/functional/apps/ml/permissions/read_ml_access.ts b/x-pack/test/functional/apps/ml/permissions/read_ml_access.ts index 55cfb035d0cfe0..5e6e179a7bdcce 100644 --- a/x-pack/test/functional/apps/ml/permissions/read_ml_access.ts +++ b/x-pack/test/functional/apps/ml/permissions/read_ml_access.ts @@ -137,7 +137,6 @@ export default function ({ getService }: FtrProviderContext) { description: 'Test calendar', }); await ml.api.createCalendarEvents(calendarId, [ - // @ts-expect-error not full interface { description: eventDescription, start_time: '1513641600000', diff --git a/x-pack/test/functional/apps/ml/settings/calendar_edit.ts b/x-pack/test/functional/apps/ml/settings/calendar_edit.ts index 1237cd8d71b8c4..a643c4eb342997 100644 --- a/x-pack/test/functional/apps/ml/settings/calendar_edit.ts +++ b/x-pack/test/functional/apps/ml/settings/calendar_edit.ts @@ -35,7 +35,6 @@ export default function ({ getService }: FtrProviderContext) { job_ids: jobConfigs.map((c) => c.job_id), description: 'Test calendar', }); - // @ts-expect-error not full interface await ml.api.createCalendarEvents(calendarId, testEvents); await ml.testResources.setKibanaTimeZoneToUTC(); diff --git a/x-pack/test/functional/services/ml/api.ts b/x-pack/test/functional/services/ml/api.ts index 4623b4f4e41ae9..9a96b1ec372dc5 100644 --- a/x-pack/test/functional/services/ml/api.ts +++ b/x-pack/test/functional/services/ml/api.ts @@ -384,7 +384,7 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { }); }, - async createCalendarEvents(calendarId: string, events: estypes.ScheduledEvent[]) { + async createCalendarEvents(calendarId: string, events: estypes.MlCalendarEvent[]) { log.debug(`Creating events for calendar with id '${calendarId}'...`); await esSupertest.post(`/_ml/calendars/${calendarId}/events`).send({ events }).expect(200); await this.waitForEventsToExistInCalendar(calendarId, events); @@ -396,7 +396,7 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { }, assertAllEventsExistInCalendar: ( - eventsToCheck: estypes.ScheduledEvent[], + eventsToCheck: estypes.MlCalendarEvent[], calendar: Calendar ): boolean => { const updatedCalendarEvents = calendar.events; @@ -409,7 +409,7 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { (updatedEvent) => updatedEvent.description === eventToCheck.description && // updatedEvent are fetched with suptertest which converts start_time and end_time to number - // sometimes eventToCheck declared manually with types incompatible with estypes.ScheduledEvent + // sometimes eventToCheck declared manually with types incompatible with estypes.MlCalendarEvent String(updatedEvent.start_time) === String(eventToCheck.start_time) && String(updatedEvent.end_time) === String(eventToCheck.end_time) ) < 0 @@ -429,7 +429,7 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { async waitForEventsToExistInCalendar( calendarId: string, - eventsToCheck: estypes.ScheduledEvent[], + eventsToCheck: estypes.MlCalendarEvent[], errorMsg?: string ) { await retry.waitForWithTimeout(`'${calendarId}' events to exist`, 5 * 1000, async () => { diff --git a/x-pack/test/functional_with_es_ssl/apps/ml/alert_flyout.ts b/x-pack/test/functional_with_es_ssl/apps/ml/alert_flyout.ts index 1a8395a1b49df5..2c80f4b2ebd917 100644 --- a/x-pack/test/functional_with_es_ssl/apps/ml/alert_flyout.ts +++ b/x-pack/test/functional_with_es_ssl/apps/ml/alert_flyout.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Datafeed } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { FtrProviderContext } from '../../ftr_provider_context'; import { DATAFEED_STATE } from '../../../../plugins/ml/common/constants/states'; @@ -56,7 +56,7 @@ function createTestJobAndDatafeed() { }, query_delay: '120s', indices: ['ft_ecommerce'], - } as unknown) as Datafeed, + } as unknown) as estypes.MlDatafeed, }; } diff --git a/x-pack/test/lists_api_integration/utils.ts b/x-pack/test/lists_api_integration/utils.ts index 2467e613ca2f58..90103ec8b856c3 100644 --- a/x-pack/test/lists_api_integration/utils.ts +++ b/x-pack/test/lists_api_integration/utils.ts @@ -161,7 +161,6 @@ export const deleteAllExceptions = async (es: KibanaClient): Promise => { return countDownES(async () => { return es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:exception-list or type:exception-list-agnostic', wait_for_completion: true, refresh: true, diff --git a/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts b/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts index 26333ecabd505d..b8ba9c93fe8b07 100644 --- a/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts +++ b/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts @@ -7,6 +7,7 @@ import _ from 'lodash'; import expect from '@kbn/expect'; +import type { estypes } from '@elastic/elasticsearch'; import url from 'url'; import supertestAsPromised from 'supertest-as-promised'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -87,7 +88,7 @@ export default function ({ getService }: FtrProviderContext) { params: taskManagerIndexMapping.params, state: taskManagerIndexMapping.state, runAt: taskManagerIndexMapping.runAt, - }, + } as Record, }, }, }); diff --git a/x-pack/test/saved_object_api_integration/common/fixtures/saved_object_test_plugin/server/plugin.ts b/x-pack/test/saved_object_api_integration/common/fixtures/saved_object_test_plugin/server/plugin.ts index e29bbc0db56b6a..36bbbb4bb8755e 100644 --- a/x-pack/test/saved_object_api_integration/common/fixtures/saved_object_test_plugin/server/plugin.ts +++ b/x-pack/test/saved_object_api_integration/common/fixtures/saved_object_test_plugin/server/plugin.ts @@ -22,7 +22,7 @@ export class Plugin { properties: { title: { type: 'text' }, }, - }; + } as const; core.savedObjects.registerType({ name: 'isolatedtype', diff --git a/x-pack/test/security_api_integration/tests/anonymous/login.ts b/x-pack/test/security_api_integration/tests/anonymous/login.ts index 30d5d3ea331207..05f3adf2b8cb6c 100644 --- a/x-pack/test/security_api_integration/tests/anonymous/login.ts +++ b/x-pack/test/security_api_integration/tests/anonymous/login.ts @@ -162,12 +162,13 @@ export default function ({ getService }: FtrProviderContext) { .set('kbn-xsrf', 'xxx') .set('Authorization', 'Basic ZHVtbXlfaGFja2VyOnBhc3M=') .set('Cookie', sessionCookie.cookieString()) - .expect(401, { - statusCode: 401, - error: 'Unauthorized', - message: - '[security_exception]: unable to authenticate user [dummy_hacker] for REST request [/_security/_authenticate]', - }); + .expect(401); + + expect(apiResponse.body.statusCode).to.be(401); + expect(apiResponse.body.error).to.be('Unauthorized'); + expect(apiResponse.body.message).to.include.string( + '[security_exception] Reason: unable to authenticate user [dummy_hacker] for REST request [/_security/_authenticate]' + ); expect(apiResponse.headers['set-cookie']).to.be(undefined); }); diff --git a/yarn.lock b/yarn.lock index 6d3da3bd879ba1..5a9b30fbd9dd28 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1410,16 +1410,15 @@ dependencies: "@elastic/ecs-helpers" "^1.1.0" -"@elastic/elasticsearch@npm:@elastic/elasticsearch-canary@^8.0.0-canary.4": - version "8.0.0-canary.4" - resolved "https://registry.yarnpkg.com/@elastic/elasticsearch-canary/-/elasticsearch-canary-8.0.0-canary.4.tgz#6f1a592974941baae347eb8c66a2006848349717" - integrity sha512-UexFloloyvGOhvMc1ePRHCy89sjQL6rPTTZkXAB/GcC8rCvA3mgSnIY2+Ylvctdv9o4l+M4Bkw8azICulyhwMg== +"@elastic/elasticsearch@npm:@elastic/elasticsearch-canary@^8.0.0-canary.13": + version "8.0.0-canary.13" + resolved "https://registry.yarnpkg.com/@elastic/elasticsearch-canary/-/elasticsearch-canary-8.0.0-canary.13.tgz#bb5c71440411703364701eabae7960c8899d2012" + integrity sha512-QbwwpOqnarG469fIJw9VL+PTs4WLHl5M6OsEZA3IqQOlMfjtXEMdC0dRQoVz8UCcDW1rp+r87QPDkMneCFxFKg== dependencies: debug "^4.3.1" hpagent "^0.1.1" ms "^2.1.3" - pump "^3.0.0" - secure-json-parse "^2.3.1" + secure-json-parse "^2.4.0" "@elastic/ems-client@7.13.0": version "7.13.0" @@ -24705,10 +24704,10 @@ scss-tokenizer@^0.2.3: js-base64 "^2.1.8" source-map "^0.4.2" -secure-json-parse@^2.3.1: - version "2.3.1" - resolved "https://registry.yarnpkg.com/secure-json-parse/-/secure-json-parse-2.3.1.tgz#908aa5e806e223ff8d179d37ad95c2433f5f147d" - integrity sha512-5uGhQLHSC9tVa7RGPkSwxbZVsJCZvIODOadAimCXkU1aCa1fWdszj2DktcutK8A7dD58PoRdxTYiy0jFl6qjnw== +secure-json-parse@^2.4.0: + version "2.4.0" + resolved "https://registry.yarnpkg.com/secure-json-parse/-/secure-json-parse-2.4.0.tgz#5aaeaaef85c7a417f76271a4f5b0cc3315ddca85" + integrity sha512-Q5Z/97nbON5t/L/sH6mY2EacfjVGwrCcSi5D3btRO2GZ8pf1K1UN7Z9H5J57hjVU2Qzxr1xO+FmBhOvEkzCMmg== seed-random@~2.2.0: version "2.2.0"