From 501dc8f1836b76cb2331a834ae599ac404f24ed0 Mon Sep 17 00:00:00 2001 From: restrry Date: Mon, 26 Apr 2021 09:21:29 +0200 Subject: [PATCH 01/86] bump @elastic/elasticsearch to canary.7 --- package.json | 2 +- yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 6af5c256c57fa..8ec874b16306d 100644 --- a/package.json +++ b/package.json @@ -99,7 +99,7 @@ "@elastic/apm-rum-react": "^1.2.5", "@elastic/charts": "29.0.0", "@elastic/datemath": "link:bazel-bin/packages/elastic-datemath/npm_module", - "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.4", + "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.7", "@elastic/ems-client": "7.13.0", "@elastic/eui": "32.1.0", "@elastic/filesaver": "1.1.2", diff --git a/yarn.lock b/yarn.lock index 1c33d64afbec0..76b10c948282c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1389,10 +1389,10 @@ version "0.0.0" uid "" -"@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.7": + version "8.0.0-canary.7" + resolved "https://registry.yarnpkg.com/@elastic/elasticsearch-canary/-/elasticsearch-canary-8.0.0-canary.7.tgz#e4870cd9ec225e3975d950d1a6f42599cfbed35f" + integrity sha512-ZLP8tt0H13N3YUyajDDpKFAxr9zjzbEIBaiY8XImDrg0+qimG+x6SgeONFAsKOJvyQ08WRSreM4Pn3Qt+tCjZA== dependencies: debug "^4.3.1" hpagent "^0.1.1" From f54192ec3e5f58fa63c0abf06892ddd306b1da2c Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Mon, 26 Apr 2021 11:44:51 +0200 Subject: [PATCH 02/86] address errors in core --- .../mappings/lib/get_property.test.ts | 2 +- .../lib/get_root_properties_objects.test.ts | 16 ++++++------ .../server/saved_objects/mappings/types.ts | 26 +++++++++---------- .../core/build_active_mappings.test.ts | 8 +++--- .../migrations/core/build_index_map.test.ts | 14 +++++----- .../migrations/core/elastic_index.test.ts | 4 +-- .../migrations/core/elastic_index.ts | 3 ++- .../migrations/core/migration_context.test.ts | 4 +-- .../migrations/kibana/kibana_migrator.test.ts | 6 ++++- .../migrationsv2/actions/index.ts | 7 ++--- .../saved_objects/migrationsv2/model.test.ts | 4 +-- .../saved_objects_type_registry.ts | 2 +- .../lib/aggregations/validation.test.ts | 4 +-- .../lib/aggregations/validation_utils.test.ts | 4 +-- .../service/lib/filter_utils.test.ts | 4 +-- .../saved_objects/service/lib/repository.ts | 12 +++------ .../lib/search_dsl/sorting_params.test.ts | 2 +- 17 files changed, 61 insertions(+), 61 deletions(-) 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 dab712bbb87ad..8732b5e07d3fa 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_root_properties_objects.test.ts b/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.test.ts index 2daca3a1fdd83..cbc6808418bc0 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/types.ts b/src/core/server/saved_objects/mappings/types.ts index 25fb61de93518..15c6b744c1c6e 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. * @@ -120,18 +121,17 @@ export interface IndexMappingMeta { * * @public */ -export interface SavedObjectsCoreFieldMapping { - type: string; - null_value?: number | boolean | string; - index?: boolean; - doc_values?: boolean; - fields?: { - [subfield: string]: { - type: string; - ignore_above?: number; - }; - }; -} +export type SavedObjectsCoreFieldMapping = estypes.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`. + */ + dynamic?: false | 'strict'; +}; /** * See {@link SavedObjectsFieldMapping} for documentation. @@ -150,6 +150,6 @@ export interface SavedObjectsComplexFieldMapping { dynamic?: false | 'strict'; enabled?: boolean; doc_values?: boolean; - type?: string; + type?: estypes.Property['type']; 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 5465da2f620ad..a39fff20abbe7 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 c7a3251e33ab1..ec1c765cf6cf0 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: 'join', }, }, }, @@ -48,7 +48,7 @@ test('mappings without index pattern goes to default index', () => { type1: { properties: { field1: { - type: 'string', + type: 'join', }, }, }, @@ -69,7 +69,7 @@ test(`mappings with custom index pattern doesn't go to default index`, () => { type1: { properties: { field1: { - type: 'string', + type: 'join', }, }, }, @@ -103,7 +103,7 @@ test('creating a script gets added to the index pattern', () => { type1: { properties: { field1: { - type: 'string', + type: 'join', }, }, }, @@ -144,18 +144,18 @@ test('throws when two scripts are defined for an index pattern', () => { type1: { properties: { field1: { - type: 'string', + type: 'join', }, }, }, type2: { properties: { field1: { - type: 'string', + type: 'join', }, }, }, - }; + } 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 1d2ec6abc0dd1..c32f7483abf66 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,7 +40,7 @@ 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); @@ -175,7 +175,7 @@ describe('ElasticIndex', () => { dynamic: 'strict' as const, properties: { foo: { type: 'keyword' } }, }, - }; + } as const; await Index.convertToAlias( client, 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 460aabbc77415..0e31ff44bd62b 100644 --- a/src/core/server/saved_objects/migrations/core/elastic_index.ts +++ b/src/core/server/saved_objects/migrations/core/elastic_index.ts @@ -261,6 +261,7 @@ export async function createIndex( mappings?: IndexMapping ) { await client.indices.create({ + // @ts-expect-error @elastic-elasticsearch types don't support nested properties body: { mappings, settings }, index, }); @@ -283,6 +284,7 @@ export async function convertToAlias( script?: string ) { await client.indices.create({ + // @ts-expect-error @elastic-elasticsearch types don't support nested properties body: { mappings: info.mappings, settings }, index: info.indexName, }); @@ -406,7 +408,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/migration_context.test.ts b/src/core/server/saved_objects/migrations/core/migration_context.test.ts index 5f2e8a37ec427..240b41266abb6 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 221e78e3e12e2..f819f9775aaa3 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 @@ -362,7 +362,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({ diff --git a/src/core/server/saved_objects/migrationsv2/actions/index.ts b/src/core/server/saved_objects/migrationsv2/actions/index.ts index 02d3f8e21a510..45f4e25dc97ea 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/index.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/index.ts @@ -305,7 +305,7 @@ export const cloneIndex = ( }; 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; @@ -367,7 +367,6 @@ 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, @@ -523,7 +522,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)); @@ -720,6 +719,7 @@ export const createIndex = ( // started timeout: DEFAULT_TIMEOUT, body: { + // @ts-expect-error @elastic-elasticsearch types don't support nested properties mappings, aliases: aliasesObject, settings: { @@ -813,6 +813,7 @@ export const updateAndPickupMappings = ( .putMapping({ index, timeout: DEFAULT_TIMEOUT, + // @ts-expect-error @elastic-elasticsearch types don't support nested properties body: mappings, }) .then((res) => { diff --git a/src/core/server/saved_objects/migrationsv2/model.test.ts b/src/core/server/saved_objects/migrationsv2/model.test.ts index 0267ae33dd157..462a7f166f9e3 100644 --- a/src/core/server/saved_objects/migrationsv2/model.test.ts +++ b/src/core/server/saved_objects/migrationsv2/model.test.ts @@ -210,7 +210,7 @@ describe('migrations v2 model', () => { disabled_saved_object_type: '7997cf5a56cc02bdc9c93361bde732b0', }, }, - }; + } as const; test('INIT -> OUTDATED_DOCUMENTS_SEARCH if .kibana is already pointing to the target index', () => { const res: ResponseType<'INIT'> = Either.right({ @@ -657,7 +657,7 @@ describe('migrations v2 model', () => { disabled_saved_object_type: '7997cf5a56cc02bdc9c93361bde732b0', }, }, - }; + } as const; const waitForYellowSourceState: WaitForYellowSourceState = { ...baseState, 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 a63837132b652..ba5960c59239d 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 8a7c1c3719eb0..e131bc0ec92b9 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 @@ -25,7 +25,7 @@ const mockMappings = { type: 'text', }, bytes: { - type: 'number', + type: 'integer', }, }, }, @@ -67,7 +67,7 @@ const mockMappings = { }, }, }, -}; +} as const; describe('validateAndConvertAggregations', () => { it('validates a simple aggregations', () => { 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 25c3aea474ece..456c898f66534 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 @@ -28,7 +28,7 @@ const mockMappings: IndexMapping = { type: 'text', }, bytes: { - type: 'number', + type: 'integer', }, }, }, @@ -70,7 +70,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 2ef5219ccfff1..e6934398862dc 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 c0e2cdc333363..ca6479ff0829a 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -665,7 +665,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 @@ -1386,7 +1385,6 @@ export class SavedObjectsRepository { } const deleteDocNotFound = body.result === 'not_found'; - // @ts-expect-error const deleteIndexNotFound = body.error && body.error.type === 'index_not_found_exception'; if (deleteDocNotFound || deleteIndexNotFound) { // see "404s from missing index" above @@ -1920,13 +1918,9 @@ export class SavedObjectsRepository { const { body, statusCode, - } = await this.client.openPointInTime( - // @ts-expect-error @elastic/elasticsearch OpenPointInTimeRequest.index expected to accept string[] - esOptions, - { - ignore: [404], - } - ); + } = 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/sorting_params.test.ts b/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.test.ts index 1376f0d50a9da..e2a21cc03ce3b 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', () => { From 2db55e3ee0e928609861dc537da907a4ce44b967 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Mon, 26 Apr 2021 11:46:15 +0200 Subject: [PATCH 03/86] address errors in data plugin --- src/plugins/data/server/search/routes/call_msearch.ts | 7 +++++-- .../search/strategies/eql_search/eql_search_strategy.ts | 3 ++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/plugins/data/server/search/routes/call_msearch.ts b/src/plugins/data/server/search/routes/call_msearch.ts index 0c238adf831bd..4a7db9517c688 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/strategies/eql_search/eql_search_strategy.ts b/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts index 0e3acedfe12f6..91de0fca3674c 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); }; From e8f4424269bfc7ead2d96b4e3f557c806d44f97a Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Mon, 26 Apr 2021 11:48:40 +0200 Subject: [PATCH 04/86] address errors in Alerting team plugins --- x-pack/plugins/actions/server/saved_objects/index.ts | 6 +++--- x-pack/plugins/alerting/server/saved_objects/index.ts | 4 ++-- .../task_manager/server/monitoring/workload_statistics.ts | 3 --- x-pack/plugins/task_manager/server/saved_objects/index.ts | 4 ++-- 4 files changed, 7 insertions(+), 10 deletions(-) diff --git a/x-pack/plugins/actions/server/saved_objects/index.ts b/x-pack/plugins/actions/server/saved_objects/index.ts index c8626660de2d9..4ee7f3a6e1629 100644 --- a/x-pack/plugins/actions/server/saved_objects/index.ts +++ b/x-pack/plugins/actions/server/saved_objects/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { SavedObjectsServiceSetup } from 'kibana/server'; +import type { SavedObjectsServiceSetup, SavedObjectsTypeMappingDefinition } from 'kibana/server'; import { EncryptedSavedObjectsPluginSetup } from '../../../encrypted_saved_objects/server'; import mappings from './mappings.json'; import { getMigrations } from './migrations'; @@ -22,7 +22,7 @@ export function setupSavedObjects( name: ACTION_SAVED_OBJECT_TYPE, hidden: true, namespaceType: 'single', - mappings: mappings.action, + mappings: mappings.action as SavedObjectsTypeMappingDefinition, migrations: getMigrations(encryptedSavedObjects), }); @@ -40,7 +40,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/saved_objects/index.ts b/x-pack/plugins/alerting/server/saved_objects/index.ts index bb4383083fedc..96bea843a10f5 100644 --- a/x-pack/plugins/alerting/server/saved_objects/index.ts +++ b/x-pack/plugins/alerting/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 { getMigrations } from './migrations'; import { EncryptedSavedObjectsPluginSetup } from '../../../encrypted_saved_objects/server'; @@ -42,7 +42,7 @@ export function setupSavedObjects( hidden: true, namespaceType: 'single', migrations: getMigrations(encryptedSavedObjects), - mappings: mappings.alert, + mappings: mappings.alert as SavedObjectsTypeMappingDefinition, }); savedObjects.registerType({ 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 c79b310822c3e..456b9a8492080 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)}`, }, ], 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 33b57b62b31aa..c032e8d658a40 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, }); From 5a06616d344012286908537e521e5fec81f5d4ed Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Mon, 26 Apr 2021 11:49:06 +0200 Subject: [PATCH 05/86] remove outdated messages in Lens --- x-pack/plugins/lens/server/routes/existing_fields.ts | 1 - x-pack/plugins/lens/server/routes/field_stats.ts | 1 - 2 files changed, 2 deletions(-) diff --git a/x-pack/plugins/lens/server/routes/existing_fields.ts b/x-pack/plugins/lens/server/routes/existing_fields.ts index d775113d83ff7..358756d38173f 100644 --- a/x-pack/plugins/lens/server/routes/existing_fields.ts +++ b/x-pack/plugins/lens/server/routes/existing_fields.ts @@ -201,7 +201,6 @@ 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), diff --git a/x-pack/plugins/lens/server/routes/field_stats.ts b/x-pack/plugins/lens/server/routes/field_stats.ts index 6cddd2c60f416..038f940c29e6c 100644 --- a/x-pack/plugins/lens/server/routes/field_stats.ts +++ b/x-pack/plugins/lens/server/routes/field_stats.ts @@ -85,7 +85,6 @@ export async function initFieldsRoute(setup: CoreSetup) { body: { query, aggs, - // @ts-expect-error @elastic/elasticsearch StoredScript.language is required runtime_mappings: field.runtimeField ? { [fieldName]: field.runtimeField } : {}, }, size: 0, From 2201e2561684e6b4e40c0832ec4d24118ca07e5c Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Mon, 26 Apr 2021 11:49:27 +0200 Subject: [PATCH 06/86] remove unnecessary comments in ML --- .../plugins/ml/server/models/fields_service/fields_service.ts | 2 -- 1 file changed, 2 deletions(-) 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 cfe0bcc532630..e608bfeb622d8 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 ?? {}), }); From 2815faaf3cb2c9e8d6b0e0e4bdf7ee8ef8849367 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Mon, 26 Apr 2021 11:49:56 +0200 Subject: [PATCH 07/86] address errors in Observability plugin --- .../server/lib/annotations/create_annotations_client.ts | 1 + .../plugins/observability/server/lib/annotations/mappings.ts | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/observability/server/lib/annotations/create_annotations_client.ts b/x-pack/plugins/observability/server/lib/annotations/create_annotations_client.ts index 39a594dcc86ca..ad94467a88ed0 100644 --- a/x-pack/plugins/observability/server/lib/annotations/create_annotations_client.ts +++ b/x-pack/plugins/observability/server/lib/annotations/create_annotations_client.ts @@ -34,6 +34,7 @@ export function createAnnotationsClient(params: { const initIndex = () => createOrUpdateIndex({ index, + // @ts-expect-error @elastic-elasticsearch types don't support nested properties mappings, client: esClient, logger, diff --git a/x-pack/plugins/observability/server/lib/annotations/mappings.ts b/x-pack/plugins/observability/server/lib/annotations/mappings.ts index da72afdbecb33..3313c411b5889 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; From 1171f072f3c73b7b075d0c07c873fb3e4e88f87b Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Mon, 26 Apr 2021 11:50:21 +0200 Subject: [PATCH 08/86] address errors in reporting plugin --- x-pack/plugins/reporting/server/lib/store/mapping.ts | 2 +- x-pack/plugins/reporting/server/lib/store/store.ts | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/reporting/server/lib/store/mapping.ts b/x-pack/plugins/reporting/server/lib/store/mapping.ts index c35540f3869a0..ce8f768ef077f 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/reporting/server/lib/store/store.ts b/x-pack/plugins/reporting/server/lib/store/store.ts index fc7bd9c23d769..22a667cc01700 100644 --- a/x-pack/plugins/reporting/server/lib/store/store.ts +++ b/x-pack/plugins/reporting/server/lib/store/store.ts @@ -83,7 +83,11 @@ export class ReportingStore { }; try { - await client.indices.create({ index: indexName, body }); + await client.indices.create({ + index: indexName, + // @ts-expect-error @elastic/elasticsearch types don't support nested mappings + body, + }); return true; } catch (error) { From adcb00f410c6972dcce7d6f2c3afcd46a4c6fb6f Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Mon, 26 Apr 2021 11:50:52 +0200 Subject: [PATCH 09/86] address errors in Rule registry plugin --- .../server/rule_registry/field_map/mapping_from_field_map.ts | 4 ++-- x-pack/plugins/rule_registry/server/rule_registry/index.ts | 2 ++ x-pack/plugins/rule_registry/server/rule_registry/types.ts | 5 ----- 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/x-pack/plugins/rule_registry/server/rule_registry/field_map/mapping_from_field_map.ts b/x-pack/plugins/rule_registry/server/rule_registry/field_map/mapping_from_field_map.ts index f1d7126906431..d54ff03c6ae17 100644 --- a/x-pack/plugins/rule_registry/server/rule_registry/field_map/mapping_from_field_map.ts +++ b/x-pack/plugins/rule_registry/server/rule_registry/field_map/mapping_from_field_map.ts @@ -5,11 +5,11 @@ * 2.0. */ +import type { SavedObjectsTypeMappingDefinition } from 'src/core/server'; import { set } from '@elastic/safer-lodash-set'; import { FieldMap } from '../../../common'; -import { Mappings } from '../types'; -export function mappingFromFieldMap(fieldMap: FieldMap): Mappings { +export function mappingFromFieldMap(fieldMap: FieldMap): SavedObjectsTypeMappingDefinition { const mappings = { dynamic: 'strict' as const, properties: {}, diff --git a/x-pack/plugins/rule_registry/server/rule_registry/index.ts b/x-pack/plugins/rule_registry/server/rule_registry/index.ts index bbc381f60a809..8e050580ab422 100644 --- a/x-pack/plugins/rule_registry/server/rule_registry/index.ts +++ b/x-pack/plugins/rule_registry/server/rule_registry/index.ts @@ -137,6 +137,7 @@ export class RuleRegistry { name: indexAliasName, body: { index_patterns: [`${indexAliasName}-*`], + // @ts-expect-error @elastic/elasticsearch types don't support nested mappings mappings, }, create: false, @@ -186,6 +187,7 @@ export class RuleRegistry { await esClient.indices.putMapping({ index: indexAliasName, + // @ts-expect-error @elastic/elasticsearch types don't support nested mappings body: mappings, }); } diff --git a/x-pack/plugins/rule_registry/server/rule_registry/types.ts b/x-pack/plugins/rule_registry/server/rule_registry/types.ts index ec7293d1c1d4c..3675a82867cc5 100644 --- a/x-pack/plugins/rule_registry/server/rule_registry/types.ts +++ b/x-pack/plugins/rule_registry/server/rule_registry/types.ts @@ -5,11 +5,6 @@ * 2.0. */ -export interface Mappings { - dynamic: 'strict' | boolean; - properties: Record; -} - enum ILMPolicyPhase { hot = 'hot', delete = 'delete', From 911bdd3f86c84d3a8480e8bed69c496309ecf753 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Mon, 26 Apr 2021 11:51:26 +0200 Subject: [PATCH 10/86] fix errors in Security plugins --- .../security/server/routes/authorization/roles/put.ts | 1 - .../security/server/session_management/session_index.ts | 5 +++-- x-pack/plugins/spaces/server/saved_objects/mappings.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) 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 09bcb6b8c505c..5a0934721e20c 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 d7a4c3e2520bf..a437856ec56c2 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, }); } @@ -339,6 +339,7 @@ export class SessionIndex { try { await this.options.elasticsearchClient.indices.putTemplate({ name: sessionIndexTemplateName, + // @ts-expect-error @elastic-elasticsearch types don't support nested properties body: getSessionIndexTemplate(this.indexName), }); this.options.logger.debug('Successfully created session index template.'); diff --git a/x-pack/plugins/spaces/server/saved_objects/mappings.ts b/x-pack/plugins/spaces/server/saved_objects/mappings.ts index 2b1763f1de583..82a134bfdbf62 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 From c6ccefbf6e5de4e1f6f47e06def6d14dc68e3914 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Mon, 26 Apr 2021 11:51:50 +0200 Subject: [PATCH 11/86] fix errors in ES-UI plugin --- x-pack/plugins/snapshot_restore/server/routes/api/policy.ts | 1 + .../snapshot_restore/server/routes/api/repositories.ts | 1 - .../plugins/snapshot_restore/server/routes/api/snapshots.ts | 5 ----- .../upgrade_assistant/server/lib/es_migration_apis.test.ts | 1 + 4 files changed, 2 insertions(+), 6 deletions(-) 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 77264c4bffc9a..4c4a455f980f8 100644 --- a/x-pack/plugins/snapshot_restore/server/routes/api/policy.ts +++ b/x-pack/plugins/snapshot_restore/server/routes/api/policy.ts @@ -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 96099e3fbb1eb..4254562a0a886 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/snapshots.ts b/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.ts index 8f6f44f63a556..8ce33cb8cd05b 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/upgrade_assistant/server/lib/es_migration_apis.test.ts b/x-pack/plugins/upgrade_assistant/server/lib/es_migration_apis.test.ts index 2620fe31d6277..d78af9162e924 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 () => { From a79ded4e05e6ae8eb5a9b787114c1e1f902ffe44 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Mon, 26 Apr 2021 11:55:01 +0200 Subject: [PATCH 12/86] remove unnecessary union. --- src/core/server/saved_objects/mappings/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/server/saved_objects/mappings/types.ts b/src/core/server/saved_objects/mappings/types.ts index 15c6b744c1c6e..e50b8ea8b99aa 100644 --- a/src/core/server/saved_objects/mappings/types.ts +++ b/src/core/server/saved_objects/mappings/types.ts @@ -150,6 +150,6 @@ export interface SavedObjectsComplexFieldMapping { dynamic?: false | 'strict'; enabled?: boolean; doc_values?: boolean; - type?: estypes.Property['type']; + type?: string; properties: SavedObjectsMappingProperties; } From 78e0b57053b89d0aa4e6ba5034691d1cd014d3d0 Mon Sep 17 00:00:00 2001 From: restrry Date: Mon, 26 Apr 2021 12:02:46 +0200 Subject: [PATCH 13/86] update core tests --- .../migrations/core/build_index_map.test.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) 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 ec1c765cf6cf0..731b7f8c029c2 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: 'join', + type: 'text', }, }, }, @@ -48,7 +48,7 @@ test('mappings without index pattern goes to default index', () => { type1: { properties: { field1: { - type: 'join', + type: 'text', }, }, }, @@ -69,7 +69,7 @@ test(`mappings with custom index pattern doesn't go to default index`, () => { type1: { properties: { field1: { - type: 'join', + 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: 'join', + type: 'text', }, }, }, @@ -116,7 +116,7 @@ test('creating a script gets added to the index pattern', () => { type1: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, @@ -144,14 +144,14 @@ test('throws when two scripts are defined for an index pattern', () => { type1: { properties: { field1: { - type: 'join', + type: 'text', }, }, }, type2: { properties: { field1: { - type: 'join', + type: 'text', }, }, }, From 00d835674aa6b1bd30fa689cfe4f40d3159b16e5 Mon Sep 17 00:00:00 2001 From: restrry Date: Mon, 26 Apr 2021 12:26:24 +0200 Subject: [PATCH 14/86] fix kbn-es-archiver --- packages/kbn-es-archiver/src/lib/indices/delete_index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 2a42d52e2ca80..d3d6f85d7a360 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; From eb93d74fcb4120d6c9eb9832944627017d4622cb Mon Sep 17 00:00:00 2001 From: restrry Date: Tue, 4 May 2021 09:29:11 +0200 Subject: [PATCH 15/86] update to canary 8 --- package.json | 2 +- yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 8ec874b16306d..e6cc9c03842ad 100644 --- a/package.json +++ b/package.json @@ -99,7 +99,7 @@ "@elastic/apm-rum-react": "^1.2.5", "@elastic/charts": "29.0.0", "@elastic/datemath": "link:bazel-bin/packages/elastic-datemath/npm_module", - "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.7", + "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.8", "@elastic/ems-client": "7.13.0", "@elastic/eui": "32.1.0", "@elastic/filesaver": "1.1.2", diff --git a/yarn.lock b/yarn.lock index 76b10c948282c..ef9a7c4494151 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1389,10 +1389,10 @@ version "0.0.0" uid "" -"@elastic/elasticsearch@npm:@elastic/elasticsearch-canary@^8.0.0-canary.7": - version "8.0.0-canary.7" - resolved "https://registry.yarnpkg.com/@elastic/elasticsearch-canary/-/elasticsearch-canary-8.0.0-canary.7.tgz#e4870cd9ec225e3975d950d1a6f42599cfbed35f" - integrity sha512-ZLP8tt0H13N3YUyajDDpKFAxr9zjzbEIBaiY8XImDrg0+qimG+x6SgeONFAsKOJvyQ08WRSreM4Pn3Qt+tCjZA== +"@elastic/elasticsearch@npm:@elastic/elasticsearch-canary@^8.0.0-canary.8": + version "8.0.0-canary.8" + resolved "https://registry.yarnpkg.com/@elastic/elasticsearch-canary/-/elasticsearch-canary-8.0.0-canary.8.tgz#6ed40a18bc13a8bd699d4a40434a4a9bd3abd8b6" + integrity sha512-1gF6MlWNfgF/38cspuehDN5lF1nOVm9NhN6rAKNdcwNLsCBWtXQei9/sOzGCciCCl6n1qPpmImVWm/gcAulqWw== dependencies: debug "^4.3.1" hpagent "^0.1.1" From 10fc71684c5a03f5e905818e86df4d4f25db386e Mon Sep 17 00:00:00 2001 From: restrry Date: Fri, 14 May 2021 11:17:09 +0200 Subject: [PATCH 16/86] bump to v9 --- package.json | 2 +- yarn.lock | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 6bec2fffa780d..7a0b8b038efb7 100644 --- a/package.json +++ b/package.json @@ -100,7 +100,7 @@ "@elastic/apm-rum-react": "^1.2.5", "@elastic/charts": "29.1.0", "@elastic/datemath": "link:bazel-bin/packages/elastic-datemath/npm_module", - "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.8", + "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.9", "@elastic/ems-client": "7.13.0", "@elastic/eui": "32.1.0", "@elastic/filesaver": "1.1.2", diff --git a/yarn.lock b/yarn.lock index 4857c7c908293..8524fe1b89027 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1410,10 +1410,10 @@ 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.9": + version "8.0.0-canary.9" + resolved "https://registry.yarnpkg.com/@elastic/elasticsearch-canary/-/elasticsearch-canary-8.0.0-canary.9.tgz#85b293a448593f7ecc68c6fd35bf5e4eadeb9f56" + integrity sha512-zdemJJTt/P1nJx/ttecHp2yDEBMiC3nA6BA9eQNdoGJN/VbzrlZwv35762719K/VRaeSPJqhHCsNgMURPgXxoA== dependencies: debug "^4.3.1" hpagent "^0.1.1" @@ -2707,6 +2707,9 @@ uid "" "@kbn/securitysolution-es-utils@link:bazel-bin/packages/kbn-securitysolution-es-utils/npm_module": + version "0.0.0" + uid "" + "@kbn/securitysolution-io-ts-alerting-types@link:bazel-bin/packages/kbn-securitysolution-io-ts-alerting-types/npm_module": version "0.0.0" uid "" From 5b2f816c798a1dfd199839f30cae2aecad2834dd Mon Sep 17 00:00:00 2001 From: restrry Date: Fri, 14 May 2021 11:31:46 +0200 Subject: [PATCH 17/86] use new typings --- packages/kbn-es-archiver/src/lib/indices/create_index_stream.ts | 2 +- packages/kbn-es-archiver/src/lib/indices/kibana_index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 b45a8b18a5776..fba3df24e896f 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/kibana_index.ts b/packages/kbn-es-archiver/src/lib/indices/kibana_index.ts index 51d4f28d20f2e..0712d2789a91a 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, From 7d66a3d9824a049b59d482bd1fd23729733993e3 Mon Sep 17 00:00:00 2001 From: restrry Date: Fri, 14 May 2021 11:32:11 +0200 Subject: [PATCH 18/86] fix new errors in core --- .../saved_objects/migrationsv2/actions/index.ts | 8 ++++---- .../migrationsv2/integration_tests/actions.test.ts | 8 ++++---- .../migrationsv2/integration_tests/migration.test.ts | 5 ++++- .../server/saved_objects/service/lib/repository.ts | 12 ++++-------- 4 files changed, 16 insertions(+), 17 deletions(-) diff --git a/src/core/server/saved_objects/migrationsv2/actions/index.ts b/src/core/server/saved_objects/migrationsv2/actions/index.ts index cdca2c701c47c..9ba94c46cbf41 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/index.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/index.ts @@ -162,7 +162,7 @@ export const removeWriteBlock = ( // Don't change any existing settings preserve_existing: true, body: { - index: { + settings: { blocks: { write: false, }, @@ -464,7 +464,7 @@ export interface ReadWithPit { export const readWithPit = ( client: ElasticsearchClient, pitId: string, - query: estypes.QueryContainer, + query: estypes.QueryDslQueryContainer, batchSize: number, searchAfter?: number[], seqNoPrimaryTerm?: boolean @@ -584,7 +584,7 @@ export const reindex = ( * 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 ): TaskEither.TaskEither => () => { return client .reindex({ @@ -1002,7 +1002,7 @@ export interface SearchResponse { interface SearchForOutdatedDocumentsOptions { batchSize: number; targetIndex: string; - outdatedDocumentsQuery?: estypes.QueryContainer; + outdatedDocumentsQuery?: estypes.QueryDslQueryContainer; } /** diff --git a/src/core/server/saved_objects/migrationsv2/integration_tests/actions.test.ts b/src/core/server/saved_objects/migrationsv2/integration_tests/actions.test.ts index d0158a4c68f24..a31769c4a6db1 100644 --- a/src/core/server/saved_objects/migrationsv2/integration_tests/actions.test.ts +++ b/src/core/server/saved_objects/migrationsv2/integration_tests/actions.test.ts @@ -243,7 +243,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' } } }, + index: { settings: { routing: { allocation: { enable: 'none' } } } }, }, }, }, @@ -260,7 +260,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' } } }, }, }); @@ -326,7 +326,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; @@ -1320,7 +1320,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; 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 37dfe9bc717d0..2890274ce857b 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 @@ -155,7 +155,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/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts index 67a398e9f190f..9dca600a1cb95 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -889,7 +889,7 @@ export class SavedObjectsRepository { per_page: perPage, total: body.hits.total, saved_objects: body.hits.hits.map( - (hit: estypes.Hit): SavedObjectsFindResult => ({ + (hit: estypes.SearchTypesHit): SavedObjectsFindResult => ({ // @ts-expect-error @elastic/elasticsearch declared Id as string | number ...this._rawToSavedObject(hit), score: hit._score!, @@ -1940,13 +1940,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(); } From 1bcdc62719bf42c8b580af77f921b7dfd00c4e11 Mon Sep 17 00:00:00 2001 From: restrry Date: Tue, 18 May 2021 11:55:31 +0200 Subject: [PATCH 19/86] fix errors in core typeings --- .../version_check/ensure_es_version.ts | 2 +- .../server/saved_objects/mappings/types.ts | 2 +- .../migrations/core/elastic_index.test.ts | 6 ++--- .../migrations/core/elastic_index.ts | 2 +- .../migrations/core/index_migrator.test.ts | 2 +- .../migrations/kibana/kibana_migrator.test.ts | 2 +- .../migrationsv2/actions/index.ts | 4 +-- .../integration_tests/migration.test.ts | 5 +++- .../saved_objects/migrationsv2/types.ts | 6 ++--- .../lib/aggregations/validation.test.ts | 6 +++-- .../service/lib/aggregations/validation.ts | 25 +++++++++---------- .../service/lib/search_dsl/search_dsl.ts | 2 +- .../service/lib/search_dsl/sorting_params.ts | 4 +-- .../service/lib/update_objects_spaces.ts | 6 ++--- src/core/server/saved_objects/types.ts | 4 +-- 15 files changed, 41 insertions(+), 37 deletions(-) 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 43cd52f1b5721..e1f18f8ad836a 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/saved_objects/mappings/types.ts b/src/core/server/saved_objects/mappings/types.ts index e50b8ea8b99aa..da9a41ab03080 100644 --- a/src/core/server/saved_objects/mappings/types.ts +++ b/src/core/server/saved_objects/mappings/types.ts @@ -121,7 +121,7 @@ export interface IndexMappingMeta { * * @public */ -export type SavedObjectsCoreFieldMapping = estypes.Property & { +export type SavedObjectsCoreFieldMapping = estypes.MappingProperty & { /** * The dynamic property of the mapping, either `false` or `'strict'`. If * unspecified `dynamic: 'strict'` will be inherited from the top-level 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 c32f7483abf66..fbcbb9213e662 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 @@ -43,7 +43,7 @@ describe('ElasticIndex', () => { 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.TaskGetTaskResponse) ); const info = { @@ -248,7 +248,7 @@ describe('ElasticIndex', () => { reason: 'all shards failed', failed_shards: [], }, - } as estypes.GetTaskResponse) + } as estypes.TaskGetTaskResponse) ); 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 f0f45b45b73f6..55d61c80fb7f0 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 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 fcc03f363139b..401f404e670d6 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.TaskGetTaskResponse) ); client.search.mockReturnValue( elasticsearchClientMock.createSuccessTransportRequestPromise(searchResult(0) as any) 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 2fae14ba96b7b..94e3a7dbcf025 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 @@ -337,7 +337,7 @@ const mockV2MigrationOptions = () => { error: undefined, failures: [], task: { description: 'task description' } as any, - } as estypes.GetTaskResponse) + } as estypes.TaskGetTaskResponse) ); options.client.search = jest diff --git a/src/core/server/saved_objects/migrationsv2/actions/index.ts b/src/core/server/saved_objects/migrationsv2/actions/index.ts index 9ba94c46cbf41..201cfb1fec059 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/index.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/index.ts @@ -828,8 +828,8 @@ export interface AcknowledgeResponse { shardsAcknowledged: boolean; } -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/integration_tests/migration.test.ts b/src/core/server/saved_objects/migrationsv2/integration_tests/migration.test.ts index 2890274ce857b..f265302bfdeba 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 @@ -216,7 +216,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/types.ts b/src/core/server/saved_objects/migrationsv2/types.ts index adcd2ad32fd24..1151e8337d3d5 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/service/lib/aggregations/validation.test.ts b/src/core/server/saved_objects/service/lib/aggregations/validation.test.ts index 9ed1d3d1608ae..53f1b5c9d78c5 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: { 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 cd41a23f4a28b..5ef89f297a796 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/search_dsl/search_dsl.ts b/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts index 64b3dd428fb8b..97d8aac929bab 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.SearchTypesSortOrder; namespaces?: string[]; pit?: SavedObjectsPitParams; typeToNamespacesMap?: Map; 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 64849c308f3f0..9b9b2d9ed59f5 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.SearchTypesSortOrder +): { sort?: estypes.SearchTypesSortContainer[] } { 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 079549265385c..33073650f71f8 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.BulkBulkOperationContainer[] = []; 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 d3bfdcc6923dc..594c1a8c84f30 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.SearchTypesSortOrder; /** * 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 From 67d12d5bb56bd9047f551831c9d6d2cc1487441d Mon Sep 17 00:00:00 2001 From: restrry Date: Tue, 18 May 2021 14:51:51 +0200 Subject: [PATCH 20/86] fix type errors in data plugin --- src/plugins/data/common/es_query/filters/phrase_filter.ts | 4 ++-- src/plugins/data/common/es_query/filters/range_filter.ts | 4 ++-- .../index_patterns/fields/index_pattern_field.test.ts | 2 +- src/plugins/data/common/index_patterns/fields/types.ts | 4 ++-- src/plugins/data/common/index_patterns/types.ts | 6 +++--- src/plugins/data/common/search/search_source/types.ts | 4 ++-- .../providers/kql_query_suggestion/field.test.ts | 1 + .../data/public/search/errors/painless_error.test.tsx | 1 + src/plugins/data/public/search/errors/types.ts | 4 ++-- .../search/search_interceptor/search_interceptor.test.ts | 1 + .../public/ui/shard_failure_modal/shard_failure_types.ts | 4 ++-- .../data/server/autocomplete/value_suggestions_route.ts | 2 +- .../fetcher/lib/field_capabilities/field_caps_response.ts | 2 +- .../search/strategies/ese_search/ese_search_strategy.ts | 2 +- 14 files changed, 22 insertions(+), 19 deletions(-) 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 2a7f2458a27de..85562435e68d0 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 fb8426655583e..a082b93c0a79a 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/index_pattern_field.test.ts b/src/plugins/data/common/index_patterns/fields/index_pattern_field.test.ts index 48342a9e02a2b..e45a5d162dcf2 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: 'painless' 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 565dd6d926948..0fb7a46c2cf73 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 0fcdea1a878eb..07aa8967b905e 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/search_source/types.ts b/src/plugins/data/common/search/search_source/types.ts index 507fda0dc9e47..40e92f45af143 100644 --- a/src/plugins/data/common/search/search_source/types.ts +++ b/src/plugins/data/common/search/search_source/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 { NameList } from 'elasticsearch'; import { IAggConfigs } from 'src/plugins/data/public'; import { Query } from '../..'; @@ -156,7 +156,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/public/autocomplete/providers/kql_query_suggestion/field.test.ts b/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/field.test.ts index f1eced06a33ea..84ed4315ee16f 100644 --- a/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/field.test.ts +++ b/src/plugins/data/public/autocomplete/providers/kql_query_suggestion/field.test.ts @@ -41,6 +41,7 @@ describe('Kuery field suggestions', () => { 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/search/errors/painless_error.test.tsx b/src/plugins/data/public/search/errors/painless_error.test.tsx index f07f078ea03a3..833573786594b 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 445293fe47ea3..13c5d0c242ed0 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 dfbc912453d6e..fe66d4b6e9937 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 c34a47dc1c6dd..83e4abf55d525 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 f0487b93b8ee5..4604e20fef4c1 100644 --- a/src/plugins/data/server/autocomplete/value_suggestions_route.ts +++ b/src/plugins/data/server/autocomplete/value_suggestions_route.ts @@ -80,7 +80,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 c4c1ffa3cf9f9..6db9254b81528 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/strategies/ese_search/ese_search_strategy.ts b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts index cec4b9a2dbf9f..ad6105d71dcae 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 @@ -169,7 +169,7 @@ export const enhancedEsSearchStrategyProvider = ( extend: async (id, keepAlive, options, { esClient }) => { logger.debug(`extend ${id} by ${keepAlive}`); try { - await esClient.asCurrentUser.asyncSearch.get({ id, body: { keep_alive: keepAlive } }); + await esClient.asCurrentUser.asyncSearch.get({ id, keep_alive: keepAlive }); } catch (e) { throw getKbnServerError(e); } From e7774367fbb693b5443874f62651a44637aa50f3 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 14:53:08 +0200 Subject: [PATCH 21/86] fix type errors in telemetray plugin --- .../server/telemetry_collection/get_local_stats.test.ts | 4 ++-- .../telemetry/server/telemetry_collection/get_local_stats.ts | 2 +- .../telemetry/server/telemetry_collection/get_nodes_usage.ts | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) 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 7fd6ca4080d6a..bacfa5e77107f 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 7fdcb50b704af..7860949e098aa 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 c35b8a3d24498..f9e55b3bf4028 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.NodesNodesUsageNodeUsage { /** * The Node ID as reported by ES */ @@ -31,7 +31,7 @@ export type NodesUsageGetter = (esClient: ElasticsearchClient) => Promise<{ node */ export async function fetchNodesUsage( esClient: ElasticsearchClient -): Promise { +): Promise { const { body } = await esClient.nodes.usage({ timeout: TIMEOUT, }); From 9e7cdc562217711e57217c1117082b0deacc2101 Mon Sep 17 00:00:00 2001 From: restrry Date: Tue, 18 May 2021 14:58:38 +0200 Subject: [PATCH 22/86] fix data plugin tests --- .../fields/__snapshots__/index_pattern_field.test.ts.snap | 4 ++-- .../common/index_patterns/fields/index_pattern_field.test.ts | 2 +- src/plugins/data/server/search/routes/msearch.test.ts | 2 +- .../search/strategies/ese_search/ese_search_strategy.test.ts | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) 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 6b1d01e5ba142..681aba41a609c 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 e45a5d162dcf2..73f015ca5517c 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: 'painless' as const, + 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/server/search/routes/msearch.test.ts b/src/plugins/data/server/search/routes/msearch.test.ts index 6ae8612cceb1e..303f83582f737 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/ese_search/ese_search_strategy.test.ts b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.test.ts index 216318339622f..56b26a7ebe02c 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 () => { From c90d623c9d862d075ced8421435e60e491b4569d Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 14:59:10 +0200 Subject: [PATCH 23/86] fix search examples type error --- examples/search_examples/public/search_sessions/app.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/search_examples/public/search_sessions/app.tsx b/examples/search_examples/public/search_sessions/app.tsx index a768600db24ee..7fdf91537c977 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( From c6e56de6a9d76ae0ae715e77e76e4b34fe593e66 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:00:29 +0200 Subject: [PATCH 24/86] fix errors in discover plugin --- .../application/angular/doc_table/create_doc_table_react.tsx | 2 +- .../public/application/components/doc/use_es_doc_search.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 b8e8bf1fe7d6c..162c72db700a3 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.SearchTypesHit[]; 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 6b8e912bbffba..7a3320d43c8b5 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: { From ea14ba11645b8d36dbf7c3655ba62ad7d201e646 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:01:05 +0200 Subject: [PATCH 25/86] fix errors in index_pattern_management --- .../confirmation_modal/confirmation_modal.test.tsx | 1 + .../components/table/table.test.tsx | 1 + .../scripted_field_table.test.tsx | 2 ++ .../scripted_fields_table/scripted_fields_table.tsx | 2 +- .../scripted_fields_table/types.ts | 4 ++-- .../public/components/field_editor/field_editor.tsx | 13 +++++++------ .../public/scripting_languages/index.ts | 6 +++--- 7 files changed, 17 insertions(+), 12 deletions(-) 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 96f78a088fff4..bacab18d28509 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 83ac96f6c1695..5a9f4eb871181 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 08a5f22723628..e6aa87172ca0b 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 77ba2f734d3fe..7fd5170b669f7 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 3348f5eb052eb..5c6adc824d225 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 f0da57a5f9b6f..b05ddaed064cd 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 c6b2f3c4b6b27..aeb38c8172be0 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 []; } From 41a2a37c1ceb2f6ef1a81a8eeee9fbdc9a4e36c5 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:02:00 +0200 Subject: [PATCH 26/86] fix type errors in vis_type_* --- src/plugins/vis_type_timeseries/common/fields_utils.test.ts | 2 +- src/plugins/vis_type_vega/public/data_model/types.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 9550697e22851..f056c38b0c0c3 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 8590b51d3b5ff..bca85194f09ae 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; } From d4d3bd7487db77dcbf82a50ae2005a7d541f9127 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:02:25 +0200 Subject: [PATCH 27/86] fix errors in typings/elasticsearch --- typings/elasticsearch/index.d.ts | 4 ++-- typings/elasticsearch/search.d.ts | 22 ++++++++++++++-------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/typings/elasticsearch/index.d.ts b/typings/elasticsearch/index.d.ts index 7eaf762d353ac..1951434890c50 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 d75f31d388176..de7683c29b154 100644 --- a/typings/elasticsearch/search.d.ts +++ b/typings/elasticsearch/search.d.ts @@ -28,7 +28,7 @@ type KeysOfSources = T extends [infer U, ...infer V] : {}; type CompositeKeysOf< - TAggregationContainer extends estypes.AggregationContainer + TAggregationContainer extends estypes.AggregationsAggregationContainer > = TAggregationContainer extends { composite: { sources: [...infer TSource] }; } @@ -56,7 +56,7 @@ 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: { @@ -520,7 +526,7 @@ export type AggregateOf< max_score: number | null; hits: TAggregationContainer extends { top_hits: estypes.TopHitsAggregation } ? HitsOf - : estypes.HitsMetadata; + : estypes.SearchTypesHitsMetadata; }; }; 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 { ... } | {} }; From dc45dc4c7742d7d96b1a9d767f86f22291c36534 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:03:07 +0200 Subject: [PATCH 28/86] fix type errors in actions plugin --- x-pack/plugins/actions/server/actions_client.ts | 2 +- .../lib/extract_bulk_response_delete_failures.ts | 4 +++- .../create_alert_history_index_template.ts | 1 + x-pack/plugins/actions/server/saved_objects/index.ts | 3 ++- 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/x-pack/plugins/actions/server/actions_client.ts b/x-pack/plugins/actions/server/actions_client.ts index c655141415b54..449d218ed5ae0 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/cleanup_failed_executions/lib/extract_bulk_response_delete_failures.ts b/x-pack/plugins/actions/server/cleanup_failed_executions/lib/extract_bulk_response_delete_failures.ts index 90418c9763a4d..01ca44e156254 100644 --- a/x-pack/plugins/actions/server/cleanup_failed_executions/lib/extract_bulk_response_delete_failures.ts +++ b/x-pack/plugins/actions/server/cleanup_failed_executions/lib/extract_bulk_response_delete_failures.ts @@ -7,7 +7,9 @@ import { ApiResponse, estypes } from '@elastic/elasticsearch'; -type ResponseFailures = Array>; +type ResponseFailures = Array< + Pick +>; export function extractBulkResponseDeleteFailures( response: ApiResponse 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 fe9874fb1d671..28b904361e677 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 fbbff02fae443..9d8c364007959 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'; From 604105584cde34b009d8e96322bbfaff4aa1822e Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:04:20 +0200 Subject: [PATCH 29/86] fix type errors in alerting and apm plugins --- .../plugins/alerting/server/alerts_client/alerts_client.ts | 2 +- x-pack/plugins/alerting/server/saved_objects/index.ts | 1 + .../apm/scripts/create-functional-tests-archive/index.ts | 4 ++-- .../lib/alerts/chart_preview/get_transaction_duration.ts | 4 ++-- .../lib/alerts/register_transaction_duration_alert_type.ts | 4 ++-- .../register_transaction_duration_anomaly_alert_type.ts | 4 ++-- .../apm/server/lib/service_map/get_service_anomalies.ts | 2 +- .../server/lib/settings/custom_link/list_custom_links.ts | 4 ++-- x-pack/plugins/apm/server/lib/traces/get_trace_items.ts | 4 ++-- .../lib/transaction_groups/get_transaction_group_stats.ts | 5 ++++- .../lib/transactions/distribution/get_buckets/index.ts | 6 +++--- .../apm/server/lib/transactions/get_anomaly_data/fetcher.ts | 4 ++-- x-pack/plugins/apm/server/projections/metrics.ts | 4 ++-- x-pack/plugins/apm/server/projections/transactions.ts | 4 ++-- x-pack/plugins/apm/server/projections/typings.ts | 2 +- x-pack/plugins/apm/server/utils/queries.ts | 6 ++++-- 16 files changed, 33 insertions(+), 27 deletions(-) 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 21eff9d796235..f85e8678f9bf4 100644 --- a/x-pack/plugins/alerting/server/alerts_client/alerts_client.ts +++ b/x-pack/plugins/alerting/server/alerts_client/alerts_client.ts @@ -102,7 +102,7 @@ export interface FindOptions extends IndexType { defaultSearchOperator?: 'AND' | 'OR'; searchFields?: string[]; sortField?: string; - sortOrder?: estypes.SortOrder; + sortOrder?: estypes.SearchTypesSortOrder; 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 6b76fd97dc53b..a91aba926dbef 100644 --- a/x-pack/plugins/alerting/server/saved_objects/index.ts +++ b/x-pack/plugins/alerting/server/saved_objects/index.ts @@ -48,6 +48,7 @@ export function setupSavedObjects( hidden: true, namespaceType: 'single', migrations: getMigrations(encryptedSavedObjects), + // @ts-expect-error mappings is not properly types json mappings: mappings.alert, management: { importableAndExportable: true, 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 7f62fd3998060..18cb641bd4e65 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 508b9419344cd..091982598d6a3 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 f77cc3ee930b1..3e870eb3e32c6 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 399fb9a216ef5..4cc2324f47b9d 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/service_map/get_service_anomalies.ts b/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts index bcddbff34a8f6..4acff0acbfa3a 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: { 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 f6b41f462c99f..0eac2e08d0901 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 a946fa66a3b92..157f09978eaec 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 86be82faee578..8156d52d984df 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 1a586d1d4dbb6..3b4319c37996d 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 8b068fd6bd2fb..b105f3b5c0a30 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 68056f091c873..9a757893337e5 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 dd16b0b910abf..3e830403debb0 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 bb90aa0bf5eb4..60a3317af1864 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 7255e7ed75a63..f21ef9de0283f 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 []; } From e5866ce303c35a107f88a0bcd976053d7adcd8d7 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:05:02 +0200 Subject: [PATCH 30/86] fix type errors in canvas and cases --- x-pack/plugins/canvas/types/strategy.ts | 4 ++-- x-pack/plugins/cases/server/services/index.ts | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/x-pack/plugins/canvas/types/strategy.ts b/x-pack/plugins/canvas/types/strategy.ts index 1c94059f0c9ca..cd827cb191c69 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/index.ts b/x-pack/plugins/cases/server/services/index.ts index 11b8cef6ab5a5..b791aac111923 100644 --- a/x-pack/plugins/cases/server/services/index.ts +++ b/x-pack/plugins/cases/server/services/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { AggregationContainer } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { KibanaRequest, Logger, @@ -907,7 +907,9 @@ export class CaseService implements CaseServiceSetup { } } - private buildCaseIdsAggs = (size: number = 100): Record => ({ + private buildCaseIdsAggs = ( + size: number = 100 + ): Record => ({ references: { nested: { path: `${CASE_COMMENT_SAVED_OBJECT}.references`, From 9e83b4c969abe0e856c931c316cf0987014dbbba Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:05:23 +0200 Subject: [PATCH 31/86] fix errors in event_log --- x-pack/plugins/event_log/server/es/cluster_client_adapter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 dd6ac6350d6e3..e42e24e4b47d4 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 Date: Tue, 18 May 2021 15:05:54 +0200 Subject: [PATCH 32/86] fix type errors in ILM and ingest_pipelines --- .../server/routes/api/index/register_add_policy_route.ts | 1 - .../routes/api/templates/register_add_policy_route.ts | 1 + .../ingest_pipelines/common/lib/pipeline_serialization.ts | 6 ++++-- .../plugins/ingest_pipelines/server/routes/api/simulate.ts | 4 ++-- 4 files changed, 7 insertions(+), 5 deletions(-) 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 77f14decc5642..a18459d5d21b9 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 4d467a807109a..823b36e63a873 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/ingest_pipelines/common/lib/pipeline_serialization.ts b/x-pack/plugins/ingest_pipelines/common/lib/pipeline_serialization.ts index 5360e2713aee1..d2669e7c0012b 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 a1d0a4ec2e3d3..0f107f38b251d 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'; @@ -39,7 +39,7 @@ export const registerSimulateRoute = ({ verbose, body: { pipeline, - docs: documents as SimulatePipelineDocument[], + docs: documents as estypes.IngestSimulatePipelineSimulatePipelineDocument[], }, }); From 3ed8434fe9d4a9a8eba289da4bb6f6b8db5c9640 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:06:26 +0200 Subject: [PATCH 33/86] fix errors in lens plugin --- .../lens/public/indexpattern_datasource/mocks.ts | 6 +++--- .../lens/server/routes/existing_fields.test.ts | 2 +- x-pack/plugins/lens/server/routes/existing_fields.ts | 6 +++--- x-pack/plugins/lens/server/routes/field_stats.ts | 12 +++++++----- 4 files changed, 14 insertions(+), 12 deletions(-) diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/mocks.ts b/x-pack/plugins/lens/public/indexpattern_datasource/mocks.ts index e71b26b9d4cd9..4545e42b2ff99 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 57d8ebf678d61..66fb13c18ce8e 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.SearchTypesHit _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 358756d38173f..2d1ef9084610d 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; } @@ -203,7 +203,7 @@ async function fetchIndexPatternStats({ if (!field.runtimeField) return acc; acc[field.name] = field.runtimeField; return acc; - }, {} as Record), + }, {} as Record), script_fields: scriptedFields.reduce((acc, field) => { acc[field.name] = { script: { @@ -232,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.SearchTypesHit[], 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 038f940c29e6c..b60840ea39c98 100644 --- a/x-pack/plugins/lens/server/routes/field_stats.ts +++ b/x-pack/plugins/lens/server/routes/field_stats.ts @@ -78,7 +78,7 @@ 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, @@ -134,7 +134,9 @@ export async function initFieldsRoute(setup: CoreSetup) { } export async function getNumberHistogram( - aggSearchWithBody: (aggs: Record) => Promise, + aggSearchWithBody: ( + aggs: Record + ) => Promise, field: IFieldType, useTopHits = true ): Promise { @@ -243,7 +245,7 @@ export async function getNumberHistogram( } export async function getStringSamples( - aggSearchWithBody: (aggs: Record) => unknown, + aggSearchWithBody: (aggs: Record) => unknown, field: IFieldType ): Promise { const fieldRef = getFieldRef(field); @@ -282,7 +284,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 { @@ -329,7 +331,7 @@ function getFieldRef(field: IFieldType) { return field.scripted ? { script: { - lang: field.lang as string, + lang: field.lang!, source: field.script as string, }, } From 5ba2bbd52464f752c5e5de1fc832131c3bd9d908 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:07:04 +0200 Subject: [PATCH 34/86] fix errors in lists plugin --- x-pack/plugins/lists/server/services/items/find_list_item.ts | 4 ++-- x-pack/plugins/lists/server/services/lists/find_list.ts | 4 ++-- .../lists/server/services/utils/get_search_after_scroll.ts | 2 +- .../server/services/utils/transform_elastic_to_list_item.ts | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) 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 e1586daf1cbb1..12bd47901ab33 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 92d7262c19543..202a65773ce66 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 ae37e47861845..914fc876b8161 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 @@ -42,7 +42,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/transform_elastic_to_list_item.ts b/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts index 1cbf72e8eb653..076b7658ddd81 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 @@ -21,7 +21,7 @@ export interface TransformElasticToListItemOptions { } export interface TransformElasticHitToListItemOptions { - hits: Array>; + hits: Array>; type: Type; } From 50941bd96bf5c9776b613cffdf1c7044c987550e Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:07:25 +0200 Subject: [PATCH 35/86] fix errors in logstash --- x-pack/plugins/logstash/server/models/cluster/cluster.test.ts | 2 +- x-pack/plugins/logstash/server/models/cluster/cluster.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 1e1afc33394f3..10c1d1ba24ae0 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 88789a2d29c89..2982284879c47 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 }); } From c9c7b322b6e978ed9d1cc119db46478b0c427345 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:08:08 +0200 Subject: [PATCH 36/86] fix errors in metrics_entities --- .../plugins/metrics_entities/server/routes/post_transforms.ts | 4 ++-- .../metrics_entities/server/services/install_transforms.ts | 2 +- .../server/services/metrics_entities_client_types.ts | 2 +- .../metrics_entities/server/services/post_transforms.ts | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) 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 d5b5648757e8b..f5a46ec04611d 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 d0a81955ca184..eec4f8d555356 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 1ae9f0d7a2f53..def26c5342ef9 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 1850047ae1e9d..f14f53d78f10e 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; From 4deea477afc8e9a04a5d80dc924072c21857ba9c Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:08:27 +0200 Subject: [PATCH 37/86] fix errors in o11y --- .../lib/annotations/create_annotations_client.ts | 1 - .../server/utils/create_or_update_index.ts | 10 +++++----- x-pack/plugins/observability/server/utils/queries.ts | 10 +++++++--- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/x-pack/plugins/observability/server/lib/annotations/create_annotations_client.ts b/x-pack/plugins/observability/server/lib/annotations/create_annotations_client.ts index ad94467a88ed0..39a594dcc86ca 100644 --- a/x-pack/plugins/observability/server/lib/annotations/create_annotations_client.ts +++ b/x-pack/plugins/observability/server/lib/annotations/create_annotations_client.ts @@ -34,7 +34,6 @@ export function createAnnotationsClient(params: { const initIndex = () => createOrUpdateIndex({ index, - // @ts-expect-error @elastic-elasticsearch types don't support nested properties mappings, client: esClient, logger, 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 19b14ef8b2437..7451314ad248c 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 9e1c110e77587..1eca0f37c95e5 100644 --- a/x-pack/plugins/observability/server/utils/queries.ts +++ b/x-pack/plugins/observability/server/utils/queries.ts @@ -5,10 +5,14 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { estypes } from '@elastic/elasticsearch'; import { esKuery } from '../../../../../src/plugins/data/server'; -export function rangeQuery(start?: number, end?: number, field = '@timestamp'): QueryContainer[] { +export function rangeQuery( + start?: number, + end?: number, + field = '@timestamp' +): estypes.QueryDslQueryContainer[] { return [ { range: { @@ -22,7 +26,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 []; } From a02b37c6a3d1aa1c5491c86e2107110f4f39758e Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:08:55 +0200 Subject: [PATCH 38/86] fix errors in watcher --- .../lib/fetch_all_from_scroll/fetch_all_from_scroll.ts | 10 +++++----- .../server/routes/api/indices/register_get_route.ts | 6 ++++-- .../server/routes/api/watches/register_delete_route.ts | 7 +++++-- 3 files changed, 14 insertions(+), 9 deletions(-) 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 f686d978ec710..287f900c955d8 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.SearchTypesHit[] = [] +): 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 915871185af85..f69ee60f9cd73 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 e47d451c227e5..b7c09361774ab 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) => { From 4f4f4353a335a7fb5ded51f601b1002b9a40d4ab Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:09:27 +0200 Subject: [PATCH 39/86] fix errors in uptime --- .../uptime/server/lib/requests/get_journey_details.ts | 6 +++--- .../uptime/server/lib/requests/get_journey_failed_steps.ts | 4 ++-- .../uptime/server/lib/requests/get_journey_screenshot.ts | 4 ++-- .../plugins/uptime/server/lib/requests/get_journey_steps.ts | 4 ++-- .../uptime/server/lib/requests/get_latest_monitor.ts | 4 ++-- .../uptime/server/lib/requests/get_monitor_duration.ts | 4 ++-- .../uptime/server/lib/requests/get_monitor_status.ts | 4 ++-- .../uptime/server/lib/requests/get_network_events.ts | 4 ++-- x-pack/plugins/uptime/server/lib/requests/get_pings.ts | 4 ++-- 9 files changed, 19 insertions(+), 19 deletions(-) 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 560653950c6f8..6081cc3a7b7c8 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 5c4e263468947..d14a723d27628 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, }, }, From 3ec7ea41fd8a7811c2e20213d8bc651743bfb09b Mon Sep 17 00:00:00 2001 From: restrry Date: Tue, 18 May 2021 15:12:16 +0200 Subject: [PATCH 40/86] fix errors in upgrade_assistant --- .../server/lib/reindexing/index_settings.test.ts | 4 ++++ .../server/lib/reindexing/index_settings.ts | 8 ++++++++ .../server/lib/reindexing/reindex_service.test.ts | 4 ++-- .../server/lib/reindexing/reindex_service.ts | 4 ++-- .../server/lib/reindexing/types.ts | 13 +++++-------- .../server/routes/update_index_settings.ts | 2 +- 6 files changed, 22 insertions(+), 13 deletions(-) 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 5e994f76f927c..30093a9fb6e50 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 5ee067f3640f3..0fb531b286854 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 ae0a6f97e29d5..7a5bf1c187698 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 b9d5b42a65250..1bf45e3a4a038 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 569316e276e43..ddff137772ae8 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 4bdf3c7f56cac..b90ff4281644b 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, }, }); From 498a5a96d5d08f25387812df462e6d7419d714ba Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:12:50 +0200 Subject: [PATCH 41/86] fix errors in task_manager --- .../monitoring/workload_statistics.test.ts | 6 ++--- .../server/monitoring/workload_statistics.ts | 10 ++++----- .../mark_available_tasks_as_claimed.ts | 6 ++--- .../server/queries/query_clauses.ts | 22 +++++++++---------- .../task_manager/server/task_store.test.ts | 2 +- .../plugins/task_manager/server/task_store.ts | 8 +++---- 6 files changed, 27 insertions(+), 27 deletions(-) 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 a4913fca19ee8..daeb0c19e4b8d 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.SearchTypesTotalHitsRelation, }, }, 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 dd7484af20726..e251ce07679ff 100644 --- a/x-pack/plugins/task_manager/server/monitoring/workload_statistics.ts +++ b/x-pack/plugins/task_manager/server/monitoring/workload_statistics.ts @@ -352,7 +352,7 @@ export function summarizeWorkloadStat( } function hasAggregations( - aggregations?: Record + aggregations?: Record ): aggregations is WorkloadAggregationResponse { return !!( aggregations?.taskType && @@ -365,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; @@ -383,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; @@ -408,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 2437e893abf37..6d5a674a8fa9c 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.SearchTypesSort >; 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 97c41295eece3..5f7cc8ed2bdb3 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/task_store.test.ts b/x-pack/plugins/task_manager/server/task_store.test.ts index a44bddcdb8201..f04d38320ab78 100644 --- a/x-pack/plugins/task_manager/server/task_store.test.ts +++ b/x-pack/plugins/task_manager/server/task_store.test.ts @@ -205,7 +205,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 0eeccd0af75f7..69a9068488940 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.SearchTypesSort; + query?: estypes.QueryDslQueryContainer; seq_no_primary_term?: boolean; } export interface AggregationOpts { - aggs: Record; - query?: estypes.QueryContainer; + aggs: Record; + query?: estypes.QueryDslQueryContainer; size?: number; } From e66294b8ab598be4dff1c5ef8e33e6ee531a249b Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:13:24 +0200 Subject: [PATCH 42/86] fix errors in stack_alerts --- x-pack/plugins/stack_alerts/common/build_sorted_events_query.ts | 2 +- .../stack_alerts/public/alert_types/es_query/expression.tsx | 2 +- .../stack_alerts/server/alert_types/es_query/action_context.ts | 2 +- .../stack_alerts/server/alert_types/es_query/alert_type.test.ts | 1 + .../stack_alerts/server/alert_types/es_query/alert_type.ts | 2 +- 5 files changed, 5 insertions(+), 4 deletions(-) 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 34851073bd8a2..455307cb73a09 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 f89f1133d0248..3783632e9ad1c 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.SearchTypesHitsMetadata['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 bc5d5c41c5cce..961501a3d0bab 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.SearchTypesHit[]; } export function addMessages( diff --git a/x-pack/plugins/stack_alerts/server/alert_types/es_query/alert_type.test.ts b/x-pack/plugins/stack_alerts/server/alert_types/es_query/alert_type.test.ts index 92f6e731f7114..cf39af8002bcc 100644 --- a/x-pack/plugins/stack_alerts/server/alert_types/es_query/alert_type.test.ts +++ b/x-pack/plugins/stack_alerts/server/alert_types/es_query/alert_type.test.ts @@ -612,6 +612,7 @@ function generateResults( relation: 'eq', }, max_score: 100, + // @ts-expect-error not full interface hits, }, }; 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 ece193e07d776..9cd414ae5254c 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.SearchTypesTotalHits).value; // apply the alert condition const conditionMet = compareFn(numMatches, params.threshold); From 6071ab895cecbe7f22e3dbf6d3f7bb4103721314 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:14:19 +0200 Subject: [PATCH 43/86] fix errors in security_solution --- .../endpoint/data_generators/fleet_agent_generator.ts | 9 ++++++--- .../security_solution/common/endpoint/index_data.ts | 4 ++-- .../security_solution/hosts/details/index.ts | 2 +- .../detection_engine/signals/filters/filter_events.ts | 2 +- .../signals/filters/filter_events_against_list.ts | 6 +++--- .../server/lib/detection_engine/signals/filters/types.ts | 6 +++--- .../lib/detection_engine/signals/single_search_after.ts | 4 ++-- .../signals/threat_mapping/get_threat_list.ts | 4 ++-- .../lib/detection_engine/signals/threat_mapping/types.ts | 2 +- .../server/lib/detection_engine/signals/types.ts | 4 ++-- .../factory/hosts/overview/query.overview_host.dsl.ts | 2 +- .../factory/hosts/uncommon_processes/dsl/query.dsl.ts | 4 ++-- 12 files changed, 26 insertions(+), 23 deletions(-) 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 6e508a099003a..e5872557aa952 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.SearchTypesHit { const hostname = this.randomHostname(); const now = new Date().toISOString(); const osFamily = this.randomOSFamily(); - return merge, DeepPartial>>( + return merge< + estypes.SearchTypesHit, + 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 0dc7891560c2d..43ca54be59c04 100644 --- a/x-pack/plugins/security_solution/common/endpoint/index_data.ts +++ b/x-pack/plugins/security_solution/common/endpoint/index_data.ts @@ -119,7 +119,7 @@ async function indexHostDocs({ const kibanaVersion = await fetchKibanaVersion(kbnClient); let hostMetadata: HostMetadata; let wasAgentEnrolled = false; - let enrolledAgent: undefined | estypes.Hit; + let enrolledAgent: undefined | estypes.SearchTypesHit; for (let j = 0; j < numDocs; j++) { generator.updateHostData(); @@ -368,7 +368,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/security_solution/hosts/details/index.ts b/x-pack/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts index 34b32115a089d..e8578b4c07063 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({ 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 f50f0b521ed76..8c12a48f26b22 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 f653fde816c62..d253979252cf3 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 @@ -21,7 +21,7 @@ export interface FilterEventsAgainstListOptions { } export interface CreateSetToFilterAgainstOptions { - events: Array>; + events: Array>; field: string; listId: string; listType: Type; @@ -31,12 +31,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/single_search_after.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts index 57ed05bcb27cf..ae99b308040e9 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 @@ -23,7 +23,7 @@ import { } from '../../../../common/detection_engine/schemas/common/schemas'; interface SingleSearchAfterParams { - aggregations?: Record; + aggregations?: Record; searchAfterSortIds: SortResults | undefined; index: string[]; from: string; @@ -32,7 +32,7 @@ interface SingleSearchAfterParams { logger: Logger; pageSize: number; sortOrder?: SortOrderOrUndefined; - filter?: estypes.QueryContainer; + filter?: estypes.QueryDslQueryContainer; timestampOverride: TimestampOverrideOrUndefined; buildRuleMessage: BuildRuleMessage; } 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 c3d3d6c6a99e1..3ff23e27547b4 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 82fc0dd3abd0a..b4b2daf542579 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.SearchTypesHit; 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 80d08a77ba5d2..6f4777fe13dbf 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.SearchTypesHit; export type WrappedSignalHit = BaseHit; -export type BaseSignalHit = estypes.Hit; +export type BaseSignalHit = estypes.SearchTypesHit; export type EqlSignalSearchResponse = EqlSearchResponse; 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 897ae633076a2..a0ae368ac0fe2 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 1df0d60d54a88..97f0fc6f2efe0 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 @@ -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[], }, }, { From af3d7a6a76c21944ef43404dfaafe1bf884c61b4 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:14:43 +0200 Subject: [PATCH 44/86] fix errors in rule_registry --- x-pack/plugins/rule_registry/common/mapping_from_field_map.ts | 4 ++-- x-pack/plugins/rule_registry/common/types.ts | 4 ++-- x-pack/plugins/rule_registry/server/rule_data_client/index.ts | 4 ++-- .../rule_registry/server/rule_data_plugin_service/index.ts | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) 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 17eb5ae8967af..74681a6aad4ee 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 299d2c300ab49..858b1a5af431f 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/rule_data_client/index.ts b/x-pack/plugins/rule_registry/server/rule_data_client/index.ts index 135c870f20727..3ab01f36e289f 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,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -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 { @@ -125,7 +125,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; await clusterClient.indices.putMapping({ index: `${alias}*`, body: mappings }); } 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 159e9b8152597..22435ef8c0203 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); } From 4f6a79d407369449518848904e94533ea9b60c43 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:15:14 +0200 Subject: [PATCH 45/86] fix errors in snapshot_restore --- x-pack/plugins/snapshot_restore/server/routes/api/policy.ts | 6 +++--- .../plugins/snapshot_restore/server/routes/api/restore.ts | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) 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 4c4a455f980f8..52e4e7011f0d4 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 }); 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 b7281fee04c53..eb77c5e2d833f 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 }); From 39c5e1cb5cdcef74cc428ea3bcae9484ce2f3eb5 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 18 May 2021 15:15:55 +0200 Subject: [PATCH 46/86] fix remaining errors --- x-pack/plugins/maps/server/mvt/get_tile.ts | 2 +- .../ml/common/types/anomaly_detection_jobs/datafeed.ts | 2 +- x-pack/plugins/ml/common/types/data_frame_analytics.ts | 2 +- x-pack/plugins/ml/common/util/job_utils.ts | 4 ++-- x-pack/plugins/ml/server/lib/query_utils.ts | 2 +- .../plugins/osquery/common/search_strategy/osquery/index.ts | 2 +- x-pack/plugins/reporting/server/lib/store/store.ts | 1 - x-pack/plugins/rollup/server/collectors/helpers.ts | 1 - .../server/routes/authorization/privileges/get_builtin.ts | 5 ++++- .../security/server/session_management/session_index.ts | 1 - .../server/telemetry_collection/get_license.ts | 2 +- .../telemetry_collection/get_stats_with_xpack.test.ts | 2 +- x-pack/plugins/transform/server/routes/api/transforms.ts | 2 +- x-pack/test/case_api_integration/common/lib/utils.ts | 6 +++--- 14 files changed, 17 insertions(+), 17 deletions(-) diff --git a/x-pack/plugins/maps/server/mvt/get_tile.ts b/x-pack/plugins/maps/server/mvt/get_tile.ts index 95b8e043e0ce4..51902e1564429 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.SearchTypesHit documentsResponse.rawResponse.hits.hits, (hit: Record) => { return flattenHit(geometryFieldName, hit); 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 440f4c6e55fb8..ef41e54a5c0d7 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 @@ -13,7 +13,7 @@ export type Datafeed = estypes.Datafeed; export type ChunkingConfig = estypes.ChunkingConfig; -export type Aggregation = Record; +export type Aggregation = Record; // export type IndicesOptions = estypes.IndicesOptions; export interface IndicesOptions { 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 ff5069e7d59ad..3305eeaaf4794 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/util/job_utils.ts b/x-pack/plugins/ml/common/util/job_utils.ts index e7608af553f60..2cb803af38579 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/server/lib/query_utils.ts b/x-pack/plugins/ml/server/lib/query_utils.ts index dd4dc01498dbb..e801130643345 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/osquery/common/search_strategy/osquery/index.ts b/x-pack/plugins/osquery/common/search_strategy/osquery/index.ts index d07af8c878c51..fb3bd92abb4c9 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/reporting/server/lib/store/store.ts b/x-pack/plugins/reporting/server/lib/store/store.ts index 22a667cc01700..19f06a060da7d 100644 --- a/x-pack/plugins/reporting/server/lib/store/store.ts +++ b/x-pack/plugins/reporting/server/lib/store/store.ts @@ -85,7 +85,6 @@ export class ReportingStore { try { await client.indices.create({ index: indexName, - // @ts-expect-error @elastic/elasticsearch types don't support nested mappings body, }); diff --git a/x-pack/plugins/rollup/server/collectors/helpers.ts b/x-pack/plugins/rollup/server/collectors/helpers.ts index 3ec457bc6191e..1d1a8755aa568 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/security/server/routes/authorization/privileges/get_builtin.ts b/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts index e3a586062ae4c..29849497e02ec 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/session_management/session_index.ts b/x-pack/plugins/security/server/session_management/session_index.ts index a437856ec56c2..9093d5d2e0db2 100644 --- a/x-pack/plugins/security/server/session_management/session_index.ts +++ b/x-pack/plugins/security/server/session_management/session_index.ts @@ -339,7 +339,6 @@ export class SessionIndex { try { await this.options.elasticsearchClient.indices.putTemplate({ name: sessionIndexTemplateName, - // @ts-expect-error @elastic-elasticsearch types don't support nested properties body: getSessionIndexTemplate(this.indexName), }); this.options.logger.debug('Successfully created session index template.'); 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 3db9f06bd8bf6..c5cb4b97609c7 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.LicenseGetLicenseLicenseInformation; 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 86d1554a4fd57..75b9c736de901 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/server/routes/api/transforms.ts b/x-pack/plugins/transform/server/routes/api/transforms.ts index 80f80d6f1d71b..34ae3f42d8622 100644 --- a/x-pack/plugins/transform/server/routes/api/transforms.ts +++ b/x-pack/plugins/transform/server/routes/api/transforms.ts @@ -252,7 +252,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, }); 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 f7ff49727df33..a7f5f532b5ac0 100644 --- a/x-pack/test/case_api_integration/common/lib/utils.ts +++ b/x-pack/test/case_api_integration/common/lib/utils.ts @@ -47,7 +47,7 @@ export const getSignalsWithES = async ({ es: KibanaClient; indices: string | string[]; ids: string | string[]; -}): Promise>>> => { +}): Promise>>> => { const signals: ApiResponse> = await es.search({ index: indices, body: { @@ -69,13 +69,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 { From 7d6ad5cf256a31b83e012128e17c7f693a2f0de5 Mon Sep 17 00:00:00 2001 From: restrry Date: Tue, 18 May 2021 15:49:00 +0200 Subject: [PATCH 47/86] fix search intergration tests --- test/api_integration/apis/search/verify_error.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/api_integration/apis/search/verify_error.ts b/test/api_integration/apis/search/verify_error.ts index d6b729f59d8d4..1973fe4e4ab36 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'); From 19b8fe0464c7df8f198f1c004fc4d8d69a16f75d Mon Sep 17 00:00:00 2001 From: restrry Date: Tue, 18 May 2021 16:18:23 +0200 Subject: [PATCH 48/86] adjust assetion --- test/api_integration/apis/search/search.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/api_integration/apis/search/search.ts b/test/api_integration/apis/search/search.ts index 7ef82cd5467ab..9baf52c8d6041 100644 --- a/test/api_integration/apis/search/search.ts +++ b/test/api_integration/apis/search/search.ts @@ -138,7 +138,7 @@ export default function ({ getService }: FtrProviderContext) { it('should return 400 for a painless error', async () => { const resp = await supertest.post(`/internal/search/es`).send(painlessErrReq).expect(400); - verifyErrorResponse(resp.body, 400, 'search_phase_execution_exception', true); + verifyErrorResponse(resp.body, 400, 'script_exception', true); }); }); From 00a4af4d029671e7a4b3e91c0f168ff511d59916 Mon Sep 17 00:00:00 2001 From: restrry Date: Wed, 19 May 2021 12:30:32 +0200 Subject: [PATCH 49/86] bump version to canary.10 --- package.json | 2 +- yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index e475a5cc2c6ff..0ad23e82dd698 100644 --- a/package.json +++ b/package.json @@ -100,7 +100,7 @@ "@elastic/apm-rum-react": "^1.2.5", "@elastic/charts": "29.1.0", "@elastic/datemath": "link:bazel-bin/packages/elastic-datemath/npm_module", - "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.9", + "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.10", "@elastic/ems-client": "7.13.0", "@elastic/eui": "32.1.0", "@elastic/filesaver": "1.1.2", diff --git a/yarn.lock b/yarn.lock index ab1acedb4a355..8d06c9b4430b6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1410,10 +1410,10 @@ dependencies: "@elastic/ecs-helpers" "^1.1.0" -"@elastic/elasticsearch@npm:@elastic/elasticsearch-canary@^8.0.0-canary.9": - version "8.0.0-canary.9" - resolved "https://registry.yarnpkg.com/@elastic/elasticsearch-canary/-/elasticsearch-canary-8.0.0-canary.9.tgz#85b293a448593f7ecc68c6fd35bf5e4eadeb9f56" - integrity sha512-zdemJJTt/P1nJx/ttecHp2yDEBMiC3nA6BA9eQNdoGJN/VbzrlZwv35762719K/VRaeSPJqhHCsNgMURPgXxoA== +"@elastic/elasticsearch@npm:@elastic/elasticsearch-canary@^8.0.0-canary.10": + version "8.0.0-canary.10" + resolved "https://registry.yarnpkg.com/@elastic/elasticsearch-canary/-/elasticsearch-canary-8.0.0-canary.10.tgz#09c66a9f829c3f4158bec3dbdf4b1149a09bce14" + integrity sha512-C/HX6F86r6txGW4566juFUdocnsuBveRkELPKEWL+sXJ2BfjcbJNWBGwQH6ALS0/vncJ7tWLPTT0ZW7QkCIKEg== dependencies: debug "^4.3.1" hpagent "^0.1.1" From 812195f5ed3226201428e03ddeb13dd585117930 Mon Sep 17 00:00:00 2001 From: restrry Date: Wed, 19 May 2021 12:47:19 +0200 Subject: [PATCH 50/86] adapt code to new naming schema --- .../saved_objects/migrations/core/elastic_index.test.ts | 4 ++-- .../saved_objects/migrations/core/index_migrator.test.ts | 2 +- .../migrations/kibana/kibana_migrator.test.ts | 2 +- src/core/server/saved_objects/service/lib/repository.ts | 2 +- .../saved_objects/service/lib/search_dsl/search_dsl.ts | 2 +- .../service/lib/search_dsl/sorting_params.ts | 4 ++-- .../saved_objects/service/lib/update_objects_spaces.ts | 2 +- src/core/server/saved_objects/types.ts | 2 +- .../angular/doc_table/create_doc_table_react.tsx | 2 +- .../server/telemetry_collection/get_nodes_usage.ts | 4 ++-- typings/elasticsearch/search.d.ts | 4 ++-- .../lib/extract_bulk_response_delete_failures.ts | 4 +--- .../alerting/server/alerts_client/alerts_client.ts | 2 +- x-pack/plugins/canvas/types/strategy.ts | 2 +- .../ingest_pipelines/server/routes/api/simulate.ts | 2 +- x-pack/plugins/lens/server/routes/existing_fields.test.ts | 2 +- x-pack/plugins/lens/server/routes/existing_fields.ts | 2 +- .../services/utils/transform_elastic_to_list_item.ts | 2 +- x-pack/plugins/maps/server/mvt/get_tile.ts | 2 +- .../endpoint/data_generators/fleet_agent_generator.ts | 8 ++++---- .../security_solution/common/endpoint/index_data.ts | 4 ++-- .../lib/detection_engine/signals/filters/filter_events.ts | 2 +- .../signals/filters/filter_events_against_list.ts | 6 +++--- .../server/lib/detection_engine/signals/filters/types.ts | 6 +++--- .../lib/detection_engine/signals/threat_mapping/types.ts | 2 +- .../server/lib/detection_engine/signals/types.ts | 4 ++-- .../public/alert_types/es_query/expression.tsx | 2 +- .../server/alert_types/es_query/action_context.ts | 2 +- .../server/alert_types/es_query/alert_type.ts | 2 +- .../server/monitoring/workload_statistics.test.ts | 2 +- .../server/queries/mark_available_tasks_as_claimed.ts | 2 +- x-pack/plugins/task_manager/server/task_store.test.ts | 2 +- x-pack/plugins/task_manager/server/task_store.ts | 2 +- .../server/telemetry_collection/get_license.ts | 2 +- .../lib/fetch_all_from_scroll/fetch_all_from_scroll.ts | 2 +- x-pack/test/case_api_integration/common/lib/utils.ts | 6 +++--- 36 files changed, 51 insertions(+), 53 deletions(-) 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 fbcbb9213e662..c9c24cc85a452 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 @@ -164,7 +164,7 @@ describe('ElasticIndex', () => { client.tasks.get.mockResolvedValue( elasticsearchClientMock.createSuccessTransportRequestPromise({ completed: true, - } as estypes.TaskGetTaskResponse) + } as estypes.TaskGetResponse) ); const info = { @@ -248,7 +248,7 @@ describe('ElasticIndex', () => { reason: 'all shards failed', failed_shards: [], }, - } as estypes.TaskGetTaskResponse) + } as estypes.TaskGetResponse) ); const info = { 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 401f404e670d6..64d4fa3609e90 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.TaskGetTaskResponse) + } as estypes.TaskGetResponse) ); client.search.mockReturnValue( elasticsearchClientMock.createSuccessTransportRequestPromise(searchResult(0) as any) 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 94e3a7dbcf025..d0cc52f2dd9bd 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 @@ -337,7 +337,7 @@ const mockV2MigrationOptions = () => { error: undefined, failures: [], task: { description: 'task description' } as any, - } as estypes.TaskGetTaskResponse) + } as estypes.TaskGetResponse) ); options.client.search = jest diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts index 7382ebf9bef69..6b51bd57248a1 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -896,7 +896,7 @@ export class SavedObjectsRepository { per_page: perPage, total: body.hits.total, saved_objects: body.hits.hits.map( - (hit: estypes.SearchTypesHit): SavedObjectsFindResult => ({ + (hit: estypes.SearchHit): SavedObjectsFindResult => ({ // @ts-expect-error @elastic/elasticsearch declared Id as string | number ...this._rawToSavedObject(hit), score: hit._score!, 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 97d8aac929bab..3196a59ca39ee 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.SearchTypesSortOrder; + sortOrder?: estypes.SearchSortOrder; namespaces?: string[]; pit?: SavedObjectsPitParams; typeToNamespacesMap?: Map; 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 9b9b2d9ed59f5..592110a5413ec 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.SearchTypesSortOrder -): { sort?: estypes.SearchTypesSortContainer[] } { + 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 33073650f71f8..3131d0240f96b 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 @@ -192,7 +192,7 @@ export async function updateObjectsSpaces({ const time = new Date().toISOString(); let bulkOperationRequestIndexCounter = 0; - const bulkOperationParams: estypes.BulkBulkOperationContainer[] = []; + 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 594c1a8c84f30..964ba671b5964 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.SearchTypesSortOrder; + sortOrder?: estypes.SearchSortOrder; /** * An array of fields to include in the results * @example 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 162c72db700a3..55ef8e0b40533 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.SearchTypesHit[]; + rows: estypes.SearchHit[]; indexPattern: IIndexPattern; minimumVisibleRows: number; onAddColumn?: (column: string) => void; 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 f9e55b3bf4028..0d58d80ed5965 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.NodesNodesUsageNodeUsage { +export interface NodeUsage extends estypes.NodesUsageNodeUsage { /** * The Node ID as reported by ES */ @@ -31,7 +31,7 @@ export type NodesUsageGetter = (esClient: ElasticsearchClient) => Promise<{ node */ export async function fetchNodesUsage( esClient: ElasticsearchClient -): Promise { +): Promise { const { body } = await esClient.nodes.usage({ timeout: TIMEOUT, }); diff --git a/typings/elasticsearch/search.d.ts b/typings/elasticsearch/search.d.ts index de7683c29b154..4a8fff05bbc1b 100644 --- a/typings/elasticsearch/search.d.ts +++ b/typings/elasticsearch/search.d.ts @@ -56,7 +56,7 @@ 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 ? { @@ -526,7 +526,7 @@ export type AggregateOf< max_score: number | null; hits: TAggregationContainer extends { top_hits: estypes.TopHitsAggregation } ? HitsOf - : estypes.SearchTypesHitsMetadata; + : estypes.SearchHitsMetadata; }; }; top_metrics: { diff --git a/x-pack/plugins/actions/server/cleanup_failed_executions/lib/extract_bulk_response_delete_failures.ts b/x-pack/plugins/actions/server/cleanup_failed_executions/lib/extract_bulk_response_delete_failures.ts index 01ca44e156254..90418c9763a4d 100644 --- a/x-pack/plugins/actions/server/cleanup_failed_executions/lib/extract_bulk_response_delete_failures.ts +++ b/x-pack/plugins/actions/server/cleanup_failed_executions/lib/extract_bulk_response_delete_failures.ts @@ -7,9 +7,7 @@ import { ApiResponse, estypes } from '@elastic/elasticsearch'; -type ResponseFailures = Array< - Pick ->; +type ResponseFailures = Array>; export function extractBulkResponseDeleteFailures( response: ApiResponse 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 56c09c48b5d32..c81fa7927ef7d 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.SearchTypesSortOrder; + sortOrder?: estypes.SearchSortOrder; hasReference?: { type: string; id: string; diff --git a/x-pack/plugins/canvas/types/strategy.ts b/x-pack/plugins/canvas/types/strategy.ts index cd827cb191c69..d7115a3e4372f 100644 --- a/x-pack/plugins/canvas/types/strategy.ts +++ b/x-pack/plugins/canvas/types/strategy.ts @@ -27,5 +27,5 @@ export interface EssqlSearchStrategyResponse { }>; rows: any[]; - rawResponse: ApiResponse; + rawResponse: ApiResponse; } 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 0f107f38b251d..d2b475a9cfce2 100644 --- a/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts +++ b/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts @@ -39,7 +39,7 @@ export const registerSimulateRoute = ({ verbose, body: { pipeline, - docs: documents as estypes.IngestSimulatePipelineSimulatePipelineDocument[], + docs: documents as estypes.IngestSimulatePipelineDocument[], }, }); 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 66fb13c18ce8e..703b946149e26 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.SearchTypesHit + // @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 2d1ef9084610d..f35b0a7f23179 100644 --- a/x-pack/plugins/lens/server/routes/existing_fields.ts +++ b/x-pack/plugins/lens/server/routes/existing_fields.ts @@ -232,7 +232,7 @@ async function fetchIndexPatternStats({ /** * Exported only for unit tests. */ -export function existingFields(docs: estypes.SearchTypesHit[], 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/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 076b7658ddd81..53f1c6cabe8a9 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 @@ -21,7 +21,7 @@ export interface TransformElasticToListItemOptions { } export interface TransformElasticHitToListItemOptions { - hits: Array>; + hits: Array>; type: Type; } diff --git a/x-pack/plugins/maps/server/mvt/get_tile.ts b/x-pack/plugins/maps/server/mvt/get_tile.ts index 51902e1564429..776d316440a56 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.SearchTypesHit + // @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/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 e5872557aa952..58e7539b1f617 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,15 +51,15 @@ export class FleetAgentGenerator extends BaseDataGenerator { * @param [overrides] any partial value to the full document */ generateEsHit( - overrides: DeepPartial> = {} - ): estypes.SearchTypesHit { + overrides: DeepPartial> = {} + ): estypes.SearchHit { const hostname = this.randomHostname(); const now = new Date().toISOString(); const osFamily = this.randomOSFamily(); return merge< - estypes.SearchTypesHit, - DeepPartial> + estypes.SearchHit, + DeepPartial> >( { _index: AGENTS_INDEX, 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 43ca54be59c04..c78e1a747dc53 100644 --- a/x-pack/plugins/security_solution/common/endpoint/index_data.ts +++ b/x-pack/plugins/security_solution/common/endpoint/index_data.ts @@ -119,7 +119,7 @@ async function indexHostDocs({ const kibanaVersion = await fetchKibanaVersion(kbnClient); let hostMetadata: HostMetadata; let wasAgentEnrolled = false; - let enrolledAgent: undefined | estypes.SearchTypesHit; + let enrolledAgent: undefined | estypes.SearchHit; for (let j = 0; j < numDocs; j++) { generator.updateHostData(); @@ -368,7 +368,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/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 5e0a4294da2c0..da664f65c2d50 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 8c12a48f26b22..3b8314a2738f6 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 d253979252cf3..71471c0b4896d 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 @@ -21,7 +21,7 @@ export interface FilterEventsAgainstListOptions { } export interface CreateSetToFilterAgainstOptions { - events: Array>; + events: Array>; field: string; listId: string; listType: Type; @@ -31,12 +31,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/threat_mapping/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/types.ts index b4b2daf542579..c0bc4f550291b 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.SearchTypesHit; +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 6f4777fe13dbf..b107741b1c6f1 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.SearchTypesHit; +export type SignalSourceHit = estypes.SearchHit; export type WrappedSignalHit = BaseHit; -export type BaseSignalHit = estypes.SearchTypesHit; +export type BaseSignalHit = estypes.SearchHit; export type EqlSignalSearchResponse = EqlSearchResponse; 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 3783632e9ad1c..5111f427cd0d8 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.SearchTypesHitsMetadata['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 961501a3d0bab..84a4569d9b860 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.SearchTypesHit[]; + 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 9cd414ae5254c..b81bc19d5c731 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.SearchTypesTotalHits).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 daeb0c19e4b8d..f3ee21bc7d770 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 @@ -944,7 +944,7 @@ function setTaskTypeCount( ...rest.hits, total: { value: buckets.reduce((sum, bucket) => sum + bucket.doc_count, 0), - relation: 'eq' as estypes.SearchTypesTotalHitsRelation, + relation: 'eq' as estypes.SearchTotalHitsRelation, }, }, aggregations: { 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 6d5a674a8fa9c..1793ede8161df 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 @@ -104,7 +104,7 @@ if (doc['task.runAt'].size()!=0) { }; export const SortByRunAtAndRetryAt = (SortByRunAtAndRetryAtScript as unknown) as Record< string, - estypes.SearchTypesSort + estypes.SearchSort >; export const updateFieldsAndMarkAsFailed = ( 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 f04d38320ab78..936854087a74b 100644 --- a/x-pack/plugins/task_manager/server/task_store.test.ts +++ b/x-pack/plugins/task_manager/server/task_store.test.ts @@ -205,7 +205,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 69a9068488940..ce01660134683 100644 --- a/x-pack/plugins/task_manager/server/task_store.ts +++ b/x-pack/plugins/task_manager/server/task_store.ts @@ -46,7 +46,7 @@ export interface StoreOpts { export interface SearchOpts { search_after?: Array; size?: number; - sort?: estypes.SearchTypesSort; + sort?: estypes.SearchSort; query?: estypes.QueryDslQueryContainer; seq_no_primary_term?: boolean; } 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 c5cb4b97609c7..ad7d5439f8765 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.LicenseGetLicenseLicenseInformation; +export type ESLicense = estypes.LicenseGetLicenseInformation; let cachedLicense: ESLicense | undefined; 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 287f900c955d8..621fdf0d15861 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 @@ -13,7 +13,7 @@ import { ES_SCROLL_SETTINGS } from '../../../common/constants'; export function fetchAllFromScroll( searchResults: estypes.ScrollResponse, dataClient: IScopedClusterClient, - hits: estypes.SearchTypesHit[] = [] + hits: estypes.SearchHit[] = [] ): Promise { const newHits = get(searchResults, 'hits.hits', []); const scrollId = get(searchResults, '_scroll_id'); 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 a7f5f532b5ac0..e073c25727be2 100644 --- a/x-pack/test/case_api_integration/common/lib/utils.ts +++ b/x-pack/test/case_api_integration/common/lib/utils.ts @@ -47,7 +47,7 @@ export const getSignalsWithES = async ({ es: KibanaClient; indices: string | string[]; ids: string | string[]; -}): Promise>>> => { +}): Promise>>> => { const signals: ApiResponse> = await es.search({ index: indices, body: { @@ -69,13 +69,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 { From 287745b7a764ea0fdf25b2598699ba85f68afeda Mon Sep 17 00:00:00 2001 From: restrry Date: Wed, 19 May 2021 14:50:13 +0200 Subject: [PATCH 51/86] use mapping types provided by the client library --- src/core/server/index.ts | 2 - src/core/server/saved_objects/index.ts | 2 - .../server/saved_objects/mappings/index.ts | 2 - .../mappings/lib/get_property.ts | 4 +- .../lib/get_root_properties_objects.ts | 8 +-- .../server/saved_objects/mappings/types.ts | 52 ++++--------------- .../migrations/core/elastic_index.ts | 2 - .../migrationsv2/actions/index.ts | 2 - 8 files changed, 15 insertions(+), 59 deletions(-) diff --git a/src/core/server/index.ts b/src/core/server/index.ts index 05408d839c0ae..28ae845fd424e 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 2af25e0cdef3f..b1b1584d7de88 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 bf1029e9f3b81..5da185ace79c6 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.ts b/src/core/server/saved_objects/mappings/lib/get_property.ts index c2daa1e70a898..2a9993bc175ca 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.ts b/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.ts index 3a25865c03b26..54ea4eafc186f 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 da9a41ab03080..e2ad2a91fd000 100644 --- a/src/core/server/saved_objects/mappings/types.ts +++ b/src/core/server/saved_objects/mappings/types.ts @@ -97,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 { @@ -115,41 +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 type SavedObjectsCoreFieldMapping = 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'; -}; - -/** - * 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/elastic_index.ts b/src/core/server/saved_objects/migrations/core/elastic_index.ts index 55d61c80fb7f0..296a4cee07c11 100644 --- a/src/core/server/saved_objects/migrations/core/elastic_index.ts +++ b/src/core/server/saved_objects/migrations/core/elastic_index.ts @@ -256,7 +256,6 @@ export async function createIndex( mappings?: IndexMapping ) { await client.indices.create({ - // @ts-expect-error @elastic-elasticsearch types don't support nested properties body: { mappings, settings }, index, }); @@ -279,7 +278,6 @@ export async function convertToAlias( script?: string ) { await client.indices.create({ - // @ts-expect-error @elastic-elasticsearch types don't support nested properties body: { mappings: info.mappings, settings }, index: info.indexName, }); diff --git a/src/core/server/saved_objects/migrationsv2/actions/index.ts b/src/core/server/saved_objects/migrationsv2/actions/index.ts index 201cfb1fec059..cc6fd30b4be42 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/index.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/index.ts @@ -868,7 +868,6 @@ export const createIndex = ( // started timeout: DEFAULT_TIMEOUT, body: { - // @ts-expect-error @elastic-elasticsearch types don't support nested properties mappings, aliases: aliasesObject, settings: { @@ -963,7 +962,6 @@ export const updateAndPickupMappings = ( .putMapping({ index, timeout: DEFAULT_TIMEOUT, - // @ts-expect-error @elastic-elasticsearch types don't support nested properties body: mappings, }) .then((res) => { From f85e9baa929064786af48cc0992bed75b6233157 Mon Sep 17 00:00:00 2001 From: restrry Date: Wed, 19 May 2021 14:51:27 +0200 Subject: [PATCH 52/86] Revert "adjust assetion" This reverts commit 19b8fe0464c7df8f198f1c004fc4d8d69a16f75d. --- test/api_integration/apis/search/search.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/api_integration/apis/search/search.ts b/test/api_integration/apis/search/search.ts index 9baf52c8d6041..7ef82cd5467ab 100644 --- a/test/api_integration/apis/search/search.ts +++ b/test/api_integration/apis/search/search.ts @@ -138,7 +138,7 @@ export default function ({ getService }: FtrProviderContext) { it('should return 400 for a painless error', async () => { const resp = await supertest.post(`/internal/search/es`).send(painlessErrReq).expect(400); - verifyErrorResponse(resp.body, 400, 'script_exception', true); + verifyErrorResponse(resp.body, 400, 'search_phase_execution_exception', true); }); }); From 2f58edb2eddd5f02bd53c77681874c24b4c7f99c Mon Sep 17 00:00:00 2001 From: restrry Date: Wed, 19 May 2021 15:58:52 +0200 Subject: [PATCH 53/86] fix so intergration tests --- .../integration_tests/actions.test.ts | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/src/core/server/saved_objects/migrationsv2/integration_tests/actions.test.ts b/src/core/server/saved_objects/migrationsv2/integration_tests/actions.test.ts index a31769c4a6db1..5fc304d5329bf 100644 --- a/src/core/server/saved_objects/migrationsv2/integration_tests/actions.test.ts +++ b/src/core/server/saved_objects/migrationsv2/integration_tests/actions.test.ts @@ -221,9 +221,7 @@ describe('migration actions', () => { it('rejects if there is a non-retryable error', async () => { expect.assertions(1); const task = removeWriteBlock(client, 'no_such_index'); - await expect(task()).rejects.toMatchInlineSnapshot( - `[ResponseError: index_not_found_exception]` - ); + await expect(task()).rejects.toThrow('index_not_found_exception'); }); }); @@ -243,7 +241,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: { settings: { routing: { allocation: { enable: 'none' } } } }, + routing: { allocation: { enable: 'none' } }, }, }, }, @@ -799,9 +797,7 @@ describe('migration actions', () => { it('rejects if source or target index does not exist', async () => { expect.assertions(2); let task = verifyReindex(client, 'no_such_index', '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, 'existing_index_2', 'no_such_index'); await expect(task()).rejects.toThrow('index_not_found_exception'); @@ -1067,10 +1063,7 @@ describe('migration actions', () => { const task = waitForPickupUpdatedMappingsTask(client, res.right.taskId, '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( @@ -1342,7 +1335,7 @@ describe('migration actions', () => { // failure await expect( createIndex(client, 'existing_index_2_alias', undefined as any)() - ).rejects.toMatchInlineSnapshot(`[ResponseError: invalid_index_name_exception]`); + ).rejects.toThrow('invalid_index_name_exception'); }); }); From 604355428a47e86656510accec7f95f976a6e969 Mon Sep 17 00:00:00 2001 From: restrry Date: Wed, 19 May 2021 16:50:35 +0200 Subject: [PATCH 54/86] fix http integration tests --- src/core/server/http/integration_tests/core_services.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 5433f0d3c3e31..3ffa16c2f6a15 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('[Response Error]: error_reason'); }); }); }); From 194bdb25fae4c0e2d301b82f622203205fd4355f Mon Sep 17 00:00:00 2001 From: restrry Date: Sat, 22 May 2021 09:43:09 +0200 Subject: [PATCH 55/86] bump version to canary 11 --- package.json | 2 +- yarn.lock | 19 +++++++++---------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/package.json b/package.json index 6284fbbb40e6b..d23e7c06f0095 100644 --- a/package.json +++ b/package.json @@ -100,7 +100,7 @@ "@elastic/apm-rum-react": "^1.2.5", "@elastic/charts": "29.1.0", "@elastic/datemath": "link:bazel-bin/packages/elastic-datemath/npm_module", - "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.10", + "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.11", "@elastic/ems-client": "7.13.0", "@elastic/eui": "32.1.0", "@elastic/filesaver": "1.1.2", diff --git a/yarn.lock b/yarn.lock index 1e5b194d31f16..8a3faf0964ca2 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.10": - version "8.0.0-canary.10" - resolved "https://registry.yarnpkg.com/@elastic/elasticsearch-canary/-/elasticsearch-canary-8.0.0-canary.10.tgz#09c66a9f829c3f4158bec3dbdf4b1149a09bce14" - integrity sha512-C/HX6F86r6txGW4566juFUdocnsuBveRkELPKEWL+sXJ2BfjcbJNWBGwQH6ALS0/vncJ7tWLPTT0ZW7QkCIKEg== +"@elastic/elasticsearch@npm:@elastic/elasticsearch-canary@^8.0.0-canary.11": + version "8.0.0-canary.11" + resolved "https://registry.yarnpkg.com/@elastic/elasticsearch-canary/-/elasticsearch-canary-8.0.0-canary.11.tgz#69aa6da6675fd487172d3fff9563b45708dff275" + integrity sha512-sQnaPLSR678jwBfZdE8Rq0QSR3jMaT0yR86nyGakJNLrxpWmPtkZsIYBhWSZoGPli5pg8sYGz+NpHzxVfXg4+Q== 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" @@ -24761,10 +24760,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" From f4731c41aecb3d7064880b292167430aaf7dc4fd Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Sat, 22 May 2021 10:23:49 +0200 Subject: [PATCH 56/86] fix login test --- .../tests/anonymous/login.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) 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 30d5d3ea33120..05f3adf2b8cb6 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); }); From cdb20175c2af9618f27c38a74edddff28ec74154 Mon Sep 17 00:00:00 2001 From: restrry Date: Sat, 22 May 2021 10:27:19 +0200 Subject: [PATCH 57/86] fix http integration test --- src/core/server/http/integration_tests/core_services.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 3ffa16c2f6a15..99b63fc73687a 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).toMatch('[Response Error]: error_reason'); + expect(body.message).toMatch('[error_type]: error_reason'); }); }); }); From 4d70bd0751fd5c23542c47a5d07c0c8f8971ba26 Mon Sep 17 00:00:00 2001 From: restrry Date: Sat, 22 May 2021 10:36:07 +0200 Subject: [PATCH 58/86] fix apm test --- x-pack/test/apm_api_integration/tests/alerts/rule_registry.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 e0a3e4d3a3f8b..26dfef21f80ce 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 @@ -601,7 +601,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'); }); }); } From 9e5aa9b64c6d51b47a71399850617e4caa76fc67 Mon Sep 17 00:00:00 2001 From: restrry Date: Sat, 22 May 2021 10:53:18 +0200 Subject: [PATCH 59/86] update docs --- ...gin-core-public.savedobjectsfindoptions.md | 2 +- ...ublic.savedobjectsfindoptions.sortorder.md | 2 +- .../core/server/kibana-plugin-core-server.md | 2 - ...edobjectscomplexfieldmapping.doc_values.md | 11 ----- ...savedobjectscomplexfieldmapping.dynamic.md | 15 ------- ...savedobjectscomplexfieldmapping.enabled.md | 11 ----- ...-server.savedobjectscomplexfieldmapping.md | 24 ----------- ...edobjectscomplexfieldmapping.properties.md | 11 ----- ...er.savedobjectscomplexfieldmapping.type.md | 11 ----- ...savedobjectscorefieldmapping.doc_values.md | 11 ----- ...ver.savedobjectscorefieldmapping.fields.md | 16 -------- ...rver.savedobjectscorefieldmapping.index.md | 11 ----- ...ore-server.savedobjectscorefieldmapping.md | 24 ----------- ...savedobjectscorefieldmapping.null_value.md | 11 ----- ...erver.savedobjectscorefieldmapping.type.md | 11 ----- ...in-core-server.savedobjectsfieldmapping.md | 4 +- ...gin-core-server.savedobjectsfindoptions.md | 2 +- ...erver.savedobjectsfindoptions.sortorder.md | 2 +- ...gin-plugins-data-public.ifieldtype.lang.md | 2 +- ...a-plugin-plugins-data-public.ifieldtype.md | 2 +- ...gins-data-public.indexpatternfield.lang.md | 4 +- ...n-plugins-data-public.indexpatternfield.md | 2 +- ...ns-data-public.indexpatternfield.tojson.md | 4 +- ...plugin-plugins-data-public.phrasefilter.md | 2 +- ...-plugin-plugins-data-public.rangefilter.md | 2 +- ...-plugin-plugins-data-public.reason.lang.md | 2 +- ...ibana-plugin-plugins-data-public.reason.md | 2 +- ...gin-plugins-data-server.ifieldtype.lang.md | 2 +- ...a-plugin-plugins-data-server.ifieldtype.md | 2 +- ...rver.searchstrategydependencies.request.md | 11 +++++ src/core/public/public.api.md | 4 +- src/core/server/server.api.md | 40 +++---------------- src/plugins/data/public/public.api.md | 14 +++---- src/plugins/data/server/server.api.md | 10 ++--- 34 files changed, 50 insertions(+), 236 deletions(-) delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.doc_values.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.dynamic.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.enabled.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.properties.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.type.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.doc_values.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.fields.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.index.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.type.md create mode 100644 docs/development/plugins/data/server/kibana-plugin-plugins-data-server.searchstrategydependencies.request.md 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 7be45c6c173b4..706408f81f02a 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 36f99e51ea8c6..506fb9041e353 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 32a2f3312708c..604cdea1a7fbe 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 3f2d81cc97c7c..0000000000000 --- 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 b01da3c62fda6..0000000000000 --- 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 08513aa2a849b..0000000000000 --- 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 fc262cad54f18..0000000000000 --- 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 613a36a09ba1e..0000000000000 --- 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 8aaa524dad43a..0000000000000 --- 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 2a79eafd85a6c..0000000000000 --- 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 4f88b635ca2f7..0000000000000 --- 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 e3cf685e310d2..0000000000000 --- 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 e9b9c2bcf51b5..0000000000000 --- 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 627ea3695383a..0000000000000 --- 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 94d395d7983e5..0000000000000 --- 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 925ca4be92e66..85b52bacafa25 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 a92b1f48d08eb..d3696ee71049a 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 e1c657e3a5171..dca5a7d8c7583 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 a994fc458cfb6..f99e7ba8b967e 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 4e3dea5549b56..29377ff8fd392 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.indexpatternfield.lang.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.lang.md index b81218eb08886..3666e503e2722 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 05c807b1cd845..8cd1a476cf32f 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 f0600dd20658a..8882fa05ce0c2 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 090b78a7078cc..8d0447d58634c 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 fbe04f5e0a2a9..1cb627ec3a8f9 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 095142cf0f05b..757d8f34a0c3a 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 a1a76f2d2a295..fb39333cf245e 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 d033804cb6fcb..3d5a757cb8f18 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 5ac48d26a85d6..bbc4cc2135d40 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.searchstrategydependencies.request.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.searchstrategydependencies.request.md new file mode 100644 index 0000000000000..18163bfebde7e --- /dev/null +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.searchstrategydependencies.request.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-server](./kibana-plugin-plugins-data-server.md) > [SearchStrategyDependencies](./kibana-plugin-plugins-data-server.searchstrategydependencies.md) > [request](./kibana-plugin-plugins-data-server.searchstrategydependencies.request.md) + +## SearchStrategyDependencies.request property + +Signature: + +```typescript +request: KibanaRequest; +``` diff --git a/src/core/public/public.api.md b/src/core/public/public.api.md index 449afa8869f6f..38533a4a18046 100644 --- a/src/core/public/public.api.md +++ b/src/core/public/public.api.md @@ -1264,7 +1264,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 @@ -1290,7 +1290,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/server.api.md b/src/core/server/server.api.md index d9ad24a4a2c0c..e0f9386a6fdfd 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -2355,38 +2355,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; @@ -2548,12 +2516,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 @@ -2577,7 +2547,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/public/public.api.md b/src/plugins/data/public/public.api.md index 8561d7bf8d6f5..5467bd4e748d7 100644 --- a/src/plugins/data/public/public.api.md +++ b/src/plugins/data/public/public.api.md @@ -1195,7 +1195,7 @@ export interface IFieldType { // (undocumented) format?: any; // (undocumented) - lang?: string; + lang?: estypes.ScriptLanguage; // (undocumented) name: string; // (undocumented) @@ -1480,8 +1480,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) @@ -1505,7 +1505,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; @@ -1949,7 +1949,7 @@ export type PhraseFilter = Filter & { script?: { script: { source?: any; - lang?: string; + lang?: estypes.ScriptLanguage; params: any; }; }; @@ -2167,7 +2167,7 @@ export type RangeFilter = Filter & EsRangeFilter & { script?: { script: { params: any; - lang: string; + lang: estypes.ScriptLanguage; source: any; }; }; @@ -2213,7 +2213,7 @@ export interface Reason { reason: string; }; // (undocumented) - lang?: string; + lang?: estypes.ScriptLanguage; // (undocumented) position?: { offset: number; diff --git a/src/plugins/data/server/server.api.md b/src/plugins/data/server/server.api.md index a8eafd7b14aa9..b69822af6534f 100644 --- a/src/plugins/data/server/server.api.md +++ b/src/plugins/data/server/server.api.md @@ -709,7 +709,7 @@ export interface IFieldType { // (undocumented) format?: any; // (undocumented) - lang?: string; + lang?: estypes.ScriptLanguage; // (undocumented) name: string; // (undocumented) @@ -1425,22 +1425,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; }; From 93e5d3e9c842d799a90836e04d4bb5e380666b72 Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Wed, 26 May 2021 10:04:30 +0100 Subject: [PATCH 60/86] fixing some ml types --- .../types/anomaly_detection_jobs/datafeed.ts | 4 ++-- .../anomaly_detection_jobs/datafeed_stats.ts | 2 +- .../common/types/anomaly_detection_jobs/job.ts | 16 ++++++++-------- .../types/anomaly_detection_jobs/job_stats.ts | 12 ++++++------ x-pack/plugins/ml/common/types/es_client.ts | 8 +++++--- x-pack/plugins/ml/common/types/fields.ts | 4 ++-- .../ml/common/util/runtime_field_utils.ts | 2 +- 7 files changed, 25 insertions(+), 23 deletions(-) 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 ef41e54a5c0d7..48f303278f791 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,9 +9,9 @@ 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; 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 dd0d3a5001f84..4e23d97c0d145 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 68544e7cb828f..edd023d007a24 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.XpackUsageCustomSettings; 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 a53f1f2486699..be53c8c8b02b4 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,23 @@ import { estypes } from '@elastic/elasticsearch'; -export type JobStats = estypes.JobStats & { +export type JobStats = estypes.MlJobStats & { model_size_stats: ModelSizeStats; timing_stats: TimingStats; }; -export type DataCounts = estypes.DataCounts; +export type DataCounts = estypes.MlDataCounts; -export type ModelSizeStats = estypes.ModelSizeStats & { +export type ModelSizeStats = estypes.MlModelSizeStats & { model_bytes_exceeded: number; model_bytes_memory_limit: number; peak_model_bytes?: number; }; -export type TimingStats = estypes.TimingStats & { +export type TimingStats = estypes.MlTimingStats & { total_bucket_processing_time_ms: number; }; -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/es_client.ts b/x-pack/plugins/ml/common/types/es_client.ts index 249b3c150a082..67adda6b24c18 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 cf017192353e9..33a4a94e539b8 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/runtime_field_utils.ts b/x-pack/plugins/ml/common/util/runtime_field_utils.ts index 7be2a3ec8c9e1..1fcf8e2e72b15 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']) && From a4493327678d11c3b5e7dd2950d9d33338fd268e Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Thu, 3 Jun 2021 18:49:52 +0300 Subject: [PATCH 61/86] fix new errors in data plugin --- .../data/common/search/aggs/agg_configs.ts | 8 ++-- .../common/search/aggs/utils/time_splits.ts | 45 +++++++++---------- 2 files changed, 27 insertions(+), 26 deletions(-) diff --git a/src/plugins/data/common/search/aggs/agg_configs.ts b/src/plugins/data/common/search/aggs/agg_configs.ts index 6f8a8d38a4a28..8593a0b0ed0fa 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 4ac47efaea347..75c1c091e0756 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 Date: Thu, 3 Jun 2021 18:50:16 +0300 Subject: [PATCH 62/86] fix new errors in alerting plugin --- x-pack/plugins/alerting/server/saved_objects/index.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/alerting/server/saved_objects/index.ts b/x-pack/plugins/alerting/server/saved_objects/index.ts index c339183eeedcd..1ad0f972b2ec0 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: { From 4adebdd94dd1455e4670c3502e463afa49cf6589 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Thu, 3 Jun 2021 18:50:34 +0300 Subject: [PATCH 63/86] fix new errors in lists plugin --- .../lists/server/services/utils/get_sort_with_tie_breaker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 dbcec20d3d8a8..8a513483f5b5e 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 }]; From d0f0a27c6b53e7c16470a52afcc7420169fdb286 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Thu, 3 Jun 2021 18:50:51 +0300 Subject: [PATCH 64/86] fix new errors in reporting --- .../plugins/reporting/server/lib/store/report_ilm_policy.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/reporting/server/lib/store/report_ilm_policy.ts b/x-pack/plugins/reporting/server/lib/store/report_ilm_policy.ts index f4cd69a0331d7..de676d0661b49 100644 --- a/x-pack/plugins/reporting/server/lib/store/report_ilm_policy.ts +++ b/x-pack/plugins/reporting/server/lib/store/report_ilm_policy.ts @@ -5,9 +5,9 @@ * 2.0. */ -import { PutLifecycleRequest } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; -export const reportingIlmPolicy: PutLifecycleRequest['body'] = { +export const reportingIlmPolicy: estypes.IlmPutLifecycleRequest['body'] = { policy: { phases: { hot: { From 0245d27bc8b836bb9b091c2fac3a6af01b622d15 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Thu, 3 Jun 2021 18:51:19 +0300 Subject: [PATCH 65/86] fix or mute errors in rule_registry plugin --- .../event_log/elasticsearch/index_management_gateway.ts | 1 + .../server/event_log/elasticsearch/resources/ilm_policy.ts | 2 +- .../event_log/elasticsearch/resources/index_template.ts | 3 ++- .../rule_registry/server/event_log/log/event_query_builder.ts | 4 ++-- .../plugins/rule_registry/server/event_log/log/public_api.ts | 2 +- 5 files changed, 7 insertions(+), 5 deletions(-) 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 96b5860e143ee..cb04a442d0b34 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 00fc9131523ac..7663ea27fb0df 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 caf71dadf6e1e..0045bce3ed873 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 48228ce5352b7..bf9aca74f7800 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 7807dd9ca6b36..7dcaee9d382b1 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; From a02b056f9cdef92d062ea61043388b3a8ad2a573 Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Thu, 3 Jun 2021 17:31:33 +0100 Subject: [PATCH 66/86] more ML type fixes --- .../types/anomaly_detection_jobs/datafeed.ts | 7 +--- .../types/anomaly_detection_jobs/job.ts | 2 +- .../types/anomaly_detection_jobs/job_stats.ts | 15 ++------ .../anomaly_detection_jobs/model_snapshot.ts | 16 +------- .../components/data_grid/common.ts | 2 +- .../application/components/data_grid/types.ts | 2 +- .../chart_loader.ts | 1 - .../common/get_index_data.ts | 2 +- .../form_options_validation.ts | 2 +- .../hooks/use_index_data.ts | 6 ++- .../job_creator/advanced_job_creator.ts | 9 ++--- .../new_job/common/job_creator/job_creator.ts | 1 + .../util/filter_runtime_mappings.test.ts | 4 +- .../categorization_examples_loader.ts | 1 - .../common/results_loader/results_loader.ts | 1 - .../advanced_detector_modal.tsx | 4 +- .../estimate_bucket_span.ts | 1 - .../metric_selection_summary.tsx | 1 - .../multi_metric_view/metric_selection.tsx | 2 - .../metric_selection_summary.tsx | 2 - .../population_view/metric_selection.tsx | 2 - .../metric_selection_summary.tsx | 2 - .../single_metric_view/metric_selection.tsx | 1 - .../metric_selection_summary.tsx | 1 - .../components/time_range_step/time_range.tsx | 1 - .../new_job/recognize/components/edit_job.tsx | 8 ++-- .../new_job/recognize/components/job_item.tsx | 11 +++--- .../ml/server/lib/ml_client/ml_client.ts | 1 + .../models/calendar/calendar_manager.ts | 2 +- .../server/models/calendar/event_manager.ts | 2 +- .../data_frame_analytics/analytics_manager.ts | 37 ++++++++++++++++++- .../ml/server/models/filter/filter_manager.ts | 36 ++++++++++-------- .../ml/server/models/job_service/datafeeds.ts | 6 +-- .../ml/server/models/job_service/jobs.ts | 6 --- .../job_service/new_job_caps/field_service.ts | 6 ++- .../models/job_service/new_job_caps/rollup.ts | 4 +- .../models/job_validation/job_validation.ts | 1 - .../ml/server/routes/anomaly_detectors.ts | 17 ++++----- .../ml/server/routes/data_frame_analytics.ts | 3 ++ x-pack/plugins/ml/server/routes/datafeeds.ts | 2 +- .../ml/server/routes/trained_models.ts | 1 + .../apis/ml/calendars/helpers.ts | 2 +- x-pack/test/functional/services/ml/api.ts | 8 ++-- 43 files changed, 119 insertions(+), 122 deletions(-) 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 48f303278f791..e1a3f6044587b 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 @@ -15,9 +15,4 @@ export type ChunkingConfig = estypes.MlChunkingConfig; 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/job.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts index edd023d007a24..2ef1d824180ad 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 @@ -29,4 +29,4 @@ export interface PerPartitionCategorization { stop_on_warn?: boolean; } -export type CustomSettings = estypes.XpackUsageCustomSettings; +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 be53c8c8b02b4..5fc8b423a5ac2 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,22 +7,13 @@ import { estypes } from '@elastic/elasticsearch'; -export type JobStats = estypes.MlJobStats & { - model_size_stats: ModelSizeStats; - timing_stats: TimingStats; -}; +export type JobStats = estypes.MlJobStats; export type DataCounts = estypes.MlDataCounts; -export type ModelSizeStats = estypes.MlModelSizeStats & { - model_bytes_exceeded: number; - model_bytes_memory_limit: number; - peak_model_bytes?: number; -}; +export type ModelSizeStats = estypes.MlModelSizeStats; -export type TimingStats = estypes.MlTimingStats & { - total_bucket_processing_time_ms: number; -}; +export type TimingStats = estypes.MlTimingStats; export type ForecastsStats = estypes.MlJobForecastStatistics; 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 f844c42f4ca6e..0bb2162994c37 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/public/application/components/data_grid/common.ts b/x-pack/plugins/ml/public/application/components/data_grid/common.ts index 24a3cfb70d18d..a64594e86a757 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 865e09e72b40c..9dcd6abb432b3 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 15979751f40d6..a9217d884fd32 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 88f403cdf0c44..920f56b376747 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 79986e8ddb098..72853ec23fd36 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 f3b51acf093ad..ddf88ce79ab5b 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 45b26226def8f..35847839b02a0 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 fe0329851758c..d4a410bcda24c 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 7f1ee2349c2c1..f81362ad83288 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 b51cd9b99792b..641eda3dbf3e8 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 6d5fa26af7024..a01581f7526c5 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 2b1a35bcb8c46..237af335ffa51 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 113bde6fbf93d..85083146c1378 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 c553da93a4bc0..9d84854245216 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 6cbf96fcb04e8..58252feca4b53 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 dc76fc0178112..a4c344d16482b 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 c5efd4b226d5c..1be487d5b7eec 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 31b436944a5b0..55a9d37d1115c 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 b2a97d8e0589a..d41234bbedd81 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 5e64f4ef18984..ced94b2095f72 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 7e7b919f677ab..66c92d5c80851 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 6ce808ed36b15..d2780691e551d 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 311e291cf2519..b97c16e02d900 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 6e76a536feb25..736835e344613 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' ); 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 458a34346bed9..791ba6d79ab5a 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 c870d67524135..d30297eab5c15 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 a9c1d95d933a9..41b8e6dfe96c4 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/filter/filter_manager.ts b/x-pack/plugins/ml/server/models/filter/filter_manager.ts index 1429324a6d9c8..f48b71dedf3ee 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 72255e168249a..5dfe1b5934fe9 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 a838db443bebc..b7f8ce569641e 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 49c09742985d4..fad388f791f08 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 d83f7afb4cdf6..5f5ae16ed9733 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 00a51d1e4e153..80eba7b864051 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 5205ea7353ac6..a139ef7c70ac8 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,12 @@ 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, + body: {}, }); 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 f6dc21538ffa0..2ed4fd6fcd31a 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 2013af3ee8735..9f908bf61a35d 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 c4b2d63b05d13..106010d0f7550 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/test/api_integration/apis/ml/calendars/helpers.ts b/x-pack/test/api_integration/apis/ml/calendars/helpers.ts index f80c985c2676e..4667eb25437b1 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/functional/services/ml/api.ts b/x-pack/test/functional/services/ml/api.ts index 4623b4f4e41ae..9a96b1ec372dc 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 () => { From 8e913394641bfb2e50bd26af29c8cac367e0fa7c Mon Sep 17 00:00:00 2001 From: restrry Date: Thu, 3 Jun 2021 19:50:10 +0300 Subject: [PATCH 67/86] bump to canary 12 --- package.json | 2 +- yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 7be69633aebdd..4d1540d5eef0b 100644 --- a/package.json +++ b/package.json @@ -101,7 +101,7 @@ "@elastic/apm-rum-react": "^1.2.5", "@elastic/charts": "29.2.0", "@elastic/datemath": "link:bazel-bin/packages/elastic-datemath/npm_module", - "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.11", + "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.12", "@elastic/ems-client": "7.13.0", "@elastic/eui": "33.0.0", "@elastic/filesaver": "1.1.2", diff --git a/yarn.lock b/yarn.lock index dfe87641e4c7a..f62d70775a6ac 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1410,10 +1410,10 @@ dependencies: "@elastic/ecs-helpers" "^1.1.0" -"@elastic/elasticsearch@npm:@elastic/elasticsearch-canary@^8.0.0-canary.11": - version "8.0.0-canary.11" - resolved "https://registry.yarnpkg.com/@elastic/elasticsearch-canary/-/elasticsearch-canary-8.0.0-canary.11.tgz#69aa6da6675fd487172d3fff9563b45708dff275" - integrity sha512-sQnaPLSR678jwBfZdE8Rq0QSR3jMaT0yR86nyGakJNLrxpWmPtkZsIYBhWSZoGPli5pg8sYGz+NpHzxVfXg4+Q== +"@elastic/elasticsearch@npm:@elastic/elasticsearch-canary@^8.0.0-canary.12": + version "8.0.0-canary.12" + resolved "https://registry.yarnpkg.com/@elastic/elasticsearch-canary/-/elasticsearch-canary-8.0.0-canary.12.tgz#1d7004d644cb102d7f19c8579c7c5807f1dc8188" + integrity sha512-DU1N+re6LKB5ZzySvxLHu25te9L6Nk9CFiIg0z+3cOugSY/U9wotYDdz44BEosE1skBKJsb46O7nnrElrmxo3w== dependencies: debug "^4.3.1" hpagent "^0.1.1" From 22314768032f4c28cab0957e22cfc0195ba41897 Mon Sep 17 00:00:00 2001 From: restrry Date: Thu, 3 Jun 2021 20:23:43 +0300 Subject: [PATCH 68/86] fix errors after merge conflict --- .../server/saved_objects/migrationsv2/actions/create_index.ts | 4 ++-- .../saved_objects/migrationsv2/actions/read_with_pit.ts | 2 +- src/core/server/saved_objects/migrationsv2/actions/reindex.ts | 2 +- .../saved_objects/migrationsv2/actions/remove_write_block.ts | 2 +- .../migrationsv2/actions/search_for_outdated_documents.ts | 2 +- .../migrationsv2/actions/wait_for_reindex_task.ts | 2 +- .../saved_objects/migrationsv2/actions/wait_for_task.ts | 3 +-- 7 files changed, 8 insertions(+), 9 deletions(-) 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 47ee44e762db7..8e5042a5ff8fe 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/read_with_pit.ts b/src/core/server/saved_objects/migrationsv2/actions/read_with_pit.ts index 16f1df05f26b3..b101e7db0141c 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 ca8d3b594703c..e9cfb4b61dace 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 c55e4a235fbf1..b5bf64d5c29f7 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 7406cd35b1593..c27170a78245b 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 fcadb5e80298a..18cf3350292b5 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 4e3631797e34b..0cdaa88c535ab 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, From ce581f63eaef99ff699abecc7a177a49ffc72b4e Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Fri, 4 Jun 2021 09:33:47 +0100 Subject: [PATCH 69/86] additional ML fixes --- x-pack/plugins/ml/server/lib/ml_client/ml_client.ts | 5 +++-- x-pack/plugins/ml/server/routes/anomaly_detectors.ts | 1 - x-pack/test/functional/apps/ml/permissions/full_ml_access.ts | 1 - 3 files changed, 3 insertions(+), 4 deletions(-) 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 736835e344613..0a9c76893dd0b 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 @@ -495,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/routes/anomaly_detectors.ts b/x-pack/plugins/ml/server/routes/anomaly_detectors.ts index a139ef7c70ac8..c5be5e1c9ef2d 100644 --- a/x-pack/plugins/ml/server/routes/anomaly_detectors.ts +++ b/x-pack/plugins/ml/server/routes/anomaly_detectors.ts @@ -522,7 +522,6 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) { 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, - body: {}, }); return response.ok({ body, 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 a203b078774c7..87f74363413d3 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', From c068c1b3bebee916953ea6649b79563c2cb39b26 Mon Sep 17 00:00:00 2001 From: restrry Date: Fri, 4 Jun 2021 12:52:57 +0300 Subject: [PATCH 70/86] bump to canary 13 --- package.json | 2 +- yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index a6c9303c1d6b2..898ee12bba360 100644 --- a/package.json +++ b/package.json @@ -101,7 +101,7 @@ "@elastic/apm-rum-react": "^1.2.5", "@elastic/charts": "29.2.0", "@elastic/datemath": "link:bazel-bin/packages/elastic-datemath", - "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.12", + "@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/yarn.lock b/yarn.lock index 1905b4844c2f4..dfda08dc39075 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1410,10 +1410,10 @@ dependencies: "@elastic/ecs-helpers" "^1.1.0" -"@elastic/elasticsearch@npm:@elastic/elasticsearch-canary@^8.0.0-canary.12": - version "8.0.0-canary.12" - resolved "https://registry.yarnpkg.com/@elastic/elasticsearch-canary/-/elasticsearch-canary-8.0.0-canary.12.tgz#1d7004d644cb102d7f19c8579c7c5807f1dc8188" - integrity sha512-DU1N+re6LKB5ZzySvxLHu25te9L6Nk9CFiIg0z+3cOugSY/U9wotYDdz44BEosE1skBKJsb46O7nnrElrmxo3w== +"@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" From c07f8e85e7a93f31401157b5ace2c3fa673b9e0b Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Fri, 4 Jun 2021 16:19:25 +0300 Subject: [PATCH 71/86] fix errors in apm plugin --- .../apm_telemetry/collect_data_telemetry/tasks.ts | 4 ++-- .../create_internal_es_client/index.ts | 12 ++++-------- .../lib/metrics/by_agent/shared/memory/index.ts | 4 ++-- .../fetch_service_paths_from_trace_ids.ts | 2 +- .../server/lib/service_map/get_service_anomalies.ts | 4 +++- .../service_map/get_service_map_service_node_info.ts | 4 +++- .../agent_configuration/create_agent_config_index.ts | 3 ++- .../settings/custom_link/create_custom_link_index.ts | 4 ++-- 8 files changed, 19 insertions(+), 18 deletions(-) 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 e2a39b521466a..3d5b4b754e4aa 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 9d7434d127ead..1544538de74a6 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 c58fb170bd2b0..0ec2f2c2fcfb2 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 64de74fb9023b..6047b97651e6a 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 4acff0acbfa3a..129a0ee73b8cb 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 @@ -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 c1dfed377a763..9850c36c573dd 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 7ec850717dab1..df181a36c0396 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 doesn't satisfy MappingDynamicTemplate 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 3965e363499fc..085bb2b4be40d 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', }, From f2f2749131c0e39cff616402fd5ccfa687f71656 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Fri, 4 Jun 2021 16:19:44 +0300 Subject: [PATCH 72/86] fix errors in fleet plugin --- .../server/routes/data_streams/handlers.ts | 2 +- .../fleet/server/services/agents/crud.ts | 6 ++-- .../fleet/server/services/agents/helpers.ts | 2 +- .../server/services/agents/reassign.test.ts | 2 +- .../server/services/agents/unenroll.test.ts | 30 +++++++++---------- .../services/api_keys/enrollment_api_key.ts | 1 - .../fleet/server/services/artifacts/mocks.ts | 1 + .../elasticsearch/template/install.test.ts | 1 + .../epm/elasticsearch/template/install.ts | 1 + .../epm/elasticsearch/template/template.ts | 3 +- 10 files changed, 25 insertions(+), 24 deletions(-) diff --git a/x-pack/plugins/fleet/server/routes/data_streams/handlers.ts b/x-pack/plugins/fleet/server/routes/data_streams/handlers.ts index b408d0908e768..b80ddfe8e7c9b 100644 --- a/x-pack/plugins/fleet/server/routes/data_streams/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/data_streams/handlers.ts @@ -33,7 +33,7 @@ interface ESDataStreamInfo { }; status: string; template: string; - ilm_policy: string; + ilm_policy?: string; hidden: boolean; } diff --git a/x-pack/plugins/fleet/server/services/agents/crud.ts b/x-pack/plugins/fleet/server/services/agents/crud.ts index b8ce7c36e507f..33f2a5cb120c8 100644 --- a/x-pack/plugins/fleet/server/services/agents/crud.ts +++ b/x-pack/plugins/fleet/server/services/agents/crud.ts @@ -140,7 +140,7 @@ export async function getAgentsByKuery( return { agents, - total: (res.body.hits.total as estypes.TotalHits).value, + total: (res.body.hits.total as estypes.SearchTotalHits).value, page, perPage, }; @@ -212,11 +212,11 @@ export async function getAgentById(esClient: ElasticsearchClient, agentId: strin export function isAgentDocument( maybeDocument: any -): maybeDocument is estypes.MultiGetHit { +): 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 c4273a57ddffd..822a2a9df98d5 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 63085b7729c4b..a87432c639249 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 33f12dc52dc00..3621bc5025ab3 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 511a0abecbc18..f9aab997f063c 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/artifacts/mocks.ts b/x-pack/plugins/fleet/server/services/artifacts/mocks.ts index 1a10f93f678b3..20d34285266ba 100644 --- a/x-pack/plugins/fleet/server/services/artifacts/mocks.ts +++ b/x-pack/plugins/fleet/server/services/artifacts/mocks.ts @@ -84,6 +84,7 @@ export const generateArtifactEsGetSingleHitMock = (): SearchHit { 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 9e8277eb6171f..d202dab54f5bd 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 5dd2755390ecb..07d0df021c827 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}`); From 0b46cbbe4a9fd83976804311bfbed7a641637dbb Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Fri, 4 Jun 2021 16:20:21 +0300 Subject: [PATCH 73/86] fix errors in infra plugin --- .../log_sources/resolved_log_source_configuration.ts | 6 +++--- .../logs/log_analysis/api/validate_datasets.ts | 2 +- .../logs/log_analysis/api/validate_indices.ts | 2 +- .../logs/log_analysis/log_analysis_module_types.ts | 6 +++--- .../modules/log_entry_categories/module_descriptor.ts | 4 ++-- .../use_log_entry_categories_module.tsx | 2 +- .../modules/log_entry_rate/module_descriptor.ts | 4 ++-- .../log_entry_rate/use_log_entry_rate_module.tsx | 2 +- .../lib/adapters/framework/kibana_framework_adapter.ts | 2 +- .../log_threshold/log_threshold_executor.test.ts | 4 ++-- .../alerting/log_threshold/log_threshold_executor.ts | 10 +++++----- .../domains/log_entries_domain/log_entries_domain.ts | 2 +- .../log_entries_domain/queries/log_entry_datasets.ts | 2 +- .../server/lib/log_analysis/log_entry_anomalies.ts | 2 +- .../lib/log_analysis/log_entry_categories_analysis.ts | 2 +- .../queries/log_entry_category_examples.ts | 2 +- .../lib/log_analysis/queries/log_entry_examples.ts | 2 +- .../server/routes/log_analysis/validation/datasets.ts | 2 +- .../server/services/log_entries/queries/log_entries.ts | 4 ++-- .../server/services/log_entries/queries/log_entry.ts | 4 ++-- 20 files changed, 33 insertions(+), 33 deletions(-) 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 77c7947ce22c3..ee831d9a98eb9 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 9eadc3035588d..9de6e574ecb5b 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 f9eb7609e00f3..a211fecc807fa 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 36371b080ee45..4ae99b95cfff8 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 981b7b496b435..af2bd1802042a 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 a2ad5cd4f56c4..86e8e75dc3d41 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 345f221f11c1f..9704afd80e9ea 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 b451cad1c8753..0df5d9b446dbe 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 d3ea162781b5d..2aede2f6aad16 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 1c1edb3ea8328..ffabd7ba65f03 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 3e910e5dfbf46..a537801202217 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 387143ef9f9c4..ad8650bbb0fb6 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 18e04aaf063d4..3431f3bfb0c8c 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 716ab400c0123..3210f01116f76 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 ee2441d591134..7739f39cb5624 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 f06dcd43a9156..0fef7dedfff0b 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 1e8cbe247dd50..ee339c9c6eb7e 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 950ecc98619ee..ef789c1b41349 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 6df17dbfd7bfd..d2966c26e2d6b 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 expects "runtime" 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 6bef317d96ada..56ee3b3a21853 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 expects "runtime" property runtime_mappings: runtimeMappings, sort: [{ [timestampField]: 'desc' }, { [tiebreakerField]: 'desc' }], _source: false, From 5a396550244c01868449f2b670c68cb960ca230d Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Fri, 4 Jun 2021 16:20:54 +0300 Subject: [PATCH 74/86] fix errors in monitoring plugin --- .../monitoring/server/lib/alerts/fetch_available_ccs.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 603c66d2d05f2..ca8270590da54 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, }) ); From 596e8f447029bea28a6b5cd2bcfb7749bb2c2e39 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Fri, 4 Jun 2021 16:21:24 +0300 Subject: [PATCH 75/86] fix errors in osquery plugin --- x-pack/plugins/osquery/public/agents/helpers.ts | 8 ++++---- x-pack/plugins/osquery/public/agents/types.ts | 4 ++-- .../factory/actions/results/query.action_results.dsl.ts | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/x-pack/plugins/osquery/public/agents/helpers.ts b/x-pack/plugins/osquery/public/agents/helpers.ts index a79933db0ceb0..df966a01f1de1 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 302b2686d511e..bfe59c91d007d 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 e8a8fbd63a84d..d74067bff0251 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, }, }, }, From 4e5e3d47536368d79b084c42afd8cc8137f11e8c Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Fri, 4 Jun 2021 16:22:31 +0300 Subject: [PATCH 76/86] fix errors in security solution plugins --- .../common/search_strategy/common/index.ts | 2 +- .../search_strategy/security_solution/index.ts | 2 +- .../endpoint/routes/metadata/query_builders.ts | 6 +++--- .../migrations/get_index_versions_by_index.test.ts | 2 +- .../migrations/migration_cleanup.ts | 2 +- .../lib/detection_engine/reference_rules/query.ts | 4 ++-- .../detection_engine/signals/build_events_query.ts | 13 ++++++------- .../signals/search_after_bulk_create.ts | 4 ++-- .../signals/signal_rule_alert_type.test.ts | 4 ++-- .../detection_engine/signals/single_search_after.ts | 5 ++--- .../signals/threat_mapping/create_threat_signals.ts | 2 +- .../server/lib/detection_engine/signals/utils.ts | 5 ++--- .../factory/hosts/authentications/dsl/query.dsl.ts | 2 +- .../hosts/authentications/dsl/query_entities.dsl.ts | 5 ++++- .../hosts/uncommon_processes/dsl/query.dsl.ts | 2 +- 15 files changed, 30 insertions(+), 30 deletions(-) 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 e27e9b5173fd5..4fcfbdac3c1b4 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/index.ts b/x-pack/plugins/security_solution/common/search_strategy/security_solution/index.ts index 936d9c360afb0..956b785079d8d 100644 --- a/x-pack/plugins/security_solution/common/search_strategy/security_solution/index.ts +++ b/x-pack/plugins/security_solution/common/search_strategy/security_solution/index.ts @@ -83,7 +83,7 @@ export interface RequestBasicOptions extends IEsSearchRequest { timerange: TimerangeInput; filterQuery: ESQuery | string | undefined; defaultIndex: string[]; - docValueFields?: estypes.DocValueField[]; + docValueFields?: estypes.SearchDocValueField[]; factoryQueryType?: FactoryQueryTypes; } diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.ts index 51e3495938606..f0950e5fb79ba 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { SearchRequest, SortContainer } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { KibanaRequest } from '../../../../../../../src/core/server'; import { esKuery } from '../../../../../../../src/plugins/data/server'; import { EndpointAppContext, MetadataQueryStrategy } from '../../types'; @@ -20,7 +20,7 @@ export interface QueryBuilderOptions { // using unmapped_type avoids errors when the given field doesn't exist, and sets to the 0-value for that type // effectively ignoring it // https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html#_ignoring_unmapped_fields -const MetadataSortMethod: SortContainer[] = [ +const MetadataSortMethod: estypes.SearchSortContainer[] = [ { 'event.created': { order: 'desc', @@ -147,7 +147,7 @@ function buildQueryBody( export function getESQueryHostMetadataByID( agentID: string, metadataQueryStrategy: MetadataQueryStrategy -): SearchRequest { +): estypes.SearchRequest { return { body: { query: { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/get_index_versions_by_index.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/get_index_versions_by_index.test.ts index 8e99cb32390e1..32b3ccbf17b57 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/get_index_versions_by_index.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/get_index_versions_by_index.test.ts @@ -43,9 +43,9 @@ describe('getIndexVersionsByIndex', () => { }); 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 9c40778d46704..00446a204ca89 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 3911dcabc34de..04bfa78f883f0 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 86fb51e4785ad..43b9495101fa7 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,9 +92,9 @@ export const buildEventsSearchQuery = ({ }, ]; - const filterWithTime: estypes.QueryContainer[] = [ + const filterWithTime: estypes.QueryDslQueryContainer[] = [ // but tests contain undefined, so I suppose it's desired behaviour - // @ts-expect-error undefined in not assignable to QueryContainer + // @ts-expect-error undefined in not assignable to QueryDslQueryContainer filter, { bool: { filter: [{ bool: { should: [...rangeFilter], minimum_should_match: 1 } }] } }, ]; 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 08f8abe384d0f..b0dcc1810a639 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 66f7d41df94ab..823d694f36514 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 ae99b308040e9..e4f96511dc942 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, @@ -24,7 +23,7 @@ import { interface SingleSearchAfterParams { aggregations?: Record; - searchAfterSortIds: SortResults | undefined; + searchAfterSortIds: estypes.SearchSortResults | undefined; index: string[]; from: string; to: string; @@ -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 ade85db0e4ba6..b3e0e376c7794 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/utils.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts index cc4ed6a45807b..5c35a3488dab7 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'; @@ -855,10 +854,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 e960067713bda..325d45e04b2b0 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 51d80152d65c0..d320130115588 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/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 97f0fc6f2efe0..5d4f45c68160a 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: { From 4d562e52d5d984aef5b963a1dd883297eeecb94b Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Fri, 4 Jun 2021 16:23:00 +0300 Subject: [PATCH 77/86] fix errors in transform plugin --- x-pack/plugins/transform/common/api_schemas/type_guards.ts | 2 +- x-pack/plugins/transform/public/app/hooks/use_index_data.ts | 2 +- .../common/filter_agg/components/filter_term_form.tsx | 4 +++- .../plugins/transform/server/routes/api/field_histograms.ts | 1 - x-pack/plugins/transform/server/routes/api/transforms.ts | 6 +++++- 5 files changed, 10 insertions(+), 5 deletions(-) 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 4b66de9be20d2..1f27f1798c8e7 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 bd1ecd79f4d12..55a304207a1c7 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 358bb9dcafa96..da7100a31167a 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 bb2a1b278a5c2..bfe2f47078569 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 34ae3f42d8622..ea2bb28776ac2 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, @@ -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) { From 7eec0dd4156efa00b8d31453e0762f333efc9218 Mon Sep 17 00:00:00 2001 From: Dario Gieselaar Date: Mon, 7 Jun 2021 10:35:02 +0200 Subject: [PATCH 78/86] Update type imports for ES --- typings/elasticsearch/search.d.ts | 6 +++--- .../tests/service_overview/dependencies/es_utils.ts | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/typings/elasticsearch/search.d.ts b/typings/elasticsearch/search.d.ts index 4a8fff05bbc1b..36a684fb097a5 100644 --- a/typings/elasticsearch/search.d.ts +++ b/typings/elasticsearch/search.d.ts @@ -35,7 +35,7 @@ type CompositeKeysOf< ? KeysOfSources : unknown; -type Source = estypes.SourceFilter | boolean | estypes.Fields; +type Source = estypes.SearchSourceFilter | boolean | estypes.Fields; type ValueTypeOfField = T extends Record ? ValuesType @@ -50,7 +50,7 @@ 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, @@ -524,7 +524,7 @@ 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.SearchHitsMetadata; }; 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 dbbc8ebc87958..b1663ea714056 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', From b36574a5ead3f9822a9e7b9c1cee0bb5d995458f Mon Sep 17 00:00:00 2001 From: restrry Date: Mon, 7 Jun 2021 12:24:34 +0300 Subject: [PATCH 79/86] fix errors in x-pack plugins --- x-pack/plugins/fleet/server/services/artifacts/mocks.ts | 1 - .../stack_alerts/server/alert_types/es_query/alert_type.test.ts | 1 - 2 files changed, 2 deletions(-) diff --git a/x-pack/plugins/fleet/server/services/artifacts/mocks.ts b/x-pack/plugins/fleet/server/services/artifacts/mocks.ts index 20d34285266ba..1a10f93f678b3 100644 --- a/x-pack/plugins/fleet/server/services/artifacts/mocks.ts +++ b/x-pack/plugins/fleet/server/services/artifacts/mocks.ts @@ -84,7 +84,6 @@ export const generateArtifactEsGetSingleHitMock = (): SearchHit Date: Mon, 7 Jun 2021 12:24:48 +0300 Subject: [PATCH 80/86] fix errors in tests --- .../api_integration/apis/saved_objects/migrations.ts | 12 ++++++------ test/common/services/saved_object_info.ts | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/test/api_integration/apis/saved_objects/migrations.ts b/test/api_integration/apis/saved_objects/migrations.ts index d009a66e9df55..0877998ca6c1f 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/common/services/saved_object_info.ts b/test/common/services/saved_object_info.ts index 1558b364f5391..2be1763650894 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) { From 3909a74af67f82d6a037148c6eec49b200ec085f Mon Sep 17 00:00:00 2001 From: restrry Date: Mon, 7 Jun 2021 12:29:59 +0300 Subject: [PATCH 81/86] update docs --- ...-plugin-plugins-data-public.indexpattern.addscriptedfield.md | 1 + ...gin-plugins-data-public.indexpattern.getnonscriptedfields.md | 1 + ...plugin-plugins-data-public.indexpattern.getscriptedfields.md | 1 + ...ugin-plugins-data-public.indexpattern.removescriptedfield.md | 1 + ...-plugin-plugins-data-server.indexpattern.addscriptedfield.md | 1 + ...gin-plugins-data-server.indexpattern.getnonscriptedfields.md | 1 + ...plugin-plugins-data-server.indexpattern.getscriptedfields.md | 1 + ...ugin-plugins-data-server.indexpattern.removescriptedfield.md | 1 + src/plugins/data/public/public.api.md | 2 -- src/plugins/data/server/server.api.md | 2 -- 10 files changed, 8 insertions(+), 4 deletions(-) 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 812f014b15a6c..e0ee1f0ec15a4 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 1792a979bf749..94adbefe535dd 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 b6b3dcb19bac1..57e1b5f49371b 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 91f25c09ab197..d3e1b26810fd7 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/server/kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md index 981f28a51ae09..33f1ac5e31660 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 cff2c5de98de6..e791dfc7c3738 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 62b8f1b62ac78..95f9f31309674 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 f6beed7389e43..b351eba2ace4f 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/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md index 823119f99c972..5ef499840fa6d 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'; diff --git a/src/plugins/data/server/server.api.md b/src/plugins/data/server/server.api.md index 1c48f4cd62098..ff265ccf53301 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'; From 635a2c3b31935b4c335f8c8fafab915a72c81067 Mon Sep 17 00:00:00 2001 From: restrry Date: Mon, 7 Jun 2021 14:32:49 +0300 Subject: [PATCH 82/86] fix errors in x-pack/test --- x-pack/test/accessibility/apps/ml.ts | 1 - x-pack/test/api_integration/apis/lens/telemetry.ts | 2 -- .../api_integration/apis/ml/calendars/create_calendars.ts | 6 +----- .../api_integration/apis/ml/calendars/delete_calendars.ts | 1 - .../test/api_integration/apis/ml/calendars/get_calendars.ts | 6 ------ .../api_integration/apis/ml/calendars/update_calendars.ts | 2 -- x-pack/test/api_integration/apis/ml/jobs/jobs_summary.ts | 4 ++-- x-pack/test/api_integration/apis/security/roles.ts | 1 - .../apis/upgrade_assistant/upgrade_assistant.ts | 1 + x-pack/test/case_api_integration/common/lib/utils.ts | 5 ----- .../security_and_spaces/tests/delete_signals_migrations.ts | 1 + x-pack/test/detection_engine_api_integration/utils.ts | 2 -- .../tests/encrypted_saved_objects_api.ts | 2 -- .../fleet_api_integration/apis/enrollment_api_keys/crud.ts | 1 - .../test/functional/apps/ml/permissions/read_ml_access.ts | 1 - x-pack/test/functional/apps/ml/settings/calendar_edit.ts | 1 - x-pack/test/functional_with_es_ssl/apps/ml/alert_flyout.ts | 4 ++-- x-pack/test/lists_api_integration/utils.ts | 1 - .../test_suites/task_manager/task_management.ts | 3 ++- .../fixtures/saved_object_test_plugin/server/plugin.ts | 2 +- 20 files changed, 10 insertions(+), 37 deletions(-) diff --git a/x-pack/test/accessibility/apps/ml.ts b/x-pack/test/accessibility/apps/ml.ts index 41f8d5e56f8e6..5436f74a2b8f9 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 32b6a446a57b2..be1760d129df7 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 01b87e6059a29..fac62237aa74e 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 dfbffad9dafdd..a2e1709731aa7 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 175c678317e6c..243a40abe97a4 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/update_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts index 4798a3407be11..1ca9a66319943 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 a0c00770f84dc..4e3be92a54b6a 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 09b2d2eef9fbe..440bb4ca32f18 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 7041427fb74d7..0eb0b98e29ffe 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/case_api_integration/common/lib/utils.ts b/x-pack/test/case_api_integration/common/lib/utils.ts index e073c25727be2..ca770d9928f49 100644 --- a/x-pack/test/case_api_integration/common/lib/utils.ts +++ b/x-pack/test/case_api_integration/common/lib/utils.ts @@ -352,7 +352,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, @@ -363,7 +362,6 @@ export const deleteCasesUserActions = async (es: KibanaClient): Promise => export const deleteCases = 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, @@ -378,7 +376,6 @@ export const deleteCases = 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, @@ -389,7 +386,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, @@ -400,7 +396,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, 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 9bb3e776f4553..8c4ad5a2e8117 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 9c5beebd64b3d..7456040a436a4 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 f6b0f4e825097..9ee92a8a1848f 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 25fb71ae42807..b38458f7334c4 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/read_ml_access.ts b/x-pack/test/functional/apps/ml/permissions/read_ml_access.ts index 55cfb035d0cfe..5e6e179a7bdcc 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 1237cd8d71b8c..a643c4eb34299 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_with_es_ssl/apps/ml/alert_flyout.ts b/x-pack/test/functional_with_es_ssl/apps/ml/alert_flyout.ts index 1a8395a1b49df..2c80f4b2ebd91 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 2467e613ca2f5..90103ec8b856c 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 26333ecabd505..b8ba9c93fe8b0 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 e29bbc0db56b6..36bbbb4bb8755 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', From 5e6ec78e52996636a46d85d8c71304b6ac9f583f Mon Sep 17 00:00:00 2001 From: restrry Date: Mon, 7 Jun 2021 16:03:21 +0300 Subject: [PATCH 83/86] update error description --- .../settings/agent_configuration/create_agent_config_index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 df181a36c0396..f43938891f1f0 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,7 +36,7 @@ const mappings: Mappings = { dynamic_templates: [ { // force string to keyword (instead of default of text + keyword) - // @ts-expect-error doesn't satisfy MappingDynamicTemplate + // @ts-expect-error @elastic/elasticsearch expects here mapping: MappingPropertyBase strings: { match_mapping_type: 'string', mapping: { From 7304b6ccfd7189850cb43137fe90fe7866d3ba14 Mon Sep 17 00:00:00 2001 From: restrry Date: Tue, 8 Jun 2021 12:21:36 +0300 Subject: [PATCH 84/86] fix errors after master merge --- .../service/lib/aggregations/validation_utils.test.ts | 3 +-- x-pack/plugins/cases/server/services/cases/index.ts | 6 ++++-- 2 files changed, 5 insertions(+), 4 deletions(-) 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 456c898f66534..0425e46b4477e 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', diff --git a/x-pack/plugins/cases/server/services/cases/index.ts b/x-pack/plugins/cases/server/services/cases/index.ts index 196314a0ecbfb..5618f6c83ff06 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`, From 13cca1f6fbe0a51fa57692bd295016ba41f0e567 Mon Sep 17 00:00:00 2001 From: restrry Date: Tue, 8 Jun 2021 12:41:39 +0300 Subject: [PATCH 85/86] update comment in infra plugin --- .../infra/server/services/log_entries/queries/log_entries.ts | 2 +- .../infra/server/services/log_entries/queries/log_entry.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 d2966c26e2d6b..9022195dce85d 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 @@ -53,7 +53,7 @@ export const createGetLogEntriesQuery = ( }, }, fields, - // @ts-expect-error @elastic/elasticsearch expects "runtime" property + // @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 56ee3b3a21853..8da2f1d685db3 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 @@ -32,7 +32,7 @@ export const createGetLogEntryQuery = ( }, }, fields: ['*'], - // @ts-expect-error @elastic/elasticsearch expects "runtime" property + // @ts-expect-error @elastic/elasticsearch doesn't declare "runtime_mappings" property runtime_mappings: runtimeMappings, sort: [{ [timestampField]: 'desc' }, { [tiebreakerField]: 'desc' }], _source: false, From 6e549edfe44226e48193be2769a19e8f2422a77e Mon Sep 17 00:00:00 2001 From: restrry Date: Tue, 8 Jun 2021 14:01:08 +0300 Subject: [PATCH 86/86] fix new errors on xpack tests/ --- x-pack/test/case_api_integration/common/lib/utils.ts | 1 - 1 file changed, 1 deletion(-) 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 1b3b9cbdd72fb..9ed5d84e54621 100644 --- a/x-pack/test/case_api_integration/common/lib/utils.ts +++ b/x-pack/test/case_api_integration/common/lib/utils.ts @@ -532,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,