From 4f83c0f35cf4c739188f69568c37a996013930e0 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Fri, 12 May 2023 11:15:29 +0200 Subject: [PATCH 01/15] optimize reduce usages for core --- .../src/http_config.ts | 10 +++++----- .../src/node_service.ts | 3 ++- .../src/lib/aggregations/validation.ts | 8 +++----- .../src/lib/search_dsl/query_params.ts | 2 +- .../src/import/saved_objects_importer.ts | 5 +---- .../src/core/build_types_mappings.ts | 8 +++----- .../build_active_migrations.ts | 9 +++------ .../document_migrator/document_migrator.ts | 19 +++++++++++-------- 8 files changed, 29 insertions(+), 35 deletions(-) diff --git a/packages/core/http/core-http-server-internal/src/http_config.ts b/packages/core/http/core-http-server-internal/src/http_config.ts index 53417d9c533f8..37736700ebf47 100644 --- a/packages/core/http/core-http-server-internal/src/http_config.ts +++ b/packages/core/http/core-http-server-internal/src/http_config.ts @@ -244,12 +244,12 @@ export class HttpConfig implements IHttpConfig { this.securityResponseHeaders = securityResponseHeaders; this.customResponseHeaders = Object.entries(rawHttpConfig.customResponseHeaders ?? {}).reduce( (headers, [key, value]) => { - return { - ...headers, - [key]: Array.isArray(value) ? value.map((e) => convertHeader(e)) : convertHeader(value), - }; + headers[key] = Array.isArray(value) + ? value.map((e) => convertHeader(e)) + : convertHeader(value); + return headers; }, - {} + {} as Record ); this.maxPayload = rawHttpConfig.maxPayload; this.name = rawHttpConfig.name; diff --git a/packages/core/node/core-node-server-internal/src/node_service.ts b/packages/core/node/core-node-server-internal/src/node_service.ts index d84582d57e892..c8b3618aee611 100644 --- a/packages/core/node/core-node-server-internal/src/node_service.ts +++ b/packages/core/node/core-node-server-internal/src/node_service.ts @@ -70,7 +70,8 @@ export class NodeService { // We assume the combination of node roles has been validated and avoid doing additional checks here. this.roles = NODE_ALL_ROLES.reduce((acc, curr) => { - return { ...acc, [camelCase(curr)]: (roles as string[]).includes(curr) }; + acc[camelCase(curr) as keyof NodeRoles] = (roles as string[]).includes(curr); + return acc; }, {} as NodeRoles); return { diff --git a/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/aggregations/validation.ts b/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/aggregations/validation.ts index c673f73d8d844..d76f6023f663a 100644 --- a/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/aggregations/validation.ts +++ b/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/aggregations/validation.ts @@ -194,11 +194,9 @@ const recursiveRewrite = ( newValue = recursiveRewrite(value, nestedContext, [...parents, key]); } - return { - ...memo, - [newKey]: newValue, - }; - }, {}); + memo[newKey] = newValue; + return memo; + }, {} as Record); }; const childContext = (context: ValidationContext, path: string): ValidationContext => { diff --git a/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/search_dsl/query_params.ts b/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/search_dsl/query_params.ts index 896b934c90b80..14875a7cfdc6b 100644 --- a/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/search_dsl/query_params.ts +++ b/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/search_dsl/query_params.ts @@ -291,7 +291,7 @@ const getMatchPhrasePrefixFields = ({ fields = types.reduce((typeFields, type) => { const defaultSearchField = registry.getType(type)?.management?.defaultSearchField; if (defaultSearchField) { - return [...typeFields, `${type}.${defaultSearchField}`]; + typeFields.push(`${type}.${defaultSearchField}`); } return typeFields; }, [] as string[]); diff --git a/packages/core/saved-objects/core-saved-objects-import-export-server-internal/src/import/saved_objects_importer.ts b/packages/core/saved-objects/core-saved-objects-import-export-server-internal/src/import/saved_objects_importer.ts index 2c87395c255cd..d6ceeb7fd87cb 100644 --- a/packages/core/saved-objects/core-saved-objects-import-export-server-internal/src/import/saved_objects_importer.ts +++ b/packages/core/saved-objects/core-saved-objects-import-export-server-internal/src/import/saved_objects_importer.ts @@ -41,10 +41,7 @@ export class SavedObjectsImporter implements ISavedObjectsImporter { this.#importSizeLimit = importSizeLimit; this.#importHooks = typeRegistry.getAllTypes().reduce((hooks, type) => { if (type.management?.onImport) { - return { - ...hooks, - [type.name]: [type.management.onImport], - }; + hooks[type.name] = [type.management.onImport]; } return hooks; }, {} as Record); diff --git a/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/core/build_types_mappings.ts b/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/core/build_types_mappings.ts index 6c78ae52550c5..18aa689149c24 100644 --- a/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/core/build_types_mappings.ts +++ b/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/core/build_types_mappings.ts @@ -15,14 +15,12 @@ import type { SavedObjectsTypeMappingDefinitions } from '@kbn/core-saved-objects export const buildTypesMappings = ( types: SavedObjectsType[] ): SavedObjectsTypeMappingDefinitions => { - return types.reduce((acc, { name: type, mappings }) => { + return types.reduce((acc, { name: type, mappings }) => { const duplicate = acc.hasOwnProperty(type); if (duplicate) { throw new Error(`Type ${type} is already defined.`); } - return { - ...acc, - [type]: mappings, - }; + acc[type] = mappings; + return acc; }, {}); }; diff --git a/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/document_migrator/build_active_migrations.ts b/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/document_migrator/build_active_migrations.ts index d09e9996be64d..2183a5fb5e4ad 100644 --- a/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/document_migrator/build_active_migrations.ts +++ b/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/document_migrator/build_active_migrations.ts @@ -50,14 +50,11 @@ export function buildActiveMigrations({ referenceTransforms, }); - if (!typeTransforms.transforms.length) { - return migrations; + if (typeTransforms.transforms.length) { + migrations[type.name] = typeTransforms; } - return { - ...migrations, - [type.name]: typeTransforms, - }; + return migrations; }, {} as ActiveMigrations); } diff --git a/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/document_migrator/document_migrator.ts b/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/document_migrator/document_migrator.ts index 2d10ff278e7c6..eb80f29a86416 100644 --- a/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/document_migrator/document_migrator.ts +++ b/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/document_migrator/document_migrator.ts @@ -78,14 +78,17 @@ export class DocumentMigrator implements VersionedTransformer { throw new Error('Migrations are not ready. Make sure prepareMigrations is called first.'); } - return Object.entries(this.migrations).reduce((acc, [prop, { latestVersion }]) => { - // some migration objects won't have a latest migration version (they only contain reference transforms that are applied from other types) - const latestMigrationVersion = maxVersion(latestVersion.migrate, latestVersion.convert); - if (latestMigrationVersion) { - return { ...acc, [prop]: latestMigrationVersion }; - } - return acc; - }, {}); + return Object.entries(this.migrations).reduce( + (acc, [prop, { latestVersion }]) => { + // some migration objects won't have a latest migration version (they only contain reference transforms that are applied from other types) + const latestMigrationVersion = maxVersion(latestVersion.migrate, latestVersion.convert); + if (latestMigrationVersion) { + acc[prop] = latestMigrationVersion; + } + return acc; + }, + {} + ); } /** From a5eadbd0849443dee1aaca516f8f02d2f1d677e5 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Fri, 12 May 2023 12:04:01 +0200 Subject: [PATCH 02/15] optimize reduce usages for oss plugins --- .../public/utils/layers/sort_predicate.ts | 11 ++--- .../expression_xy/public/helpers/layers.ts | 19 ++++---- .../services/spec_definitions_service.ts | 8 ++-- .../options_list_cheap_suggestion_queries.ts | 12 +++-- ...tions_list_expensive_suggestion_queries.ts | 9 ++-- .../search/expressions/es_raw_response.ts | 5 ++- .../search/collectors/search_session/fetch.ts | 3 +- .../field_capabilities/field_caps_response.ts | 11 ++--- .../hooks/use_form_is_modified.ts | 8 ++-- .../static/forms/hook_form_lib/lib/utils.ts | 7 +-- .../validators/string/contains_chars.ts | 10 +++-- .../common/fetch_event_annotations/utils.ts | 8 ++-- .../expression_renderer_registry.ts | 11 ++--- .../application_usage/rollups/total.ts | 39 ++++++++-------- .../telemetry_application_usage_collector.ts | 44 +++++++++---------- .../server/telemetry_collection/get_kibana.ts | 13 +++--- .../public/service/ui_actions_service.ts | 10 +++-- .../usage_counters/usage_counters_service.ts | 12 +++-- .../default_search_capabilities.ts | 15 +++---- .../rollup_search_capabilities.ts | 11 ++--- 20 files changed, 128 insertions(+), 138 deletions(-) diff --git a/src/plugins/chart_expressions/expression_partition_vis/public/utils/layers/sort_predicate.ts b/src/plugins/chart_expressions/expression_partition_vis/public/utils/layers/sort_predicate.ts index b5992c3b600bf..d33281a0500c2 100644 --- a/src/plugins/chart_expressions/expression_partition_vis/public/utils/layers/sort_predicate.ts +++ b/src/plugins/chart_expressions/expression_partition_vis/public/utils/layers/sort_predicate.ts @@ -22,13 +22,10 @@ type SortPredicatePieDonutFn = (visParams: PartitionVisParams) => SortFn; type SortPredicatePureFn = () => SortFn; export const extractUniqTermsMap = (dataTable: Datatable, columnId: string) => - [...new Set(dataTable.rows.map((item) => item[columnId]))].reduce( - (acc, item, index) => ({ - ...acc, - [item]: index, - }), - {} - ); + [...new Set(dataTable.rows.map((item) => item[columnId]))].reduce((acc, item, index) => { + acc[item] = index; + return acc; + }, {}); export const sortPredicateSaveSourceOrder: SortPredicatePureFn = () => diff --git a/src/plugins/chart_expressions/expression_xy/public/helpers/layers.ts b/src/plugins/chart_expressions/expression_xy/public/helpers/layers.ts index 7dc26e4c76cf1..df45158cf6432 100644 --- a/src/plugins/chart_expressions/expression_xy/public/helpers/layers.ts +++ b/src/plugins/chart_expressions/expression_xy/public/helpers/layers.ts @@ -153,17 +153,18 @@ export const getLayerFormats = ( }), {} ), - splitSeriesAccessors: splitColumnAccessors?.reduce((formatters, splitAccessor) => { - const formatObj = getAccessorWithFieldFormat(splitAccessor, table.columns); - const accessor = Object.keys(formatObj)[0]; - return { - ...formatters, - [accessor]: { + splitSeriesAccessors: splitColumnAccessors?.reduce( + (formatters, splitAccessor) => { + const formatObj = getAccessorWithFieldFormat(splitAccessor, table.columns); + const accessor = Object.keys(formatObj)[0]; + formatters[accessor] = { format: formatObj[accessor], formatter: formatFactory(formatObj[accessor]), - }, - }; - }, {}), + }; + return formatters; + }, + {} + ), splitColumnAccessors: getAccessorWithFieldFormat(splitColumnAccessor, table.columns), splitRowAccessors: getAccessorWithFieldFormat(splitRowAccessor, table.columns), }; diff --git a/src/plugins/console/server/services/spec_definitions_service.ts b/src/plugins/console/server/services/spec_definitions_service.ts index b978c3c326159..ece2695947fe3 100644 --- a/src/plugins/console/server/services/spec_definitions_service.ts +++ b/src/plugins/console/server/services/spec_definitions_service.ts @@ -128,17 +128,15 @@ export class SpecDefinitionsService { if (overrideFile) { merge(loadedSpec, JSON.parse(readFileSync(overrideFile, 'utf8'))); } - const spec: Record = {}; Object.entries(loadedSpec).forEach(([key, value]) => { if (acc[key]) { // add time to remove key collision - spec[`${key}${Date.now()}`] = value; + acc[`${key}${Date.now()}`] = value; } else { - spec[key] = value; + acc[key] = value; } }); - - return { ...acc, ...spec }; + return acc; }, {} as Record); } diff --git a/src/plugins/controls/server/options_list/options_list_cheap_suggestion_queries.ts b/src/plugins/controls/server/options_list/options_list_cheap_suggestion_queries.ts index 3b69b2818b909..f716f2b0b3373 100644 --- a/src/plugins/controls/server/options_list/options_list_cheap_suggestion_queries.ts +++ b/src/plugins/controls/server/options_list/options_list_cheap_suggestion_queries.ts @@ -53,7 +53,8 @@ const cheapSuggestionAggSubtypes: { [key: string]: OptionsListSuggestionAggregat parse: (rawEsResult) => ({ suggestions: get(rawEsResult, 'aggregations.suggestions.buckets')?.reduce( (acc: OptionsListSuggestions, suggestion: EsBucket) => { - return [...acc, { value: suggestion.key, docCount: suggestion.doc_count }]; + acc.push({ value: suggestion.key, docCount: suggestion.doc_count }); + return acc; }, [] ), @@ -76,7 +77,8 @@ const cheapSuggestionAggSubtypes: { [key: string]: OptionsListSuggestionAggregat parse: (rawEsResult) => ({ suggestions: get(rawEsResult, 'aggregations.suggestions.buckets')?.reduce( (acc: OptionsListSuggestions, suggestion: EsBucket & { key_as_string: string }) => { - return [...acc, { value: suggestion.key_as_string, docCount: suggestion.doc_count }]; + acc.push({ value: suggestion.key_as_string, docCount: suggestion.doc_count }); + return acc; }, [] ), @@ -151,7 +153,8 @@ const cheapSuggestionAggSubtypes: { [key: string]: OptionsListSuggestionAggregat suggestions: sortedSuggestions .slice(0, 10) // only return top 10 results .reduce((acc: OptionsListSuggestions, suggestion: EsBucket) => { - return [...acc, { value: suggestion.key, docCount: suggestion.doc_count }]; + acc.push({ value: suggestion.key, docCount: suggestion.doc_count }); + return acc; }, []), }; }, @@ -189,7 +192,8 @@ const cheapSuggestionAggSubtypes: { [key: string]: OptionsListSuggestionAggregat parse: (rawEsResult) => ({ suggestions: get(rawEsResult, 'aggregations.nestedSuggestions.suggestions.buckets')?.reduce( (acc: OptionsListSuggestions, suggestion: EsBucket) => { - return [...acc, { value: suggestion.key, docCount: suggestion.doc_count }]; + acc.push({ value: suggestion.key, docCount: suggestion.doc_count }); + return acc; }, [] ), diff --git a/src/plugins/controls/server/options_list/options_list_expensive_suggestion_queries.ts b/src/plugins/controls/server/options_list/options_list_expensive_suggestion_queries.ts index a1114191d1fa8..22025ec480605 100644 --- a/src/plugins/controls/server/options_list/options_list_expensive_suggestion_queries.ts +++ b/src/plugins/controls/server/options_list/options_list_expensive_suggestion_queries.ts @@ -93,7 +93,8 @@ const expensiveSuggestionAggSubtypes: { [key: string]: OptionsListSuggestionAggr const suggestions = get(rawEsResult, `${basePath}.suggestions.buckets`)?.reduce( (acc: OptionsListSuggestions, suggestion: EsBucket) => { - return [...acc, { value: suggestion.key, docCount: suggestion.doc_count }]; + acc.push({ value: suggestion.key, docCount: suggestion.doc_count }); + return acc; }, [] ); @@ -120,7 +121,8 @@ const expensiveSuggestionAggSubtypes: { [key: string]: OptionsListSuggestionAggr parse: (rawEsResult) => { const suggestions = get(rawEsResult, 'aggregations.suggestions.buckets')?.reduce( (acc: OptionsListSuggestions, suggestion: EsBucket & { key_as_string: string }) => { - return [...acc, { value: suggestion.key_as_string, docCount: suggestion.doc_count }]; + acc.push({ value: suggestion.key_as_string, docCount: suggestion.doc_count }); + return acc; }, [] ); @@ -200,7 +202,8 @@ const expensiveSuggestionAggSubtypes: { [key: string]: OptionsListSuggestionAggr const suggestions = sortedSuggestions .slice(0, request.size) .reduce((acc: OptionsListSuggestions, suggestion: EsBucket) => { - return [...acc, { value: suggestion.key, docCount: suggestion.doc_count }]; + acc.push({ value: suggestion.key, docCount: suggestion.doc_count }); + return acc; }, []); const totalCardinality = (get(rawEsResult, `aggregations.suggestions.buckets.ipv4.unique_terms.value`) ?? 0) + diff --git a/src/plugins/data/common/search/expressions/es_raw_response.ts b/src/plugins/data/common/search/expressions/es_raw_response.ts index 6853eba6a9bc7..6a7698497155e 100644 --- a/src/plugins/data/common/search/expressions/es_raw_response.ts +++ b/src/plugins/data/common/search/expressions/es_raw_response.ts @@ -26,7 +26,10 @@ function flatten(obj: any, keyPrefix = '') { nestedRows.push( ...obj[key] .map((nestedRow: any) => flatten(nestedRow, prefix + key)) - .reduce((acc: any, object: any) => [...acc, ...object], []) + .reduce((acc: unknown[], object: unknown[]) => { + acc.push(...object); + return acc; + }, []) ); } else if (typeof obj[key] === 'object' && obj[key] !== null) { const subRows = flatten(obj[key], prefix + key); diff --git a/src/plugins/data/server/search/collectors/search_session/fetch.ts b/src/plugins/data/server/search/collectors/search_session/fetch.ts index 08660f4adb136..aaa83bf5b808e 100644 --- a/src/plugins/data/server/search/collectors/search_session/fetch.ts +++ b/src/plugins/data/server/search/collectors/search_session/fetch.ts @@ -48,7 +48,8 @@ export function fetchProvider(getIndexForType: (type: string) => Promise const { transientCount = 0, persistedCount = 0 } = buckets.reduce( (usage: Partial, bucket: SessionPersistedTermsBucket) => { const key = bucket.key_as_string === 'false' ? 'transientCount' : 'persistedCount'; - return { ...usage, [key]: bucket.doc_count }; + usage[key] = bucket.doc_count; + return usage; }, {} ); diff --git a/src/plugins/data_views/server/fetcher/lib/field_capabilities/field_caps_response.ts b/src/plugins/data_views/server/fetcher/lib/field_capabilities/field_caps_response.ts index e21443546bad3..0cf2e460d35f5 100644 --- a/src/plugins/data_views/server/fetcher/lib/field_capabilities/field_caps_response.ts +++ b/src/plugins/data_views/server/fetcher/lib/field_capabilities/field_caps_response.ts @@ -110,13 +110,10 @@ export function readFieldCapsResponse( searchable: isSearchable, aggregatable: isAggregatable, readFromDocValues: false, - conflictDescriptions: types.reduce( - (acc, esType) => ({ - ...acc, - [esType]: capsByType[esType].indices, - }), - {} - ), + conflictDescriptions: types.reduce((acc, esType) => { + acc[esType] = capsByType[esType].indices; + return acc; + }, {} as Record), metadata_field: capsByType[types[0]].metadata_field, }; // This is intentionally using a "hash" and a "push" to be highly optimized with very large indexes diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form_is_modified.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form_is_modified.ts index ea8b1602711c1..b84ebb4581db4 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form_is_modified.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form_is_modified.ts @@ -61,10 +61,10 @@ export const useFormIsModified = ({ return; } - return fieldPathsToDiscard.reduce( - (acc, path) => ({ ...acc, [path]: true }), - {} as { [key: string]: {} } - ); + return fieldPathsToDiscard.reduce((acc, path) => { + acc[path] = true; + return acc; + }, {} as { [key: string]: {} }); // discardArrayToString === discard, we don't want to add it to the dependencies so // the consumer does not need to memoize the "discard" array they provide. diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/utils.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/utils.ts index fe41de2947795..4d2fcd4e8f7d8 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/utils.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/utils.ts @@ -67,10 +67,11 @@ export const stripOutUndefinedValues = (obj: GenericObject): R => { .filter(({ 1: value }) => value !== undefined) .reduce((acc, [key, value]) => { if (typeof value === 'object' && value !== null && !Array.isArray(value)) { - return { ...acc, [key]: stripOutUndefinedValues(value) }; + acc[key as keyof R] = stripOutUndefinedValues(value); + } else { + acc[key as keyof R] = value; } - - return { ...acc, [key]: value }; + return acc; }, {} as R); }; diff --git a/src/plugins/es_ui_shared/static/validators/string/contains_chars.ts b/src/plugins/es_ui_shared/static/validators/string/contains_chars.ts index 6a8e297e6bf98..320448515a8c7 100644 --- a/src/plugins/es_ui_shared/static/validators/string/contains_chars.ts +++ b/src/plugins/es_ui_shared/static/validators/string/contains_chars.ts @@ -9,10 +9,12 @@ export const containsChars = (chars: string | string[]) => (value: string) => { const charToArray = Array.isArray(chars) ? (chars as string[]) : ([chars] as string[]); - const charsFound = charToArray.reduce( - (acc, char) => (value.includes(char) ? [...acc, char] : acc), - [] as string[] - ); + const charsFound = charToArray.reduce((acc, char) => { + if (value.includes(char)) { + acc.push(char); + } + return acc; + }, [] as string[]); return { charsFound, diff --git a/src/plugins/event_annotation/common/fetch_event_annotations/utils.ts b/src/plugins/event_annotation/common/fetch_event_annotations/utils.ts index 7af00db63160e..b8658b8b81565 100644 --- a/src/plugins/event_annotation/common/fetch_event_annotations/utils.ts +++ b/src/plugins/event_annotation/common/fetch_event_annotations/utils.ts @@ -179,10 +179,10 @@ export const postprocessAnnotations = ( let extraFields: Record = {}; if (annotationConfig?.extraFields?.length) { - extraFields = annotationConfig.extraFields.reduce( - (acc, field) => ({ ...acc, [`field:${field}`]: row[fieldsColIdMap[field]] }), - {} - ); + extraFields = annotationConfig.extraFields.reduce((acc, field) => { + acc[`field:${field}`] = row[fieldsColIdMap[field]]; + return acc; + }, {} as typeof extraFields); } if (annotationConfig?.textField) { extraFields[`field:${annotationConfig.textField}`] = diff --git a/src/plugins/expressions/common/expression_renderers/expression_renderer_registry.ts b/src/plugins/expressions/common/expression_renderers/expression_renderer_registry.ts index 8335e31187b41..30ef4877ef399 100644 --- a/src/plugins/expressions/common/expression_renderers/expression_renderer_registry.ts +++ b/src/plugins/expressions/common/expression_renderers/expression_renderer_registry.ts @@ -27,13 +27,10 @@ export class ExpressionRendererRegistry implements IRegistry } public toJS(): Record { - return this.toArray().reduce( - (acc, renderer) => ({ - ...acc, - [renderer.name]: renderer, - }), - {} as Record - ); + return this.toArray().reduce((acc, renderer) => { + acc[renderer.name] = renderer; + return acc; + }, {} as Record); } public toArray(): ExpressionRenderer[] { diff --git a/src/plugins/kibana_usage_collection/server/collectors/application_usage/rollups/total.ts b/src/plugins/kibana_usage_collection/server/collectors/application_usage/rollups/total.ts index c8a83deba52e8..8487c0ea8418e 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/application_usage/rollups/total.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/application_usage/rollups/total.ts @@ -48,11 +48,9 @@ export async function rollTotals(logger: Logger, savedObjectsClient?: ISavedObje ) => { const key = viewId === MAIN_APP_DEFAULT_VIEW_ID ? appId : serializeKey(appId, viewId); - return { - ...acc, - // No need to sum because there should be 1 document per appId only - [key]: { appId, viewId, numberOfClicks, minutesOnScreen }, - }; + // No need to sum because there should be 1 document per appId only + acc[key] = { appId, viewId, numberOfClicks, minutesOnScreen }; + return acc; }, {} as Record< string, @@ -60,26 +58,27 @@ export async function rollTotals(logger: Logger, savedObjectsClient?: ISavedObje > ); - const totals = rawApplicationUsageDaily.reduce((acc, { attributes }) => { - const { - appId, - viewId = MAIN_APP_DEFAULT_VIEW_ID, - numberOfClicks, - minutesOnScreen, - } = attributes; - const key = viewId === MAIN_APP_DEFAULT_VIEW_ID ? appId : serializeKey(appId, viewId); - const existing = acc[key] || { minutesOnScreen: 0, numberOfClicks: 0 }; + const totals = rawApplicationUsageDaily.reduce( + (acc, { attributes }) => { + const { + appId, + viewId = MAIN_APP_DEFAULT_VIEW_ID, + numberOfClicks, + minutesOnScreen, + } = attributes; + const key = viewId === MAIN_APP_DEFAULT_VIEW_ID ? appId : serializeKey(appId, viewId); + const existing = acc[key] || { minutesOnScreen: 0, numberOfClicks: 0 }; - return { - ...acc, - [key]: { + acc[key] = { appId, viewId, numberOfClicks: numberOfClicks + existing.numberOfClicks, minutesOnScreen: minutesOnScreen + existing.minutesOnScreen, - }, - }; - }, existingTotals); + }; + return acc; + }, + { ...existingTotals } + ); await Promise.all([ Object.entries(totals).length && diff --git a/src/plugins/kibana_usage_collection/server/collectors/application_usage/telemetry_application_usage_collector.ts b/src/plugins/kibana_usage_collection/server/collectors/application_usage/telemetry_application_usage_collector.ts index 1d93a05ed9d09..b689582ee2b72 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/application_usage/telemetry_application_usage_collector.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/application_usage/telemetry_application_usage_collector.ts @@ -90,21 +90,19 @@ export function registerApplicationUsageCollector( } ) => { const existing = acc[appId] || { clicks_total: 0, minutes_on_screen_total: 0 }; - return { - ...acc, - [serializeKey(appId, viewId)]: { - appId, - viewId, - clicks_total: numberOfClicks + existing.clicks_total, - clicks_7_days: 0, - clicks_30_days: 0, - clicks_90_days: 0, - minutes_on_screen_total: minutesOnScreen + existing.minutes_on_screen_total, - minutes_on_screen_7_days: 0, - minutes_on_screen_30_days: 0, - minutes_on_screen_90_days: 0, - }, + acc[serializeKey(appId, viewId)] = { + appId, + viewId, + clicks_total: numberOfClicks + existing.clicks_total, + clicks_7_days: 0, + clicks_30_days: 0, + clicks_90_days: 0, + minutes_on_screen_total: minutesOnScreen + existing.minutes_on_screen_total, + minutes_on_screen_7_days: 0, + minutes_on_screen_30_days: 0, + minutes_on_screen_90_days: 0, }; + return acc; }, {} as ApplicationUsageTelemetryReport ); @@ -156,17 +154,15 @@ export function registerApplicationUsageCollector( minutes_on_screen_90_days: existing.minutes_on_screen_90_days + minutesOnScreen, }; - return { - ...acc, - [serializeKey(appId, viewId)]: { - ...existing, - clicks_total: existing.clicks_total + numberOfClicks, - minutes_on_screen_total: existing.minutes_on_screen_total + minutesOnScreen, - ...(isInLast7Days ? last7Days : {}), - ...(isInLast30Days ? last30Days : {}), - ...(isInLast90Days ? last90Days : {}), - }, + acc[serializeKey(appId, viewId)] = { + ...existing, + clicks_total: existing.clicks_total + numberOfClicks, + minutes_on_screen_total: existing.minutes_on_screen_total + minutesOnScreen, + ...(isInLast7Days ? last7Days : {}), + ...(isInLast30Days ? last30Days : {}), + ...(isInLast90Days ? last90Days : {}), }; + return acc; }, applicationUsageFromTotals ); diff --git a/src/plugins/telemetry/server/telemetry_collection/get_kibana.ts b/src/plugins/telemetry/server/telemetry_collection/get_kibana.ts index 15ca075175cb5..c8d5e80ab5361 100644 --- a/src/plugins/telemetry/server/telemetry_collection/get_kibana.ts +++ b/src/plugins/telemetry/server/telemetry_collection/get_kibana.ts @@ -43,15 +43,12 @@ export function handleKibanaStats( ...kibanaStats.os, }; const formattedOsStats = Object.entries(os).reduce((acc, [key, value]) => { - if (typeof value !== 'string') { - // There are new fields reported now from the "os" property like "load", "memory", etc. They are objects. - return acc; + // There are new fields reported now from the "os" property like "load", "memory", etc. They are objects. + if (typeof value === 'string') { + acc[`${key}s`] = [{ [key]: value, count: 1 }]; } - return { - ...acc, - [`${key}s`]: [{ [key]: value, count: 1 }], - }; - }, {}); + return acc; + }, {} as Record); const version = serverVersion.replace(/-snapshot/i, ''); // Shouldn't we better maintain the -snapshot so we can differentiate between actual final releases and snapshots? diff --git a/src/plugins/ui_actions/public/service/ui_actions_service.ts b/src/plugins/ui_actions/public/service/ui_actions_service.ts index 567ef6f080a03..729448b9bf426 100644 --- a/src/plugins/ui_actions/public/service/ui_actions_service.ts +++ b/src/plugins/ui_actions/public/service/ui_actions_service.ts @@ -162,10 +162,12 @@ export class UiActionsService { }) ) ); - return actions.reduce( - (acc: Action[], action, i) => (isCompatibles[i] ? [...acc, action] : acc), - [] - ); + return actions.reduce((acc: Action[], action, i) => { + if (isCompatibles[i]) { + acc.push(action); + } + return acc; + }, []); }; /** diff --git a/src/plugins/usage_collection/server/usage_counters/usage_counters_service.ts b/src/plugins/usage_collection/server/usage_counters/usage_counters_service.ts index 0218334b7e153..1b40e91161704 100644 --- a/src/plugins/usage_collection/server/usage_counters/usage_counters_service.ts +++ b/src/plugins/usage_collection/server/usage_counters/usage_counters_service.ts @@ -183,14 +183,12 @@ export class UsageCountersService { acc[key] = counter; return acc; } - return { - ...acc, - [key]: { - ...existingCounter, - ...counter, - incrementBy: existingCounter.incrementBy + counter.incrementBy, - }, + acc[key] = { + ...existingCounter, + ...counter, + incrementBy: existingCounter.incrementBy + counter.incrementBy, }; + return acc; }, {} as Record); }; } diff --git a/src/plugins/vis_types/timeseries/server/lib/search_strategies/capabilities/default_search_capabilities.ts b/src/plugins/vis_types/timeseries/server/lib/search_strategies/capabilities/default_search_capabilities.ts index b925a56e7ca72..05d081308df73 100644 --- a/src/plugins/vis_types/timeseries/server/lib/search_strategies/capabilities/default_search_capabilities.ts +++ b/src/plugins/vis_types/timeseries/server/lib/search_strategies/capabilities/default_search_capabilities.ts @@ -30,15 +30,12 @@ export interface SearchCapabilitiesOptions { } const convertAggsToRestriction = (allAvailableAggs: string[]) => - allAvailableAggs.reduce( - (availableAggs, aggType) => ({ - ...availableAggs, - [aggType]: { - '*': true, - }, - }), - {} - ); + allAvailableAggs.reduce((availableAggs, aggType) => { + availableAggs[aggType] = { + '*': true, + }; + return availableAggs; + }, {} as Record); export class DefaultSearchCapabilities { public timezone: SearchCapabilitiesOptions['timezone']; diff --git a/src/plugins/vis_types/timeseries/server/lib/search_strategies/capabilities/rollup_search_capabilities.ts b/src/plugins/vis_types/timeseries/server/lib/search_strategies/capabilities/rollup_search_capabilities.ts index ec393e4ef048a..d51830bf307d3 100644 --- a/src/plugins/vis_types/timeseries/server/lib/search_strategies/capabilities/rollup_search_capabilities.ts +++ b/src/plugins/vis_types/timeseries/server/lib/search_strategies/capabilities/rollup_search_capabilities.ts @@ -54,13 +54,10 @@ export class RollupSearchCapabilities extends DefaultSearchCapabilities { }); const getFields = (fields: { [key: string]: any }) => - Object.keys(fields).reduce( - (acc, item) => ({ - ...acc, - [item]: true, - }), - this.createUiRestriction({}) - ); + Object.keys(fields).reduce((acc, item) => { + acc[item] = true; + return acc; + }, this.createUiRestriction({}) as Record); return Object.keys(this.availableMetrics).reduce( (acc, item) => ({ From fe77b3159169bc863851bd77692f860a14afc052 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Fri, 12 May 2023 12:35:58 +0200 Subject: [PATCH 03/15] start cleanup of xpack plugins --- .../get_authorization_mode_by_source.ts | 11 ++++----- .../lib/get_execution_log_aggregation.ts | 17 +++++++------- .../actions/server/usage/actions_telemetry.ts | 8 +++---- .../field_maps/mapping_from_field_map.ts | 10 ++++---- .../helpers/get_initial_by_weekday.ts | 23 ++++++++----------- .../server/lib/get_actions_config_map.ts | 6 +++-- .../lib/get_execution_log_aggregation.ts | 17 +++++++------- .../alerting/server/routes/lib/rename_keys.ts | 6 ++--- .../server/task_runner/rule_action_helper.ts | 8 +++---- .../usage/lib/get_telemetry_from_event_log.ts | 18 +++++++-------- .../lib/get_telemetry_from_task_manager.ts | 15 +++++------- .../lib/group_connectors_by_consumers.ts | 13 +++++------ .../lib/parse_simple_rule_type_bucket.ts | 8 +++---- x-pack/plugins/apm/common/apm_telemetry.ts | 14 +++++------ .../rule_types/get_service_group_fields.ts | 2 +- .../get_apm_package_policy_definition.ts | 23 ++++++++++--------- .../fleet/translate_legacy_schema_paths.ts | 18 ++++++++------- 17 files changed, 102 insertions(+), 115 deletions(-) diff --git a/x-pack/plugins/actions/server/authorization/get_authorization_mode_by_source.ts b/x-pack/plugins/actions/server/authorization/get_authorization_mode_by_source.ts index 4195d8b4086df..7980db61ee31c 100644 --- a/x-pack/plugins/actions/server/authorization/get_authorization_mode_by_source.ts +++ b/x-pack/plugins/actions/server/authorization/get_authorization_mode_by_source.ts @@ -53,13 +53,10 @@ export async function getBulkAuthorizationModeBySource( id: get(es, 'source.id'), })) ); - const legacyVersions: Record = alerts.saved_objects.reduce( - (acc, so) => ({ - ...acc, - [so.id]: so.attributes.meta?.versionApiKeyLastmodified === LEGACY_VERSION, - }), - {} - ); + const legacyVersions = alerts.saved_objects.reduce>((acc, so) => { + acc[so.id] = so.attributes.meta?.versionApiKeyLastmodified === LEGACY_VERSION; + return acc; + }, {}); return executionSources.reduce((acc, es) => { const isAlertSavedObject = isSavedObjectExecutionSource(es) && es.source?.type === ALERT_SAVED_OBJECT_TYPE; diff --git a/x-pack/plugins/actions/server/lib/get_execution_log_aggregation.ts b/x-pack/plugins/actions/server/lib/get_execution_log_aggregation.ts index ddbb864d4c06a..cc5b96205b5a5 100644 --- a/x-pack/plugins/actions/server/lib/get_execution_log_aggregation.ts +++ b/x-pack/plugins/actions/server/lib/get_execution_log_aggregation.ts @@ -49,6 +49,7 @@ interface IExecutionUuidKpiAggBucket extends estypes.AggregationsStringTermsBuck actionExecutionOutcomes: IActionExecution; }; } + interface IExecutionUuidAggBucket extends estypes.AggregationsStringTermsBucketKeys { timeoutMessage: estypes.AggregationsMultiBucketBase; actionExecution: { @@ -411,18 +412,18 @@ export function formatExecutionLogResult( export function formatSortForBucketSort(sort: estypes.Sort) { return (sort as estypes.SortCombinations[]).map((s) => - Object.keys(s).reduce( - (acc, curr) => ({ ...acc, [ExecutionLogSortFields[curr]]: get(s, curr) }), - {} - ) + Object.keys(s).reduce((acc, curr) => { + acc[ExecutionLogSortFields[curr]] = get(s, curr); + return acc; + }, {} as Record) ); } export function formatSortForTermSort(sort: estypes.Sort) { return (sort as estypes.SortCombinations[]).map((s) => - Object.keys(s).reduce( - (acc, curr) => ({ ...acc, [ExecutionLogSortFields[curr]]: get(s, `${curr}.order`) }), - {} - ) + Object.keys(s).reduce((acc, curr) => { + acc[ExecutionLogSortFields[curr]] = get(s, `${curr}.order`); + return acc; + }, {} as Record) ); } diff --git a/x-pack/plugins/actions/server/usage/actions_telemetry.ts b/x-pack/plugins/actions/server/usage/actions_telemetry.ts index 15d2d6f4d12e5..6e2b4ebbfff80 100644 --- a/x-pack/plugins/actions/server/usage/actions_telemetry.ts +++ b/x-pack/plugins/actions/server/usage/actions_telemetry.ts @@ -68,10 +68,10 @@ export async function getTotalCount( const countByType = Object.keys(aggs).reduce( // ES DSL aggregations are returned as `any` by esClient.search // eslint-disable-next-line @typescript-eslint/no-explicit-any - (obj: any, key: string) => ({ - ...obj, - [replaceFirstAndLastDotSymbols(key)]: aggs[key], - }), + (obj: any, key: string) => { + obj[replaceFirstAndLastDotSymbols(key)] = aggs[key]; + return obj; + }, {} ); if (preconfiguredActions && preconfiguredActions.length) { diff --git a/x-pack/plugins/alerting/common/alert_schema/field_maps/mapping_from_field_map.ts b/x-pack/plugins/alerting/common/alert_schema/field_maps/mapping_from_field_map.ts index 9d1db8e577aa5..038fdaf48fbf5 100644 --- a/x-pack/plugins/alerting/common/alert_schema/field_maps/mapping_from_field_map.ts +++ b/x-pack/plugins/alerting/common/alert_schema/field_maps/mapping_from_field_map.ts @@ -34,13 +34,11 @@ export function mappingFromFieldMap( ...rest, // eslint-disable-next-line @typescript-eslint/naming-convention fields: multi_fields.reduce((acc, multi_field: MultiField) => { - return { - ...acc, - [multi_field.name]: { - type: multi_field.type, - }, + acc[multi_field.name] = { + type: multi_field.type, }; - }, {}), + return acc; + }, {} as Record), } : rest; diff --git a/x-pack/plugins/alerting/public/pages/maintenance_windows/helpers/get_initial_by_weekday.ts b/x-pack/plugins/alerting/public/pages/maintenance_windows/helpers/get_initial_by_weekday.ts index b63220bd17d53..b11d3bcf6a5e6 100644 --- a/x-pack/plugins/alerting/public/pages/maintenance_windows/helpers/get_initial_by_weekday.ts +++ b/x-pack/plugins/alerting/public/pages/maintenance_windows/helpers/get_initial_by_weekday.ts @@ -11,17 +11,14 @@ import { ISO_WEEKDAYS_TO_RRULE } from '../constants'; export const getInitialByWeekday = (initialStateByweekday: string[], date: Moment | null) => { const dayOfWeek = date ? date.isoWeekday() : 1; - return ISO_WEEKDAYS.reduce( - (result, n) => ({ - ...result, - [n]: - initialStateByweekday?.length > 0 - ? initialStateByweekday - // Sanitize nth day strings, e.g. +2MO, -1FR, into just days of the week - .map((w) => w.replace(/[0-9+\-]/g, '')) - .includes(ISO_WEEKDAYS_TO_RRULE[n]) - : n === dayOfWeek, - }), - {} as Record - ); + return ISO_WEEKDAYS.reduce((result, n) => { + result[n] = + initialStateByweekday?.length > 0 + ? initialStateByweekday + // Sanitize nth day strings, e.g. +2MO, -1FR, into just days of the week + .map((w) => w.replace(/[0-9+\-]/g, '')) + .includes(ISO_WEEKDAYS_TO_RRULE[n]) + : n === dayOfWeek; + return result; + }, {} as Record); }; diff --git a/x-pack/plugins/alerting/server/lib/get_actions_config_map.ts b/x-pack/plugins/alerting/server/lib/get_actions_config_map.ts index 966f25e30f824..2ef7c97814648 100644 --- a/x-pack/plugins/alerting/server/lib/get_actions_config_map.ts +++ b/x-pack/plugins/alerting/server/lib/get_actions_config_map.ts @@ -10,15 +10,17 @@ import { ActionsConfig, ActionTypeConfig } from '../config'; export interface ActionsConfigMap { default: ActionTypeConfig; + [key: string]: ActionTypeConfig; } export const getActionsConfigMap = (actionsConfig: ActionsConfig): ActionsConfigMap => { const configsByConnectorType = actionsConfig.connectorTypeOverrides?.reduce( (config, configByConnectorType) => { - return { ...config, [configByConnectorType.id]: omit(configByConnectorType, 'id') }; + config[configByConnectorType.id] = omit(configByConnectorType, 'id') as ActionTypeConfig; + return config; }, - {} + {} as Record ); return { default: omit(actionsConfig, 'connectorTypeOverrides'), diff --git a/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.ts b/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.ts index 44e1f7bbe98c1..08665a547b1bc 100644 --- a/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.ts +++ b/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.ts @@ -70,6 +70,7 @@ interface IExecutionUuidKpiAggBucket extends estypes.AggregationsStringTermsBuck ruleExecutionOutcomes: IActionExecution; }; } + interface IExecutionUuidAggBucket extends estypes.AggregationsStringTermsBucketKeys { timeoutMessage: estypes.AggregationsMultiBucketBase; ruleExecution: { @@ -632,18 +633,18 @@ export function getNumExecutions(dateStart: Date, dateEnd: Date, ruleSchedule: s export function formatSortForBucketSort(sort: estypes.Sort) { return (sort as estypes.SortCombinations[]).map((s) => - Object.keys(s).reduce( - (acc, curr) => ({ ...acc, [ExecutionLogSortFields[curr]]: get(s, curr) }), - {} - ) + Object.keys(s).reduce((acc, curr) => { + acc[ExecutionLogSortFields[curr]] = get(s, curr); + return acc; + }, {} as Record) ); } export function formatSortForTermSort(sort: estypes.Sort) { return (sort as estypes.SortCombinations[]).map((s) => - Object.keys(s).reduce( - (acc, curr) => ({ ...acc, [ExecutionLogSortFields[curr]]: get(s, `${curr}.order`) }), - {} - ) + Object.keys(s).reduce((acc, curr) => { + acc[ExecutionLogSortFields[curr]] = get(s, `${curr}.order`); + return acc; + }, {} as Record) ); } diff --git a/x-pack/plugins/alerting/server/routes/lib/rename_keys.ts b/x-pack/plugins/alerting/server/routes/lib/rename_keys.ts index b1af837b8aea0..0303c2cb4f2c1 100644 --- a/x-pack/plugins/alerting/server/routes/lib/rename_keys.ts +++ b/x-pack/plugins/alerting/server/routes/lib/rename_keys.ts @@ -10,8 +10,6 @@ export const renameKeys = , U extends Record ): T => Object.keys(obj).reduce((acc, key) => { - return { - ...acc, - ...{ [keysMap[key] || key]: obj[key] }, - }; + acc[(keysMap[key] || key) as keyof T] = obj[key] as T[keyof T]; + return acc; }, {} as T); diff --git a/x-pack/plugins/alerting/server/task_runner/rule_action_helper.ts b/x-pack/plugins/alerting/server/task_runner/rule_action_helper.ts index 5eb9794dce606..11c24218e7d47 100644 --- a/x-pack/plugins/alerting/server/task_runner/rule_action_helper.ts +++ b/x-pack/plugins/alerting/server/task_runner/rule_action_helper.ts @@ -87,11 +87,11 @@ export const getSummaryActionsFromTaskState = ({ action.frequency?.summary && (action.uuid === key || generateActionHash(action) === key) ); if (actionExists) { - return { ...newObj, [actionExists.uuid!]: val }; // replace hash with uuid - } else { - return newObj; + // replace hash with uuid + newObj[actionExists.uuid!] = val; } - }, {}); + return newObj; + }, {} as Record); }; export const getSummaryActionTimeBounds = ( diff --git a/x-pack/plugins/alerting/server/usage/lib/get_telemetry_from_event_log.ts b/x-pack/plugins/alerting/server/usage/lib/get_telemetry_from_event_log.ts index e21df2376f4f8..49b7c7374213d 100644 --- a/x-pack/plugins/alerting/server/usage/lib/get_telemetry_from_event_log.ts +++ b/x-pack/plugins/alerting/server/usage/lib/get_telemetry_from_event_log.ts @@ -56,15 +56,18 @@ interface GetExecutionsPerDayCountResults { alertsPercentilesByType: Record>; countRulesByExecutionStatus: Record; } + interface GetExecutionTimeoutsPerDayCountResults { hasErrors: boolean; errorMessage?: string; countExecutionTimeouts: number; countExecutionTimeoutsByType: Record; } + interface GetExecutionCountsExecutionFailures extends AggregationsSingleBucketAggregateBase { by_reason: AggregationsTermsAggregateBase; } + interface GetExecutionCountsAggregationBucket extends AggregationsStringTermsBucketKeys { avg_execution_time: AggregationsSingleMetricAggregateBase; avg_es_search_duration: AggregationsSingleMetricAggregateBase; @@ -484,10 +487,7 @@ export function parsePercentileAggs( }; } } - return { - ...acc, - ...result, - }; + return Object.assign(acc, result); }, {}); } @@ -562,13 +562,11 @@ export function parseExecutionCountAggregationResults(results: { return { countTotalFailedExecutions: results?.execution_failures?.doc_count ?? 0, - countFailedExecutionsByReason: executionFailuresByReasonBuckets.reduce( - (acc: Record, bucket: AggregationsStringTermsBucketKeys) => { + countFailedExecutionsByReason: executionFailuresByReasonBuckets.reduce>( + (acc, bucket: AggregationsStringTermsBucketKeys) => { const reason: string = bucket.key; - return { - ...acc, - [reason]: bucket.doc_count ?? 0, - }; + acc[reason] = bucket.doc_count ?? 0; + return acc; }, {} ), diff --git a/x-pack/plugins/alerting/server/usage/lib/get_telemetry_from_task_manager.ts b/x-pack/plugins/alerting/server/usage/lib/get_telemetry_from_task_manager.ts index 41f41f6ab7ada..9b37051db5baf 100644 --- a/x-pack/plugins/alerting/server/usage/lib/get_telemetry_from_task_manager.ts +++ b/x-pack/plugins/alerting/server/usage/lib/get_telemetry_from_task_manager.ts @@ -175,18 +175,15 @@ export function parseBucket( const status: string = bucket.key; const taskTypeBuckets = bucket?.by_task_type?.buckets as AggregationsStringTermsBucketKeys[]; - const byTaskType = (taskTypeBuckets ?? []).reduce( - (acc: Record, taskTypeBucket: AggregationsStringTermsBucketKeys) => { + const byTaskType = (taskTypeBuckets ?? []).reduce>( + (acc, taskTypeBucket: AggregationsStringTermsBucketKeys) => { const taskType: string = replaceDotSymbols(taskTypeBucket.key.replace('alerting:', '')); - return { - ...acc, - [taskType]: taskTypeBucket.doc_count ?? 0, - }; + acc[taskType] = taskTypeBucket.doc_count ?? 0; + return acc; }, {} ); - return { - ...summary, + return Object.assign(summary, { countFailedAndUnrecognizedTasksByStatus: { ...summary.countFailedAndUnrecognizedTasksByStatus, [status]: bucket?.doc_count ?? 0, @@ -195,7 +192,7 @@ export function parseBucket( summary.countFailedAndUnrecognizedTasksByStatusByType, isEmpty(byTaskType) ? {} : { [status]: byTaskType } ), - }; + }); }, { countFailedAndUnrecognizedTasksByStatus: {}, diff --git a/x-pack/plugins/alerting/server/usage/lib/group_connectors_by_consumers.ts b/x-pack/plugins/alerting/server/usage/lib/group_connectors_by_consumers.ts index b189e2868b418..9dfaa9706b774 100644 --- a/x-pack/plugins/alerting/server/usage/lib/group_connectors_by_consumers.ts +++ b/x-pack/plugins/alerting/server/usage/lib/group_connectors_by_consumers.ts @@ -17,11 +17,10 @@ export function groupConnectorsByConsumers( consumers: AggregationsBuckets ) { return (consumers as ConnectorsByConsumersBucket[]).reduce((acc, consumer) => { - return { - ...acc, - [consumer.key]: consumer.actions.connector_types.buckets.reduce((accBucket, bucket) => { - return { ...accBucket, [replaceDotSymbols(bucket.key)]: bucket.doc_count }; - }, {}), - }; - }, {}); + acc[consumer.key] = consumer.actions.connector_types.buckets.reduce((accBucket, bucket) => { + accBucket[replaceDotSymbols(bucket.key)] = bucket.doc_count; + return accBucket; + }, {} as Record); + return acc; + }, {} as Record); } diff --git a/x-pack/plugins/alerting/server/usage/lib/parse_simple_rule_type_bucket.ts b/x-pack/plugins/alerting/server/usage/lib/parse_simple_rule_type_bucket.ts index 3cbae06517089..f3d3007061365 100644 --- a/x-pack/plugins/alerting/server/usage/lib/parse_simple_rule_type_bucket.ts +++ b/x-pack/plugins/alerting/server/usage/lib/parse_simple_rule_type_bucket.ts @@ -17,9 +17,7 @@ export function parseSimpleRuleTypeBucket( const buckets = ruleTypeBuckets as AggregationsStringTermsBucketKeys[]; return (buckets ?? []).reduce((acc, bucket: AggregationsStringTermsBucketKeys) => { const ruleType: string = replaceDotSymbols(bucket.key); - return { - ...acc, - [ruleType]: bucket.doc_count ?? 0, - }; - }, {}); + acc[ruleType] = bucket.doc_count ?? 0; + return acc; + }, {} as Record); } diff --git a/x-pack/plugins/apm/common/apm_telemetry.ts b/x-pack/plugins/apm/common/apm_telemetry.ts index d48d8fd25604b..d3b318e62eab3 100644 --- a/x-pack/plugins/apm/common/apm_telemetry.ts +++ b/x-pack/plugins/apm/common/apm_telemetry.ts @@ -21,15 +21,13 @@ function schemaToMapping(schemaLeaf: any): any { return Object.entries(schemaLeaf).reduce((acc, [key, value]) => { const propMapping = schemaToMapping(value); + acc[key] = + typeof propMapping.type === 'string' + ? propMapping + : { properties: propMapping }; - return { - ...acc, - [key]: - typeof propMapping.type === 'string' - ? propMapping - : { properties: propMapping }, - }; - }, {}); + return acc; + }, {} as Record); } /** diff --git a/x-pack/plugins/apm/server/routes/alerts/rule_types/get_service_group_fields.ts b/x-pack/plugins/apm/server/routes/alerts/rule_types/get_service_group_fields.ts index 2a50b8ba2f31e..cb70951111901 100644 --- a/x-pack/plugins/apm/server/routes/alerts/rule_types/get_service_group_fields.ts +++ b/x-pack/plugins/apm/server/routes/alerts/rule_types/get_service_group_fields.ts @@ -54,6 +54,6 @@ export function flattenSourceDoc( } return Object.keys(val).reduce((acc, key) => { const fieldMap = flattenSourceDoc(val[key], [...path, key]); - return { ...acc, ...fieldMap }; + return Object.assign(acc, fieldMap); }, {}); } diff --git a/x-pack/plugins/apm/server/routes/fleet/get_apm_package_policy_definition.ts b/x-pack/plugins/apm/server/routes/fleet/get_apm_package_policy_definition.ts index d2eea5db4ef17..738161abc4eeb 100644 --- a/x-pack/plugins/apm/server/routes/fleet/get_apm_package_policy_definition.ts +++ b/x-pack/plugins/apm/server/routes/fleet/get_apm_package_policy_definition.ts @@ -76,19 +76,19 @@ function getApmPackageInputVars({ ), // fixes issue where "*" needs to be wrapped in quotes to be parsed as a YAML string }; - return policyTemplateInputVars.reduce((acc, registryVarsEntry) => { + return policyTemplateInputVars.reduce< + Record + >((acc, registryVarsEntry) => { const { name, type, default: defaultValue } = registryVarsEntry; - return { - ...acc, - [name]: { - type, - value: - overrideValues[name] ?? - apmServerSchema[INPUT_VAR_NAME_TO_SCHEMA_PATH[name]] ?? - defaultValue ?? - '', - }, + acc[name] = { + type, + value: + overrideValues[name] ?? + apmServerSchema[INPUT_VAR_NAME_TO_SCHEMA_PATH[name]] ?? + defaultValue ?? + '', }; + return acc; }, {}); } @@ -98,6 +98,7 @@ function ensureValidMultiText(textMultiValue: string[] | undefined) { } return textMultiValue.map(escapeInvalidYamlString); } + function escapeInvalidYamlString(yamlString: string) { try { yaml.load(yamlString); diff --git a/x-pack/plugins/apm/server/routes/fleet/translate_legacy_schema_paths.ts b/x-pack/plugins/apm/server/routes/fleet/translate_legacy_schema_paths.ts index ca8de7d6e7a62..7860b70141177 100644 --- a/x-pack/plugins/apm/server/routes/fleet/translate_legacy_schema_paths.ts +++ b/x-pack/plugins/apm/server/routes/fleet/translate_legacy_schema_paths.ts @@ -10,12 +10,14 @@ import { LEGACY_TO_CURRENT_SCHEMA_PATHS } from '../../../common/fleet'; export function translateLegacySchemaPaths( apmServerSchema: Record ) { - return Object.keys(apmServerSchema).reduce((acc, apmServerSchemaKey) => { - const currentSchemaPath = - LEGACY_TO_CURRENT_SCHEMA_PATHS[apmServerSchemaKey] || apmServerSchemaKey; - return { - ...acc, - [currentSchemaPath]: apmServerSchema[apmServerSchemaKey], - }; - }, {}); + return Object.keys(apmServerSchema).reduce>( + (acc, apmServerSchemaKey) => { + const currentSchemaPath = + LEGACY_TO_CURRENT_SCHEMA_PATHS[apmServerSchemaKey] || + apmServerSchemaKey; + acc[currentSchemaPath] = apmServerSchema[apmServerSchemaKey]; + return acc; + }, + {} + ); } From c20c3a77228e0049573b19867c0793b833bf1ffc Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Fri, 12 May 2023 16:31:40 +0200 Subject: [PATCH 04/15] more of xpack plugins --- .../get_service_group_alerts.ts | 25 ++++---- .../service_groups/get_services_counts.ts | 13 ++-- .../apm/server/routes/service_groups/route.ts | 12 ++-- .../transform_service_map_responses.ts | 6 +- .../settings/apm_indices/save_apm_indices.ts | 5 +- .../pointseries/lib/get_expression_type.ts | 3 +- x-pack/plugins/canvas/public/lib/filter.ts | 19 +++--- .../canvas/public/state/selectors/workpad.ts | 8 +-- .../canvas/server/collectors/collector.ts | 2 +- x-pack/plugins/cases/public/api/utils.ts | 7 ++- x-pack/plugins/cases/public/containers/api.ts | 19 +++--- .../cases/server/client/attachments/get.ts | 8 +-- .../cases/server/client/cases/update.ts | 8 +-- .../cases/server/client/configure/client.ts | 13 ++-- .../server/client/metrics/actions/actions.ts | 2 +- x-pack/plugins/cases/server/client/utils.ts | 21 ++----- x-pack/plugins/cases/server/common/utils.ts | 3 +- .../migrations/user_actions/payload.ts | 9 +-- .../cases/server/services/alerts/index.ts | 2 +- .../cases/server/services/cases/index.ts | 2 +- .../cases/server/services/transform.ts | 11 ++-- .../server/telemetry/queries/connectors.ts | 13 ++-- .../cases/server/telemetry/queries/utils.ts | 13 ++-- .../crawl_custom_settings_flyout_logic.ts | 16 ++--- .../curations/curation/results/utils.ts | 12 ++-- .../server/lib/indices/fetch_index_counts.ts | 2 +- .../get_ml_inference_pipelines.ts | 24 ++++---- .../feature_privilege_iterator.ts | 6 +- .../plugins/features/server/feature_schema.ts | 3 +- .../server/ui_capabilities_for_features.ts | 38 +++++------- x-pack/plugins/fleet/common/authz.ts | 60 +++++++++---------- .../package_policies_to_agent_inputs.ts | 8 +-- .../fleet/server/services/agent_policy.ts | 6 +- .../security/uninstall_token_service/index.ts | 37 +++++++----- .../common/alerting/metrics/alert_link.ts | 18 ++---- .../common/inventory_models/intl_strings.ts | 6 +- .../plugins/infra/common/time/time_scale.ts | 14 ++--- .../server/search_strategy/search_strategy.ts | 7 +-- .../assignments/get_updatable_types.ts | 6 +- .../authorization/roles/elasticsearch_role.ts | 24 ++++---- .../snapshot_restore/common/lib/flatten.ts | 5 +- .../spaces_usage_collector.ts | 14 ++--- .../get_stats_with_xpack.ts | 3 +- 43 files changed, 237 insertions(+), 296 deletions(-) diff --git a/x-pack/plugins/apm/server/routes/service_groups/get_service_group_alerts.ts b/x-pack/plugins/apm/server/routes/service_groups/get_service_group_alerts.ts index 16178d305bd12..06ccd8f057a3e 100644 --- a/x-pack/plugins/apm/server/routes/service_groups/get_service_group_alerts.ts +++ b/x-pack/plugins/apm/server/routes/service_groups/get_service_group_alerts.ts @@ -33,13 +33,12 @@ export async function getServiceGroupAlerts({ if (!spaceId || serviceGroups.length === 0) { return {}; } - const serviceGroupsKueryMap: Record = - serviceGroups.reduce((acc, sg) => { - return { - ...acc, - [sg.id]: kqlQuery(sg.kuery)[0], - }; - }, {}); + const serviceGroupsKueryMap = serviceGroups.reduce< + Record + >((acc, sg) => { + acc[sg.id] = kqlQuery(sg.kuery)[0]; + return acc; + }, {}); const params = { size: 0, query: { @@ -79,13 +78,11 @@ export async function getServiceGroupAlerts({ const { buckets: filterAggBuckets } = (result.aggregations ?.service_groups ?? { buckets: {} }) as ServiceGroupsAggResponse; - const serviceGroupAlertsCount: Record = Object.keys( - filterAggBuckets - ).reduce((acc, serviceGroupId) => { - return { - ...acc, - [serviceGroupId]: filterAggBuckets[serviceGroupId].alerts_count.value, - }; + const serviceGroupAlertsCount = Object.keys(filterAggBuckets).reduce< + Record + >((acc, serviceGroupId) => { + acc[serviceGroupId] = filterAggBuckets[serviceGroupId].alerts_count.value; + return acc; }, {}); return serviceGroupAlertsCount; diff --git a/x-pack/plugins/apm/server/routes/service_groups/get_services_counts.ts b/x-pack/plugins/apm/server/routes/service_groups/get_services_counts.ts index 4dbf9b1026470..dd81a2abeb57e 100644 --- a/x-pack/plugins/apm/server/routes/service_groups/get_services_counts.ts +++ b/x-pack/plugins/apm/server/routes/service_groups/get_services_counts.ts @@ -26,13 +26,12 @@ export async function getServicesCounts({ if (!serviceGroups.length) { return {}; } - const serviceGroupsKueryMap: Record = - serviceGroups.reduce((acc, sg) => { - return { - ...acc, - [sg.id]: kqlQuery(sg.kuery)[0], - }; - }, {}); + const serviceGroupsKueryMap = serviceGroups.reduce< + Record + >((acc, sg) => { + acc[sg.id] = kqlQuery(sg.kuery)[0]; + return acc; + }, {}); const params = { apm: { diff --git a/x-pack/plugins/apm/server/routes/service_groups/route.ts b/x-pack/plugins/apm/server/routes/service_groups/route.ts index 7974d3762eb25..934c6ca03376e 100644 --- a/x-pack/plugins/apm/server/routes/service_groups/route.ts +++ b/x-pack/plugins/apm/server/routes/service_groups/route.ts @@ -189,14 +189,14 @@ const serviceGroupCountsRoute = createApmServerRoute({ spaceId: activeSpace?.id, }), ]); - const serviceGroupCounts: ServiceGroupCounts = serviceGroups.reduce( - (acc, { id }): ServiceGroupCounts => ({ - ...acc, - [id]: { + const serviceGroupCounts = serviceGroups.reduce( + (acc, { id }): ServiceGroupCounts => { + acc[id] = { services: servicesCounts[id], alerts: serviceGroupAlertsCount[id], - }, - }), + }; + return acc; + }, {} ); return serviceGroupCounts; diff --git a/x-pack/plugins/apm/server/routes/service_map/transform_service_map_responses.ts b/x-pack/plugins/apm/server/routes/service_map/transform_service_map_responses.ts index 97a13c368b162..e13c667c17acf 100644 --- a/x-pack/plugins/apm/server/routes/service_map/transform_service_map_responses.ts +++ b/x-pack/plugins/apm/server/routes/service_map/transform_service_map_responses.ts @@ -245,10 +245,8 @@ export function transformServiceMapResponses({ const connectionsById = mappedConnections.reduce( (connectionMap, connection) => { - return { - ...connectionMap, - [connection.id]: connection, - }; + connectionMap[connection.id] = connection; + return connectionMap; }, {} as Record ); diff --git a/x-pack/plugins/apm/server/routes/settings/apm_indices/save_apm_indices.ts b/x-pack/plugins/apm/server/routes/settings/apm_indices/save_apm_indices.ts index 4e0b412084f6e..d51e2f927925c 100644 --- a/x-pack/plugins/apm/server/routes/settings/apm_indices/save_apm_indices.ts +++ b/x-pack/plugins/apm/server/routes/settings/apm_indices/save_apm_indices.ts @@ -32,5 +32,8 @@ function removeEmpty(apmIndices: Partial) { return Object.entries(apmIndices) .map(([key, value]) => [key, value?.trim()]) .filter(([_, value]) => !!value) - .reduce((obj, [key, value]) => ({ ...obj, [key as string]: value }), {}); + .reduce((obj, [key, value]) => { + obj[key as string] = value; + return obj; + }, {}); } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/pointseries/lib/get_expression_type.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/pointseries/lib/get_expression_type.ts index 63db2643cced7..2f59544d6702e 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/pointseries/lib/get_expression_type.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/pointseries/lib/get_expression_type.ts @@ -27,9 +27,8 @@ export function getExpressionType(columns: DatatableColumn[], mathExpression: st const fieldTypes = fieldNames.reduce((types, name) => { const type = getFieldType(columns, name); if (type !== 'null' && types.indexOf(type) === -1) { - return types.concat(type); + types.push(type); } - return types; }, [] as string[]); diff --git a/x-pack/plugins/canvas/public/lib/filter.ts b/x-pack/plugins/canvas/public/lib/filter.ts index dceb7f15b1717..1ae0a423d19a9 100644 --- a/x-pack/plugins/canvas/public/lib/filter.ts +++ b/x-pack/plugins/canvas/public/lib/filter.ts @@ -27,17 +27,14 @@ export const defaultFormatter = (value: unknown) => (value || null ? `${value}` export const formatFilterView = (filterValue: FilterType) => (filterView: FlattenFilterViewInstance) => { const filterViewKeys = Object.keys(filterView) as Array; - return filterViewKeys.reduce( - (acc, key) => ({ - ...acc, - [key]: { - label: filterView[key].label, - formattedValue: (filterView[key].formatter ?? defaultFormatter)(filterValue[key]), - component: filterView[key].component, - }, - }), - {} - ); + return filterViewKeys.reduce((acc, key) => { + acc[key] = { + label: filterView[key].label, + formattedValue: (filterView[key].formatter ?? defaultFormatter)(filterValue[key]), + component: filterView[key].component, + }; + return acc; + }, {} as Record); }; export const flattenFilterView = (filterValue: FilterType) => (filterView: FilterViewInstance) => { diff --git a/x-pack/plugins/canvas/public/state/selectors/workpad.ts b/x-pack/plugins/canvas/public/state/selectors/workpad.ts index 359cab63395e4..66e0b6ce71414 100644 --- a/x-pack/plugins/canvas/public/state/selectors/workpad.ts +++ b/x-pack/plugins/canvas/public/state/selectors/workpad.ts @@ -68,10 +68,10 @@ export function getWorkpadVariablesAsObject(state: State) { return {}; } - return (variables as CanvasVariable[]).reduce( - (vars: Record, v: CanvasVariable) => ({ ...vars, [v.name]: v.value }), - {} - ); + return (variables as CanvasVariable[]).reduce>((vars, v: CanvasVariable) => { + vars[v.name] = v.value; + return vars; + }, {}); } export function getWorkpadInfo(state: State): WorkpadInfo { diff --git a/x-pack/plugins/canvas/server/collectors/collector.ts b/x-pack/plugins/canvas/server/collectors/collector.ts index 31919bc663c1e..61d4828518f93 100644 --- a/x-pack/plugins/canvas/server/collectors/collector.ts +++ b/x-pack/plugins/canvas/server/collectors/collector.ts @@ -44,7 +44,7 @@ export function registerCanvasUsageCollector( ); return collectorResults.reduce((reduction, usage) => { - return { ...reduction, ...usage }; + return Object.assign(reduction, usage); }, {}) as CanvasUsage; // We need the casting because `TelemetryCollector` claims it returns `Record` }, schema: { ...workpadSchema, ...customElementSchema }, diff --git a/x-pack/plugins/cases/public/api/utils.ts b/x-pack/plugins/cases/public/api/utils.ts index c3303b26219ee..436b316f0ce47 100644 --- a/x-pack/plugins/cases/public/api/utils.ts +++ b/x-pack/plugins/cases/public/api/utils.ts @@ -32,12 +32,13 @@ import type { export const convertArrayToCamelCase = (arrayOfSnakes: unknown[]): unknown[] => arrayOfSnakes.reduce((acc: unknown[], value) => { if (isArray(value)) { - return [...acc, convertArrayToCamelCase(value)]; + acc.push(convertArrayToCamelCase(value)); } else if (isObject(value)) { - return [...acc, convertToCamelCase(value)]; + acc.push(convertToCamelCase(value)); } else { - return [...acc, value]; + acc.push(value); } + return acc; }, []); export const convertToCamelCase = (obj: T): U => diff --git a/x-pack/plugins/cases/public/containers/api.ts b/x-pack/plugins/cases/public/containers/api.ts index 232cf6cd4d449..96771e676ed22 100644 --- a/x-pack/plugins/cases/public/containers/api.ts +++ b/x-pack/plugins/cases/public/containers/api.ts @@ -441,17 +441,14 @@ export const getCaseConnectors = async ( } ); - return Object.keys(res).reduce( - (acc, connectorId) => ({ - ...acc, - [connectorId]: { - ...convertToCamelCase( - res[connectorId] - ), - }, - }), - {} - ); + return Object.keys(res).reduce((acc, connectorId) => { + acc[connectorId] = { + ...convertToCamelCase( + res[connectorId] + ), + }; + return acc; + }, {}); }; export const getCaseUsers = async (caseId: string, signal: AbortSignal): Promise => { diff --git a/x-pack/plugins/cases/server/client/attachments/get.ts b/x-pack/plugins/cases/server/client/attachments/get.ts index 79832e98c8016..dcbf4ba597190 100644 --- a/x-pack/plugins/cases/server/client/attachments/get.ts +++ b/x-pack/plugins/cases/server/client/attachments/get.ts @@ -38,14 +38,14 @@ const normalizeAlertResponse = (alerts: Array> return acc; } - return [ - ...acc, + acc.push( ...ids.map((id, index) => ({ id, index: indices[index], attached_at: alert.attributes.created_at, - })), - ]; + })) + ); + return acc; }, []); /** diff --git a/x-pack/plugins/cases/server/client/cases/update.ts b/x-pack/plugins/cases/server/client/cases/update.ts index 07423b4904685..07ed76ba441c6 100644 --- a/x-pack/plugins/cases/server/client/cases/update.ts +++ b/x-pack/plugins/cases/server/client/cases/update.ts @@ -436,12 +436,12 @@ export const update = async ( return flattenCases; } - return [ - ...flattenCases, + flattenCases.push( flattenCaseSavedObject({ savedObject: mergeOriginalSOWithUpdatedSO(originalCase, updatedCase), - }), - ]; + }) + ); + return flattenCases; }, [] as Case[]); await userActionService.creator.bulkCreateUpdateCase({ diff --git a/x-pack/plugins/cases/server/client/configure/client.ts b/x-pack/plugins/cases/server/client/configure/client.ts index aae777d66ea2f..95efef4121a73 100644 --- a/x-pack/plugins/cases/server/client/configure/client.ts +++ b/x-pack/plugins/cases/server/client/configure/client.ts @@ -60,7 +60,9 @@ export interface InternalConfigureSubClient { getMappings( params: MappingsArgs ): Promise['saved_objects']>; + createMappings(params: CreateMappingsArgs): Promise; + updateMappings(params: UpdateMappingsArgs): Promise; } @@ -72,10 +74,12 @@ export interface ConfigureSubClient { * Retrieves the external connector configuration for a particular case owner. */ get(params: GetConfigureFindRequest): Promise; + /** * Retrieves the valid external connectors supported by the cases plugin. */ getConnectors(): Promise; + /** * Updates a particular configuration with new values. * @@ -86,6 +90,7 @@ export interface ConfigureSubClient { configurationId: string, configurations: ICasesConfigurePatch ): Promise; + /** * Creates a configuration if one does not already exist. If one exists it is deleted and a new one is created. */ @@ -212,10 +217,10 @@ export async function getConnectors({ logger, }: CasesClientArgs): Promise { try { - const actionTypes = (await actionsClient.listTypes()).reduce( - (types, type) => ({ ...types, [type.id]: type }), - {} - ); + const actionTypes = (await actionsClient.listTypes()).reduce((types, type) => { + types[type.id] = type; + return types; + }, {} as Record); return (await actionsClient.getAll()).filter((action) => isConnectorSupported(action, actionTypes) diff --git a/x-pack/plugins/cases/server/client/metrics/actions/actions.ts b/x-pack/plugins/cases/server/client/metrics/actions/actions.ts index fe56ac1f289c5..f452e163e70f3 100644 --- a/x-pack/plugins/cases/server/client/metrics/actions/actions.ts +++ b/x-pack/plugins/cases/server/client/metrics/actions/actions.ts @@ -43,7 +43,7 @@ export class Actions extends SingleCaseAggregationHandler { ); const aggregations = this.aggregationBuilders.reduce((aggs, aggregator) => { - return { ...aggs, ...aggregator.build() }; + return Object.assign(aggs, aggregator.build()); }, {}); const response = await attachmentService.executeCaseActionsAggregations({ diff --git a/x-pack/plugins/cases/server/client/utils.ts b/x-pack/plugins/cases/server/client/utils.ts index a954dae4bb509..82be4c9225930 100644 --- a/x-pack/plugins/cases/server/client/utils.ts +++ b/x-pack/plugins/cases/server/client/utils.ts @@ -489,6 +489,7 @@ export const arraysDifference = ( interface CaseWithIDVersion { id: string; version: string; + [key: string]: unknown; } @@ -496,31 +497,19 @@ export const getCaseToUpdate = ( currentCase: unknown, queryCase: CaseWithIDVersion ): CaseWithIDVersion => - Object.entries(queryCase).reduce( + Object.entries(queryCase).reduce( (acc, [key, value]) => { const currentValue = get(currentCase, key); if (Array.isArray(currentValue) && Array.isArray(value)) { if (arraysDifference(value, currentValue)) { - return { - ...acc, - [key]: value, - }; + acc[key] = value; } - return acc; } else if (isPlainObject(currentValue) && isPlainObject(value)) { if (!deepEqual(currentValue, value)) { - return { - ...acc, - [key]: value, - }; + acc[key] = value; } - - return acc; } else if (currentValue != null && value !== currentValue) { - return { - ...acc, - [key]: value, - }; + acc[key] = value; } return acc; }, diff --git a/x-pack/plugins/cases/server/common/utils.ts b/x-pack/plugins/cases/server/common/utils.ts index 75ca980af639b..6323033000e1d 100644 --- a/x-pack/plugins/cases/server/common/utils.ts +++ b/x-pack/plugins/cases/server/common/utils.ts @@ -144,7 +144,8 @@ export const flattenCommentSavedObjects = ( savedObjects: Array> ): Comment[] => savedObjects.reduce((acc: Comment[], savedObject: SavedObject) => { - return [...acc, flattenCommentSavedObject(savedObject)]; + acc.push(flattenCommentSavedObject(savedObject)); + return acc; }, []); export const flattenCommentSavedObject = ( diff --git a/x-pack/plugins/cases/server/saved_object_types/migrations/user_actions/payload.ts b/x-pack/plugins/cases/server/saved_object_types/migrations/user_actions/payload.ts index cd1ef23f86223..986ea68195423 100644 --- a/x-pack/plugins/cases/server/saved_object_types/migrations/user_actions/payload.ts +++ b/x-pack/plugins/cases/server/saved_object_types/migrations/user_actions/payload.ts @@ -136,10 +136,11 @@ const convertPayload = ( const unsafeDecodedValue = decodeValue(value); return fields.reduce( - (payload, field) => ({ - ...payload, - ...getSingleFieldPayload(field, unsafeDecodedValue[field] ?? unsafeDecodedValue, owner), - }), + (payload, field) => + Object.assign( + payload, + getSingleFieldPayload(field, unsafeDecodedValue[field] ?? unsafeDecodedValue, owner) + ), {} ); }; diff --git a/x-pack/plugins/cases/server/services/alerts/index.ts b/x-pack/plugins/cases/server/services/alerts/index.ts index d078508969b1e..7e094a14b264d 100644 --- a/x-pack/plugins/cases/server/services/alerts/index.ts +++ b/x-pack/plugins/cases/server/services/alerts/index.ts @@ -43,7 +43,7 @@ export class AlertService { const { ids, indices } = AlertService.getUniqueIdsIndices(alerts); const builtAggs = aggregationBuilders.reduce((acc, agg) => { - return { ...acc, ...agg.build() }; + return Object.assign(acc, agg.build()); }, {}); const res = await this.scopedClusterClient.search({ diff --git a/x-pack/plugins/cases/server/services/cases/index.ts b/x-pack/plugins/cases/server/services/cases/index.ts index 42fd0f03a25e2..551e4dbf7b9be 100644 --- a/x-pack/plugins/cases/server/services/cases/index.ts +++ b/x-pack/plugins/cases/server/services/cases/index.ts @@ -592,7 +592,7 @@ export class CasesService { }): Promise { try { const builtAggs = aggregationBuilders.reduce((acc, agg) => { - return { ...acc, ...agg.build() }; + return Object.assign(acc, agg.build()); }, {}); const res = await this.unsecuredSavedObjectsClient.find< diff --git a/x-pack/plugins/cases/server/services/transform.ts b/x-pack/plugins/cases/server/services/transform.ts index 1229ec1fd6c62..fe42254af7dcb 100644 --- a/x-pack/plugins/cases/server/services/transform.ts +++ b/x-pack/plugins/cases/server/services/transform.ts @@ -50,13 +50,10 @@ function transformConnectorFieldsToExternalModel( type: connector.type, fields: connector.fields != null && connector.fields.length > 0 - ? connector.fields.reduce( - (fields, { key, value }) => ({ - ...fields, - [key]: value, - }), - {} - ) + ? connector.fields.reduce((fields, { key, value }) => { + fields[key] = value; + return fields; + }, {} as Record) : null, } as ConnectorTypeFields; diff --git a/x-pack/plugins/cases/server/telemetry/queries/connectors.ts b/x-pack/plugins/cases/server/telemetry/queries/connectors.ts index 8275ac86b729d..862f48d544b78 100644 --- a/x-pack/plugins/cases/server/telemetry/queries/connectors.ts +++ b/x-pack/plugins/cases/server/telemetry/queries/connectors.ts @@ -82,14 +82,11 @@ export const getConnectorsTelemetryData = async ({ SavedObjectsFindResponse >; - const data = connectorData.reduce( - (acc, res, currentIndex) => ({ - ...acc, - [connectorTypes[currentIndex]]: - res.aggregations?.references?.referenceType?.referenceAgg?.value ?? 0, - }), - {} as Record - ); + const data = connectorData.reduce((acc, res, currentIndex) => { + acc[connectorTypes[currentIndex]] = + res.aggregations?.references?.referenceType?.referenceAgg?.value ?? 0; + return acc; + }, {} as Record); const allAttached = all[0].aggregations?.references?.referenceType?.referenceAgg?.value ?? 0; const maxAttachedToACase = all[1].aggregations?.references?.cases?.max?.value ?? 0; diff --git a/x-pack/plugins/cases/server/telemetry/queries/utils.ts b/x-pack/plugins/cases/server/telemetry/queries/utils.ts index e47e9d1613bce..57671bc5ea0db 100644 --- a/x-pack/plugins/cases/server/telemetry/queries/utils.ts +++ b/x-pack/plugins/cases/server/telemetry/queries/utils.ts @@ -208,14 +208,11 @@ export const getAggregationsBuckets = ({ }: { keys: string[]; aggs?: Record; -}): Record => - keys.reduce( - (acc, key) => ({ - ...acc, - [key]: getBucketFromAggregation({ aggs, key }), - }), - {} - ); +}) => + keys.reduce>((acc, key) => { + acc[key] = getBucketFromAggregation({ aggs, key }); + return acc; + }, {}); export const getAttachmentsFrameworkStats = ({ attachmentAggregations, diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/crawl_custom_settings_flyout/crawl_custom_settings_flyout_logic.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/crawl_custom_settings_flyout/crawl_custom_settings_flyout_logic.ts index 8c9cc351c8257..abd159648b134 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/crawl_custom_settings_flyout/crawl_custom_settings_flyout_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/crawler/components/crawl_custom_settings_flyout/crawl_custom_settings_flyout_logic.ts @@ -52,10 +52,10 @@ export interface CrawlCustomSettingsFlyoutLogicActions { } const filterSeedUrlsByDomainUrls = (seedUrls: string[], domainUrls: string[]): string[] => { - const domainUrlMap = domainUrls.reduce( - (acc, domainUrl) => ({ ...acc, [domainUrl]: true }), - {} as { [key: string]: boolean } - ); + const domainUrlMap = domainUrls.reduce((acc, domainUrl) => { + acc[domainUrl] = true; + return acc; + }, {} as { [key: string]: boolean }); return seedUrls.filter((seedUrl) => { const { domain } = extractDomainAndEntryPointFromUrl(seedUrl); @@ -173,10 +173,10 @@ export const CrawlCustomSettingsFlyoutLogic = kea< domainConfigMap: [ (selectors) => [selectors.domainConfigs], (domainConfigs: DomainConfig[]) => - domainConfigs.reduce( - (acc, domainConfig) => ({ ...acc, [domainConfig.name]: domainConfig }), - {} as { [key: string]: DomainConfig } - ), + domainConfigs.reduce((acc, domainConfig) => { + acc[domainConfig.name] = domainConfig; + return acc; + }, {} as { [key: string]: DomainConfig }), ], entryPointUrls: [ (selectors) => [selectors.domainConfigMap, selectors.selectedDomainUrls], diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/results/utils.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/results/utils.ts index 9f9340fe46537..aebc84e41896a 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/results/utils.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/results/utils.ts @@ -42,13 +42,11 @@ const isNestedObject = (value: unknown): boolean => { export const convertToResultFormat = (document: CurationResult): SearchResult => { // Convert `key: 'value'` into `key: { raw: 'value' }` const result = Object.entries(document).reduce((acc, [key, value]) => { - return { - ...acc, - [key]: - isNestedObject(value) || Object.prototype.hasOwnProperty.call(value, 'raw') - ? value - : { raw: value }, - }; + acc[key] = + isNestedObject(value) || Object.prototype.hasOwnProperty.call(value, 'raw') + ? value + : { raw: value }; + return acc; }, {} as SearchResult); result._meta = mergeMetas(result._meta, convertIdToMeta(document.id)); diff --git a/x-pack/plugins/enterprise_search/server/lib/indices/fetch_index_counts.ts b/x-pack/plugins/enterprise_search/server/lib/indices/fetch_index_counts.ts index a80deebe45761..c4309284de58a 100644 --- a/x-pack/plugins/enterprise_search/server/lib/indices/fetch_index_counts.ts +++ b/x-pack/plugins/enterprise_search/server/lib/indices/fetch_index_counts.ts @@ -14,5 +14,5 @@ export const fetchIndexCounts = async (client: IScopedClusterClient, indicesName return { [indexName]: count }; }); const indexCountArray = await Promise.all(countPromises); - return indexCountArray.reduce((acc, current) => ({ ...acc, ...current }), {}); + return indexCountArray.reduce((acc, current) => Object.assign(acc, current), {}); }; diff --git a/x-pack/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.ts b/x-pack/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.ts index f4cf3a4968482..bf06e604e9a83 100644 --- a/x-pack/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.ts +++ b/x-pack/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.ts @@ -43,20 +43,16 @@ export const getMlInferencePipelines = async ( // Process pipelines: check if the model_id is one of the redacted ones, if so, redact it in the // result as well - const inferencePipelinesResult: Record = Object.entries( - fetchedInferencePipelines - ).reduce( - (currentPipelines, [name, inferencePipeline]) => ({ - ...currentPipelines, - [name]: { - ...inferencePipeline, - processors: inferencePipeline.processors?.map((processor) => - redactModelIdIfInaccessible(processor, accessibleModelIds) - ), - }, - }), - {} - ); + const inferencePipelinesResult = Object.entries(fetchedInferencePipelines).reduce< + Record + >((currentPipelines, [name, inferencePipeline]) => { + currentPipelines[name] = Object.assign(inferencePipeline, { + processors: inferencePipeline.processors?.map((processor) => + redactModelIdIfInaccessible(processor, accessibleModelIds) + ), + }); + return currentPipelines; + }, {}); return inferencePipelinesResult; }; diff --git a/x-pack/plugins/features/server/feature_privilege_iterator/feature_privilege_iterator.ts b/x-pack/plugins/features/server/feature_privilege_iterator/feature_privilege_iterator.ts index 270ffb4e68960..9392b3b3fee33 100644 --- a/x-pack/plugins/features/server/feature_privilege_iterator/feature_privilege_iterator.ts +++ b/x-pack/plugins/features/server/feature_privilege_iterator/feature_privilege_iterator.ts @@ -92,10 +92,8 @@ function mergeWithSubFeatures( mergedConfig.management = [managementEntries, subFeatureManagementEntries] .flat() .reduce((acc, [sectionId, managementApps]) => { - return { - ...acc, - [sectionId]: mergeArrays(acc[sectionId], managementApps), - }; + acc[sectionId] = mergeArrays(acc[sectionId], managementApps); + return acc; }, {} as Record); mergedConfig.ui = mergeArrays(mergedConfig.ui, subFeaturePrivilege.ui); diff --git a/x-pack/plugins/features/server/feature_schema.ts b/x-pack/plugins/features/server/feature_schema.ts index cfc7c2ee47eaa..416a9bf534b3a 100644 --- a/x-pack/plugins/features/server/feature_schema.ts +++ b/x-pack/plugins/features/server/feature_schema.ts @@ -452,7 +452,8 @@ export function validateKibanaFeature(feature: KibanaFeatureConfig) { const values = Array.from(entry[1].values()).map( (managementPage) => `${entry[0]}.${managementPage}` ); - return [...acc, ...values]; + acc.push(...values); + return acc; }, [] as string[]); throw new Error( diff --git a/x-pack/plugins/features/server/ui_capabilities_for_features.ts b/x-pack/plugins/features/server/ui_capabilities_for_features.ts index 84cd78a3fa548..d05e0b4d86460 100644 --- a/x-pack/plugins/features/server/ui_capabilities_for_features.ts +++ b/x-pack/plugins/features/server/ui_capabilities_for_features.ts @@ -43,29 +43,22 @@ function getCapabilitiesFromFeature( if (feature.catalogue) { UIFeatureCapabilities.catalogue = { ...UIFeatureCapabilities.catalogue, - ...feature.catalogue.reduce( - (acc, capability) => ({ - ...acc, - [capability]: true, - }), - {} - ), + ...feature.catalogue.reduce((acc, capability) => { + acc[capability] = true; + return acc; + }, {} as Record), }; } if (feature.management) { const sectionEntries = Object.entries(feature.management); UIFeatureCapabilities.management = sectionEntries.reduce((acc, [sectionId, sectionItems]) => { - return { - ...acc, - [sectionId]: sectionItems.reduce((acc2, item) => { - return { - ...acc2, - [item]: true, - }; - }, {}), - }; - }, {}); + acc[sectionId] = sectionItems.reduce((acc2, item) => { + acc2[item] = true; + return acc2; + }, {} as Record); + return acc; + }, {} as Record); } const featurePrivileges = Object.values(feature.privileges ?? {}) as Writable< @@ -86,13 +79,10 @@ function getCapabilitiesFromFeature( featurePrivileges.forEach((privilege) => { UIFeatureCapabilities[feature.id] = { ...UIFeatureCapabilities[feature.id], - ...privilege.ui.reduce( - (privilegeAcc, capability) => ({ - ...privilegeAcc, - [capability]: true, - }), - {} - ), + ...privilege.ui.reduce((privilegeAcc, capability) => { + privilegeAcc[capability] = true; + return privilegeAcc; + }, {} as Record), }; }); diff --git a/x-pack/plugins/fleet/common/authz.ts b/x-pack/plugins/fleet/common/authz.ts index 3fbfd614d8038..55e46bfaef9f0 100644 --- a/x-pack/plugins/fleet/common/authz.ts +++ b/x-pack/plugins/fleet/common/authz.ts @@ -102,25 +102,22 @@ export function calculatePackagePrivilegesFromCapabilities( return {}; } - const endpointActions = Object.entries(ENDPOINT_PRIVILEGES).reduce( - (acc, [privilege, { privilegeName }]) => { - return { - ...acc, - [privilege]: { - executePackageAction: (capabilities.siem && capabilities.siem[privilegeName]) || false, - }, - }; - }, - {} - ); + const endpointActions = Object.entries(ENDPOINT_PRIVILEGES).reduce< + FleetAuthz['packagePrivileges']['endpoint'] + >((acc, [privilege, { privilegeName }]) => { + acc[privilege] = { + executePackageAction: (capabilities.siem && capabilities.siem[privilegeName]) || false, + }; + return acc; + }, {}); - const transformActions = Object.keys(capabilities.transform).reduce((acc, privilegeName) => { - return { - ...acc, - [privilegeName]: { - executePackageAction: capabilities.transform[privilegeName] || false, - }, + const transformActions = Object.keys(capabilities.transform).reduce< + FleetAuthz['packagePrivileges']['transform'] + >((acc, privilegeName) => { + acc[privilegeName] = { + executePackageAction: capabilities.transform[privilegeName] || false, }; + return acc; }, {}); return { @@ -161,22 +158,19 @@ export function calculatePackagePrivilegesFromKibanaPrivileges( return {}; } - const endpointActions = Object.entries(ENDPOINT_PRIVILEGES).reduce( - (acc, [privilege, { appId, privilegeSplit, privilegeName }]) => { - const kibanaPrivilege = getAuthorizationFromPrivileges( - kibanaPrivileges, - `${appId}${privilegeSplit}`, - privilegeName - ); - return { - ...acc, - [privilege]: { - executePackageAction: kibanaPrivilege, - }, - }; - }, - {} - ); + const endpointActions = Object.entries(ENDPOINT_PRIVILEGES).reduce< + FleetAuthz['packagePrivileges']['endpoint'] + >((acc, [privilege, { appId, privilegeSplit, privilegeName }]) => { + const kibanaPrivilege = getAuthorizationFromPrivileges( + kibanaPrivileges, + `${appId}${privilegeSplit}`, + privilegeName + ); + acc[privilege] = { + executePackageAction: kibanaPrivilege, + }; + return acc; + }, {}); const hasTransformAdmin = getAuthorizationFromPrivileges( kibanaPrivileges, diff --git a/x-pack/plugins/fleet/server/services/agent_policies/package_policies_to_agent_inputs.ts b/x-pack/plugins/fleet/server/services/agent_policies/package_policies_to_agent_inputs.ts index f0b94474c7592..e1de799873f64 100644 --- a/x-pack/plugins/fleet/server/services/agent_policies/package_policies_to_agent_inputs.ts +++ b/x-pack/plugins/fleet/server/services/agent_policies/package_policies_to_agent_inputs.ts @@ -80,10 +80,10 @@ export const storedPackagePolicyToAgentInputs = ( // deeply merge the input.config values with the full policy input merge( fullInput, - Object.entries(input.config || {}).reduce( - (acc, [key, { value }]) => ({ ...acc, [key]: value }), - {} - ) + Object.entries(input.config || {}).reduce((acc, [key, { value }]) => { + acc[key] = value; + return acc; + }, {} as Record) ); if (packagePolicy.package) { diff --git a/x-pack/plugins/fleet/server/services/agent_policy.ts b/x-pack/plugins/fleet/server/services/agent_policy.ts index 96b53da7cbb6c..dc51dfcdf9e87 100644 --- a/x-pack/plugins/fleet/server/services/agent_policy.ts +++ b/x-pack/plugins/fleet/server/services/agent_policy.ts @@ -847,7 +847,8 @@ class AgentPolicyService { fleetServerPolicy.unenroll_timeout = policy.unenroll_timeout; } - return [...acc, fleetServerPolicy]; + acc.push(fleetServerPolicy); + return acc; }, [] as FleetServerPolicy[]); const fleetServerPoliciesBulkBody = fleetServerPolicies.flatMap((fleetServerPolicy) => [ @@ -876,7 +877,8 @@ class AgentPolicyService { return acc; } - return [...acc, value]; + acc.push(value); + return acc; }, [] as BulkResponseItem[]); logger.debug( diff --git a/x-pack/plugins/fleet/server/services/security/uninstall_token_service/index.ts b/x-pack/plugins/fleet/server/services/security/uninstall_token_service/index.ts index 633a431a84914..b5daa9d18f56a 100644 --- a/x-pack/plugins/fleet/server/services/security/uninstall_token_service/index.ts +++ b/x-pack/plugins/fleet/server/services/security/uninstall_token_service/index.ts @@ -45,14 +45,23 @@ interface UninstallTokenSOAggregation { export interface UninstallTokenServiceInterface { getTokenForPolicyId(policyId: string): Promise; + getTokensForPolicyIds(policyIds: string[]): Promise>; + getAllTokens(): Promise>; + getHashedTokenForPolicyId(policyId: string): Promise; + getHashedTokensForPolicyIds(policyIds?: string[]): Promise>; + getAllHashedTokens(): Promise>; + generateTokenForPolicyId(policyId: string, force?: boolean): Promise; + generateTokensForPolicyIds(policyIds: string[], force?: boolean): Promise>; + generateTokensForAllPolicies(force?: boolean): Promise>; + encryptTokens(): Promise; } @@ -127,7 +136,8 @@ export class UninstallTokenService implements UninstallTokenServiceInterface { const id = latest?.hits?.hits?.at(0)?._id; if (!id) return acc; const filterStr = `${UNINSTALL_TOKENS_SAVED_OBJECT_TYPE}.id: "${id}"`; - return [...acc, filterStr]; + acc.push(filterStr); + return acc; }, [] as string[]) .join(' or '); @@ -152,10 +162,8 @@ export class UninstallTokenService implements UninstallTokenServiceInterface { return acc; } - return { - ...acc, - [policyId]: token, - }; + acc[policyId] = token; + return acc; }, {} as Record); return tokensMap; @@ -190,11 +198,11 @@ export class UninstallTokenService implements UninstallTokenServiceInterface { public async getHashedTokensForPolicyIds(policyIds: string[]): Promise> { const tokensMap = await this.getTokensForPolicyIds(policyIds); return Object.entries(tokensMap).reduce((acc, [policyId, token]) => { - if (!policyId || !token) { - return acc; + if (policyId && token) { + acc[policyId] = this.hashToken(token); } - return { ...acc, [policyId]: this.hashToken(token) }; - }, {}); + return acc; + }, {} as Record); } /** @@ -264,13 +272,10 @@ export class UninstallTokenService implements UninstallTokenServiceInterface { ...newTokensMap, }; - return Object.entries(tokensMap).reduce( - (acc, [policyId, token]) => ({ - ...acc, - [policyId]: this.hashToken(token), - }), - {} - ); + return Object.entries(tokensMap).reduce((acc, [policyId, token]) => { + acc[policyId] = this.hashToken(token); + return acc; + }, {} as Record); } /** diff --git a/x-pack/plugins/infra/common/alerting/metrics/alert_link.ts b/x-pack/plugins/infra/common/alerting/metrics/alert_link.ts index 2f80f158ef3a2..e72246ae9a5c0 100644 --- a/x-pack/plugins/infra/common/alerting/metrics/alert_link.ts +++ b/x-pack/plugins/infra/common/alerting/metrics/alert_link.ts @@ -15,22 +15,14 @@ export const flatAlertRuleParams = (params: {}, pKey = ''): Record 0) { - return { - ...acc, - ...flatAlertRuleParams(field[0] as {}, objectKey), - }; + return Object.assign(acc, flatAlertRuleParams(field[0] as {}, objectKey)); } else { - return { - ...acc, - ...flatAlertRuleParams(field as {}, objectKey), - }; + return Object.assign(acc, flatAlertRuleParams(field as {}, objectKey)); } } - return { - ...acc, - [objectKey]: Array.isArray(field) ? field : [field], - }; - }, {}); + acc[objectKey] = Array.isArray(field) ? field : [field]; + return acc; + }, {} as Record); }; export const getInventoryViewInAppUrl = ( diff --git a/x-pack/plugins/infra/common/inventory_models/intl_strings.ts b/x-pack/plugins/infra/common/inventory_models/intl_strings.ts index 4c9427fbb5dc7..8131f8c9a9f67 100644 --- a/x-pack/plugins/infra/common/inventory_models/intl_strings.ts +++ b/x-pack/plugins/infra/common/inventory_models/intl_strings.ts @@ -46,6 +46,8 @@ export const fieldToName = (field: string) => { const snapshotTypeKeys = Object.keys(SnapshotMetricTypeKeys) as SnapshotMetricType[]; export const SNAPSHOT_METRIC_TRANSLATIONS = snapshotTypeKeys.reduce((result, metric) => { const text = toMetricOpt(metric)?.text; - if (text) return { ...result, [metric]: text }; + if (text) { + result[metric] = text; + } return result; -}, {}) as Record; +}, {} as Record); diff --git a/x-pack/plugins/infra/common/time/time_scale.ts b/x-pack/plugins/infra/common/time/time_scale.ts index 1e07cb869eb7d..cf449ddc8d6fb 100644 --- a/x-pack/plugins/infra/common/time/time_scale.ts +++ b/x-pack/plugins/infra/common/time/time_scale.ts @@ -25,14 +25,10 @@ export const decomposeIntoUnits = (time: number, units: TimeUnit[]) => const value = Math.floor((time - offset) / unitMillis); if (value > 0) { - return [ - ...result, - { - unit: unitMillis, - value, - }, - ]; - } else { - return result; + result.push({ + unit: unitMillis, + value, + }); } + return result; }, []); diff --git a/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.ts b/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.ts index d044e52154fd8..e7bead0cae398 100644 --- a/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.ts +++ b/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.ts @@ -86,12 +86,11 @@ export const ruleRegistrySearchStrategyProvider = ( } const alertIndexInfo = ruleDataService.findIndexByFeature(featureId, Dataset.alerts); if (alertIndexInfo) { - return [ - ...accum, + accum.push( featureId === 'siem' ? `${alertIndexInfo.baseName}-${space?.id ?? ''}*` - : `${alertIndexInfo.baseName}*`, - ]; + : `${alertIndexInfo.baseName}*` + ); } return accum; }, []); diff --git a/x-pack/plugins/saved_objects_tagging/server/services/assignments/get_updatable_types.ts b/x-pack/plugins/saved_objects_tagging/server/services/assignments/get_updatable_types.ts index 51bcae2b0c515..5c85964d6c8dc 100644 --- a/x-pack/plugins/saved_objects_tagging/server/services/assignments/get_updatable_types.ts +++ b/x-pack/plugins/saved_objects_tagging/server/services/assignments/get_updatable_types.ts @@ -25,10 +25,8 @@ export const getUpdatableSavedObjectTypes = async ({ // Each Saved Object type has a distinct privilege/action that we need to check const typeActionMap = types.reduce((acc, type) => { - return { - ...acc, - [type]: authorization!.actions.savedObject.get(type, 'update'), - }; + acc[type] = authorization!.actions.savedObject.get(type, 'update'); + return acc; }, {} as Record); // Perform the privilege check diff --git a/x-pack/plugins/security/server/authorization/roles/elasticsearch_role.ts b/x-pack/plugins/security/server/authorization/roles/elasticsearch_role.ts index fe13d0a7960b0..2febad56d7016 100644 --- a/x-pack/plugins/security/server/authorization/roles/elasticsearch_role.ts +++ b/x-pack/plugins/security/server/authorization/roles/elasticsearch_role.ts @@ -261,13 +261,11 @@ function transformRoleApplicationsToKibanaPrivileges( ), feature: featurePrivileges.reduce((acc, privilege) => { const featurePrivilege = PrivilegeSerializer.deserializeFeaturePrivilege(privilege); - return { - ...acc, - [featurePrivilege.featureId]: getUniqueList([ - ...(acc[featurePrivilege.featureId] || []), - featurePrivilege.privilege, - ]), - }; + acc[featurePrivilege.featureId] = getUniqueList([ + ...(acc[featurePrivilege.featureId] || []), + featurePrivilege.privilege, + ]); + return acc; }, {} as RoleKibanaPrivilege['feature']), spaces: ['*'], }; @@ -285,13 +283,11 @@ function transformRoleApplicationsToKibanaPrivileges( ), feature: featurePrivileges.reduce((acc, privilege) => { const featurePrivilege = PrivilegeSerializer.deserializeFeaturePrivilege(privilege); - return { - ...acc, - [featurePrivilege.featureId]: getUniqueList([ - ...(acc[featurePrivilege.featureId] || []), - featurePrivilege.privilege, - ]), - }; + acc[featurePrivilege.featureId] = getUniqueList([ + ...(acc[featurePrivilege.featureId] || []), + featurePrivilege.privilege, + ]); + return acc; }, {} as RoleKibanaPrivilege['feature']), spaces: resources.map((resource) => ResourceSerializer.deserializeSpaceResource(resource)), }; diff --git a/x-pack/plugins/snapshot_restore/common/lib/flatten.ts b/x-pack/plugins/snapshot_restore/common/lib/flatten.ts index b38ddf173d632..16845263dfdf7 100644 --- a/x-pack/plugins/snapshot_restore/common/lib/flatten.ts +++ b/x-pack/plugins/snapshot_restore/common/lib/flatten.ts @@ -14,9 +14,6 @@ export const flatten = (source: any, path: any[] = []): { [key: string]: any } = return Object.keys(source).reduce((result, key) => { const flattened: any = flatten(source[key], [...path, key]); - return { - ...result, - ...flattened, - }; + return Object.assign(result, flattened); }, {}); }; diff --git a/x-pack/plugins/spaces/server/usage_collection/spaces_usage_collector.ts b/x-pack/plugins/spaces/server/usage_collection/spaces_usage_collector.ts index bb41531ea9100..683b6073a5c31 100644 --- a/x-pack/plugins/spaces/server/usage_collection/spaces_usage_collector.ts +++ b/x-pack/plugins/spaces/server/usage_collection/spaces_usage_collector.ts @@ -75,18 +75,16 @@ async function getSpacesUsage( const count = hits?.total?.value ?? 0; const disabledFeatureBuckets = aggregations?.disabledFeatures?.buckets ?? []; - const initialCounts = knownFeatureIds.reduce( - (acc, featureId) => ({ ...acc, [featureId]: 0 }), - {} - ); + const initialCounts = knownFeatureIds.reduce((acc, featureId) => { + acc[featureId] = 0; + return acc; + }, {} as Record); const disabledFeatures: Record = disabledFeatureBuckets.reduce( // eslint-disable-next-line @typescript-eslint/naming-convention (acc, { key, doc_count }) => { - return { - ...acc, - [key]: doc_count, - }; + acc[key] = doc_count; + return acc; }, initialCounts ); diff --git a/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.ts b/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.ts index b789b1e54d2f9..f4016e0500bdb 100644 --- a/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.ts +++ b/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.ts @@ -55,6 +55,7 @@ export const getStatsWithXpack: StatsGetter = async fu // From the monitoring-sourced telemetry, we need to filter out the clusters that are opted-out. const onlyOptedInMonitoringClusters = (monitoringTelemetry || []).filter(isClusterOptedIn); - return [...acc, stats, ...onlyOptedInMonitoringClusters]; + acc.push(stats, ...onlyOptedInMonitoringClusters); + return acc; }, [] as TelemetryAggregatedStats[]); }; From eed5d2e0b11c15cb95ebc27fd20eeade0138f72b Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Mon, 15 May 2023 08:43:00 +0200 Subject: [PATCH 05/15] adapt more usages --- .../log_entries/kibana_log_entries_adapter.ts | 11 ++++------- .../elasticsearch_source_status_adapter.ts | 8 ++++---- .../inventory_metric_threshold_executor.ts | 10 ++++------ .../log_threshold/log_threshold_executor.ts | 2 +- .../convert_strings_to_missing_groups_record.ts | 5 +++-- .../metric_threshold_executor.ts | 10 ++++------ .../lib/infra_ml/metrics_hosts_anomalies.ts | 8 ++++---- .../lib/infra_ml/metrics_k8s_anomalies.ts | 8 ++++---- .../lib/convert_buckets_to_metrics_series.ts | 3 ++- .../metrics/lib/create_metrics_aggregations.ts | 2 +- .../server/routes/infra/lib/helpers/query.ts | 5 +---- .../snapshot/lib/get_metrics_aggregations.ts | 2 +- .../services/log_entries/message/message.ts | 15 ++++++++------- .../get_exception_list_summary.ts | 15 +++++++++------ .../classes/sources/es_source/es_source.ts | 12 ++++++++++-- .../public/classes/styles/color_palettes.ts | 6 ++++-- .../services/slo/historical_summary_client.ts | 8 ++++---- .../server/services/slo/summary_client.ts | 8 ++++---- .../server/deprecations/reporting_role.ts | 10 ++++++++-- .../connector_types/cases_webhook/utils.ts | 8 ++++---- .../telemetry/kibana_telemetry_adapter.ts | 2 +- .../lib/requests/generate_filter_aggs.ts | 2 +- .../timelines/common/utils/field_formatters.ts | 11 +++++++++-- .../search_strategy/index_fields/index.ts | 14 ++++++++++++-- .../timeline/factory/events/all/index.ts | 17 ++++++----------- .../factory/helpers/format_timeline_data.ts | 13 +++++++------ 26 files changed, 120 insertions(+), 95 deletions(-) diff --git a/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts index 26c29b948e266..97ef51ded269d 100644 --- a/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts @@ -48,13 +48,10 @@ export class InfraKibanaLogEntriesAdapter implements LogEntriesAdapter { ? { highlight: { boundary_scanner: 'word' as const, - fields: fields.reduce( - (highlightFieldConfigs, fieldName) => ({ - ...highlightFieldConfigs, - [fieldName]: {}, - }), - {} - ), + fields: fields.reduce((highlightFieldConfigs, fieldName) => { + highlightFieldConfigs[fieldName] = {}; + return highlightFieldConfigs; + }, {} as Record), fragment_size: 1, number_of_fragments: 100, post_tags: [''], diff --git a/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts index 54d19b3e753c1..54e2831899482 100644 --- a/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts @@ -30,10 +30,10 @@ export class InfraElasticsearchSourceStatusAdapter implements InfraSourceStatusA .catch(withDefaultIfNotFound({})), ]); - return indexMaps.reduce( - (indexNames, indexMap) => [...indexNames, ...Object.keys(indexMap)], - [] as string[] - ); + return indexMaps.reduce((indexNames, indexMap) => { + indexNames.push(...Object.keys(indexMap)); + return indexNames; + }, [] as string[]); } public async hasAlias(requestContext: InfraPluginRequestHandlerContext, aliasName: string) { diff --git a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts index d0eb8603ee69c..934249ee321f4 100644 --- a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts @@ -372,12 +372,10 @@ const mapToConditionsLookup = ( list: any[], mapFn: (value: any, index: number, array: any[]) => unknown ) => - list - .map(mapFn) - .reduce( - (result: Record, value, i) => ({ ...result, [`condition${i}`]: value }), - {} - ); + list.map(mapFn).reduce>((result, value, i) => { + result[`condition${i}`] = value; + return result; + }, {}); export const FIRED_ACTIONS: ActionGroup = { id: FIRED_ACTIONS_ID, 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 cca3b24b24c9a..4d74996f8959f 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 @@ -139,7 +139,7 @@ export const createLogThresholdExecutor = (libs: InfraBackendLibs) => ) => { const alertContext = actions != null - ? actions.reduce((next, action) => ({ ...next, ...action.context }), {}) + ? actions.reduce((next, action) => Object.assign(next, action.context), {}) : {}; const alert = alertWithLifecycle({ diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/convert_strings_to_missing_groups_record.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/convert_strings_to_missing_groups_record.ts index ef1091579dd76..efd5c1ff91534 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/convert_strings_to_missing_groups_record.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/convert_strings_to_missing_groups_record.ts @@ -17,8 +17,9 @@ export const convertStringsToMissingGroupsRecord = ( return { key: subject, bucketKey: parts.reduce((acc, part, index) => { - return { ...acc, [`groupBy${index}`]: part }; - }, {}), + acc[`groupBy${index}`] = part; + return acc; + }, {} as Record), }; } return subject; diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts index 46d2766777d21..19501f38aff7f 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts @@ -437,12 +437,10 @@ const mapToConditionsLookup = ( list: any[], mapFn: (value: any, index: number, array: any[]) => unknown ) => - list - .map(mapFn) - .reduce( - (result: Record, value, i) => ({ ...result, [`condition${i}`]: value }), - {} - ); + list.map(mapFn).reduce((result: Record, value, i) => { + result[`condition${i}`] = value; + return result; + }, {} as Record); const formatAlertResult = ( alertResult: { diff --git a/x-pack/plugins/infra/server/lib/infra_ml/metrics_hosts_anomalies.ts b/x-pack/plugins/infra/server/lib/infra_ml/metrics_hosts_anomalies.ts index 5aa53c67544f5..f265d7e923114 100644 --- a/x-pack/plugins/infra/server/lib/infra_ml/metrics_hosts_anomalies.ts +++ b/x-pack/plugins/infra/server/lib/infra_ml/metrics_hosts_anomalies.ts @@ -250,10 +250,10 @@ async function fetchMetricsHostsAnomalies( typical: typical[0], actual: actual[0], jobId: job_id, - influencers: hostInfluencers.reduce( - (acc: string[], i) => [...acc, ...i.influencer_field_values], - [] - ), + influencers: hostInfluencers.reduce((acc: string[], i) => { + acc.push(...i.influencer_field_values); + return acc; + }, []), startTime: anomalyStartTime, duration: duration * 1000, categoryId, diff --git a/x-pack/plugins/infra/server/lib/infra_ml/metrics_k8s_anomalies.ts b/x-pack/plugins/infra/server/lib/infra_ml/metrics_k8s_anomalies.ts index 81d2300604688..496c9e861d949 100644 --- a/x-pack/plugins/infra/server/lib/infra_ml/metrics_k8s_anomalies.ts +++ b/x-pack/plugins/infra/server/lib/infra_ml/metrics_k8s_anomalies.ts @@ -250,10 +250,10 @@ async function fetchMetricK8sAnomalies( typical: typical[0], actual: actual[0], jobId: job_id, - influencers: podInfluencers.reduce( - (acc: string[], i) => [...acc, ...i.influencer_field_values], - [] - ), + influencers: podInfluencers.reduce((acc: string[], i) => { + acc.push(...i.influencer_field_values); + return acc; + }, []), startTime: anomalyStartTime, duration: duration * 1000, categoryId, diff --git a/x-pack/plugins/infra/server/lib/metrics/lib/convert_buckets_to_metrics_series.ts b/x-pack/plugins/infra/server/lib/metrics/lib/convert_buckets_to_metrics_series.ts index 719d2334cc452..56ee719c931ec 100644 --- a/x-pack/plugins/infra/server/lib/metrics/lib/convert_buckets_to_metrics_series.ts +++ b/x-pack/plugins/infra/server/lib/metrics/lib/convert_buckets_to_metrics_series.ts @@ -76,7 +76,8 @@ export const convertBucketsToRows = ( const ids = options.metrics.map((metric) => metric.id); const metrics = ids.reduce((acc, id) => { const valueObject = get(bucket, [id]); - return { ...acc, [id]: ValueObjectTypeRT.is(valueObject) ? getValue(valueObject) : null }; + acc[id] = ValueObjectTypeRT.is(valueObject) ? getValue(valueObject) : null; + return acc; }, {} as Record); return { timestamp: bucket.key as number, ...metrics }; diff --git a/x-pack/plugins/infra/server/lib/metrics/lib/create_metrics_aggregations.ts b/x-pack/plugins/infra/server/lib/metrics/lib/create_metrics_aggregations.ts index 34a64085f07e6..7ab96a870cd1e 100644 --- a/x-pack/plugins/infra/server/lib/metrics/lib/create_metrics_aggregations.ts +++ b/x-pack/plugins/infra/server/lib/metrics/lib/create_metrics_aggregations.ts @@ -11,6 +11,6 @@ import { MetricsAPIRequest } from '../../../../common/http_api/metrics_api'; export const createMetricsAggregations = (options: MetricsAPIRequest): MetricsUIAggregation => { const { metrics } = options; return metrics.reduce((aggs, metric) => { - return { ...aggs, ...metric.aggregations }; + return Object.assign(aggs, metric.aggregations); }, {}); }; diff --git a/x-pack/plugins/infra/server/routes/infra/lib/helpers/query.ts b/x-pack/plugins/infra/server/routes/infra/lib/helpers/query.ts index 30a65333987fb..85f75faa4d2e3 100644 --- a/x-pack/plugins/infra/server/routes/infra/lib/helpers/query.ts +++ b/x-pack/plugins/infra/server/routes/infra/lib/helpers/query.ts @@ -91,10 +91,7 @@ export const getInventoryModelAggregations = ( ): Record => { const inventoryModel = findInventoryModel(INVENTORY_MODEL_NODE_TYPE); return metrics.reduce( - (acc, metric) => ({ - ...acc, - ...inventoryModel.metrics.snapshot?.[metric], - }), + (acc, metric) => Object.assign(acc, inventoryModel.metrics.snapshot?.[metric]), {} ); }; diff --git a/x-pack/plugins/infra/server/routes/snapshot/lib/get_metrics_aggregations.ts b/x-pack/plugins/infra/server/routes/snapshot/lib/get_metrics_aggregations.ts index 1f8760993c867..aa5141dc509bc 100644 --- a/x-pack/plugins/infra/server/routes/snapshot/lib/get_metrics_aggregations.ts +++ b/x-pack/plugins/infra/server/routes/snapshot/lib/get_metrics_aggregations.ts @@ -65,6 +65,6 @@ export const getMetricsAggregations = ( }) ); } - return { ...aggs, ...aggregation }; + return Object.assign(aggs, aggregation); }, {}); }; diff --git a/x-pack/plugins/infra/server/services/log_entries/message/message.ts b/x-pack/plugins/infra/server/services/log_entries/message/message.ts index fc547126b3b44..a77b3fe2b72ef 100644 --- a/x-pack/plugins/infra/server/services/log_entries/message/message.ts +++ b/x-pack/plugins/infra/server/services/log_entries/message/message.ts @@ -22,13 +22,10 @@ export function compileFormattingRules( return { requiredFields: Array.from( new Set( - compiledRules.reduce( - (combinedRequiredFields, { requiredFields }) => [ - ...combinedRequiredFields, - ...requiredFields, - ], - [] as string[] - ) + compiledRules.reduce((combinedRequiredFields, { requiredFields }) => { + combinedRequiredFields.push(...requiredFields); + return combinedRequiredFields; + }, [] as string[]) ) ), format(fields, highlights): LogMessagePart[] { @@ -247,16 +244,20 @@ export interface Highlights { export interface CompiledLogMessageFormattingRule { requiredFields: string[]; + fulfillsCondition(fields: Fields): boolean; + format(fields: Fields, highlights: Highlights): LogMessagePart[]; } export interface CompiledLogMessageFormattingCondition { conditionFields: string[]; + fulfillsCondition(fields: Fields): boolean; } export interface CompiledLogMessageFormattingInstruction { formattingFields: string[]; + format(fields: Fields, highlights: Highlights): LogMessagePart[]; } diff --git a/x-pack/plugins/lists/server/services/exception_lists/get_exception_list_summary.ts b/x-pack/plugins/lists/server/services/exception_lists/get_exception_list_summary.ts index 081bb1787eff8..4ecf19dd09097 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/get_exception_list_summary.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/get_exception_list_summary.ts @@ -29,6 +29,7 @@ interface ByOsAggBucketType { key: string; doc_count: number; } + interface ByOsAggType { by_os: { buckets: ByOsAggBucketType[]; @@ -84,12 +85,14 @@ export const getExceptionListSummary = async ({ return null; } - const summary: ExceptionListSummarySchema = savedObject.aggregations.by_os.buckets.reduce( - (acc, item: ByOsAggBucketType) => ({ - ...acc, - [item.key]: item.doc_count, - total: savedObject.total, - }), + const summary = savedObject.aggregations.by_os.buckets.reduce( + (acc, item: ByOsAggBucketType) => { + Object.assign(acc, { + [item.key]: item.doc_count, + total: savedObject.total, + }); + return acc; + }, { linux: 0, macos: 0, total: 0, windows: 0 } ); diff --git a/x-pack/plugins/maps/public/classes/sources/es_source/es_source.ts b/x-pack/plugins/maps/public/classes/sources/es_source/es_source.ts index da37b796cdf55..c69d23a094211 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_source/es_source.ts +++ b/x-pack/plugins/maps/public/classes/sources/es_source/es_source.ts @@ -49,10 +49,15 @@ export function isSearchSourceAbortError(error: Error) { export interface IESSource extends IVectorSource { isESSource(): true; + getId(): string; + getIndexPattern(): Promise; + getIndexPatternId(): string; + getGeoFieldName(): string; + loadStylePropsMeta({ layerName, style, @@ -472,9 +477,12 @@ export class AbstractESSource extends AbstractVectorSource implements IESSource }); const fieldAggRequests = await Promise.all(promises); - const allAggs: Record = fieldAggRequests.reduce( + const allAggs = fieldAggRequests.reduce>( (aggs: Record, fieldAggRequest: unknown | null) => { - return fieldAggRequest ? { ...aggs, ...(fieldAggRequest as Record) } : aggs; + if (fieldAggRequest) { + Object.assign(aggs, fieldAggRequest); + } + return aggs; }, {} ); diff --git a/x-pack/plugins/maps/public/classes/styles/color_palettes.ts b/x-pack/plugins/maps/public/classes/styles/color_palettes.ts index 45cd1d988fe6b..be07f78ff69ae 100644 --- a/x-pack/plugins/maps/public/classes/styles/color_palettes.ts +++ b/x-pack/plugins/maps/public/classes/styles/color_palettes.ts @@ -198,7 +198,8 @@ export function getOrdinalMbColorRampStops( return palette.reduce( (accu: Array, stopColor: string, idx: number, srcArr: string[]) => { const stopNumber = min + (delta * idx) / srcArr.length; - return [...accu, stopNumber, stopColor]; + accu.push(stopNumber, stopColor); + return accu; }, [] ); @@ -228,7 +229,8 @@ export function getPercentilesMbColorRampStops( palette.reverse(); } return palette.reduce((accu: Array, stopColor: string, idx: number) => { - return [...accu, percentiles[idx].value, stopColor]; + accu.push(percentiles[idx].value, stopColor); + return accu; }, []); } diff --git a/x-pack/plugins/observability/server/services/slo/historical_summary_client.ts b/x-pack/plugins/observability/server/services/slo/historical_summary_client.ts index 648ab8074c7c4..92e09eac37e52 100644 --- a/x-pack/plugins/observability/server/services/slo/historical_summary_client.ts +++ b/x-pack/plugins/observability/server/services/slo/historical_summary_client.ts @@ -53,10 +53,10 @@ export class DefaultHistoricalSummaryClient implements HistoricalSummaryClient { constructor(private esClient: ElasticsearchClient) {} async fetch(sloList: SLO[]): Promise> { - const dateRangeBySlo: Record = sloList.reduce( - (acc, slo) => ({ [slo.id]: getDateRange(slo), ...acc }), - {} - ); + const dateRangeBySlo = sloList.reduce>((acc, slo) => { + acc[slo.id] = getDateRange(slo); + return acc; + }, {}); const searches = sloList.flatMap((slo) => [ { index: `${SLO_DESTINATION_INDEX_NAME}*` }, diff --git a/x-pack/plugins/observability/server/services/slo/summary_client.ts b/x-pack/plugins/observability/server/services/slo/summary_client.ts index e531f7dd2e967..94fa69fb12371 100644 --- a/x-pack/plugins/observability/server/services/slo/summary_client.ts +++ b/x-pack/plugins/observability/server/services/slo/summary_client.ts @@ -21,10 +21,10 @@ export class DefaultSummaryClient implements SummaryClient { constructor(private esClient: ElasticsearchClient) {} async fetchSummary(sloList: SLO[]): Promise> { - const dateRangeBySlo: Record = sloList.reduce( - (acc, slo) => ({ [slo.id]: toDateRange(slo.timeWindow), ...acc }), - {} - ); + const dateRangeBySlo = sloList.reduce>((acc, slo) => { + acc[slo.id] = toDateRange(slo.timeWindow); + return acc; + }, {}); const searches = sloList.flatMap((slo) => [ { index: `${SLO_DESTINATION_INDEX_NAME}*` }, generateSearchQuery(slo, dateRangeBySlo[slo.id]), diff --git a/x-pack/plugins/reporting/server/deprecations/reporting_role.ts b/x-pack/plugins/reporting/server/deprecations/reporting_role.ts index 8898102918a0e..e82b6f2314d4c 100644 --- a/x-pack/plugins/reporting/server/deprecations/reporting_role.ts +++ b/x-pack/plugins/reporting/server/deprecations/reporting_role.ts @@ -120,7 +120,10 @@ async function getUsersDeprecations( const reportingUsers = Object.entries(users).reduce((userSet, current) => { const [userName, user] = current; const foundRole = user.roles.find((role) => deprecatedRoles.includes(role)); - return foundRole ? [...userSet, `${userName}[${foundRole}]`] : userSet; + if (foundRole) { + userSet.push(`${userName}[${foundRole}]`); + } + return userSet; }, [] as string[]); if (reportingUsers.length === 0) { @@ -209,7 +212,10 @@ async function getRoleMappingsDeprecations( (roleSet, current) => { const [roleName, role] = current; const foundMapping = role.roles.find((roll) => deprecatedRoles.includes(roll)); - return foundMapping ? [...roleSet, `${roleName}[${foundMapping}]`] : roleSet; + if (foundMapping) { + roleSet.push(`${roleName}[${foundMapping}]`); + } + return roleSet; }, [] as string[] ); diff --git a/x-pack/plugins/stack_connectors/server/connector_types/cases_webhook/utils.ts b/x-pack/plugins/stack_connectors/server/connector_types/cases_webhook/utils.ts index 108674d5a5a11..8da9286175f9a 100644 --- a/x-pack/plugins/stack_connectors/server/connector_types/cases_webhook/utils.ts +++ b/x-pack/plugins/stack_connectors/server/connector_types/cases_webhook/utils.ts @@ -90,8 +90,8 @@ export const throwDescriptiveErrorIfResponseIsNotValid = ({ export const removeSlash = (url: string) => (url.endsWith('/') ? url.slice(0, -1) : url); export const stringifyObjValues = (properties: Record) => ({ - case: Object.entries(properties).reduce( - (acc, [key, value]) => ({ ...acc, [key]: JSON.stringify(value) }), - {} - ), + case: Object.entries(properties).reduce((acc, [key, value]) => { + acc[key] = JSON.stringify(value); + return acc; + }, {} as Record), }); diff --git a/x-pack/plugins/synthetics/server/legacy_uptime/lib/adapters/telemetry/kibana_telemetry_adapter.ts b/x-pack/plugins/synthetics/server/legacy_uptime/lib/adapters/telemetry/kibana_telemetry_adapter.ts index 2fa270c88cef5..4f3760a2add5c 100644 --- a/x-pack/plugins/synthetics/server/legacy_uptime/lib/adapters/telemetry/kibana_telemetry_adapter.ts +++ b/x-pack/plugins/synthetics/server/legacy_uptime/lib/adapters/telemetry/kibana_telemetry_adapter.ts @@ -16,6 +16,7 @@ import { createEsQuery } from '../../../../../common/utils/es_search'; interface UptimeTelemetryCollector { [key: number]: UptimeTelemetry; } + // seconds in an hour const BUCKET_SIZE = 3600; // take buckets in the last day @@ -416,7 +417,6 @@ export class KibanaTelemetryAdapter { return Object.values(this.collector).reduce( (acc, cum) => ({ - ...cum, overview_page: acc.overview_page + cum.overview_page, monitor_page: acc.monitor_page + cum.monitor_page, settings_page: acc.settings_page + cum.settings_page, diff --git a/x-pack/plugins/synthetics/server/legacy_uptime/lib/requests/generate_filter_aggs.ts b/x-pack/plugins/synthetics/server/legacy_uptime/lib/requests/generate_filter_aggs.ts index c8c0b0cee44a9..04b3cefefa6d8 100644 --- a/x-pack/plugins/synthetics/server/legacy_uptime/lib/requests/generate_filter_aggs.ts +++ b/x-pack/plugins/synthetics/server/legacy_uptime/lib/requests/generate_filter_aggs.ts @@ -56,4 +56,4 @@ export const generateFilterAggs = ( }, }, })) - .reduce((parent: Record, agg: any) => ({ ...parent, ...agg }), {}); + .reduce((parent: Record, agg: any) => Object.assign(parent, agg), {}); diff --git a/x-pack/plugins/timelines/common/utils/field_formatters.ts b/x-pack/plugins/timelines/common/utils/field_formatters.ts index e9b8b45bfefca..f7275306235ed 100644 --- a/x-pack/plugins/timelines/common/utils/field_formatters.ts +++ b/x-pack/plugins/timelines/common/utils/field_formatters.ts @@ -14,6 +14,7 @@ import { legacyExperimentalFieldMap } from '@kbn/alerts-as-data-utils'; import { EventHit, TimelineEventsDetailsItem } from '../search_strategy'; import { toObjectArrayOfStrings, toStringArray } from './to_array'; import { ENRICHMENT_DESTINATION_PATH } from '../constants'; + export const baseCategoryFields = ['@timestamp', 'labels', 'message', 'tags']; const nonFlattenedFormatParamsFields = ['related_integrations', 'threat_mapping']; @@ -115,13 +116,19 @@ export const getDataFromFieldsHits = ( if (isRuleParametersFieldOrSubfield(field, prependField)) { nestedFields = Array.isArray(item) ? item - .reduce((acc, i) => [...acc, getDataFromFieldsHits(i, dotField, fieldCategory)], []) + .reduce((acc, i) => { + acc.push(getDataFromFieldsHits(i, dotField, fieldCategory)); + return acc; + }, []) .flat() : getDataFromFieldsHits(item, dotField, fieldCategory); } else { nestedFields = Array.isArray(item) ? item - .reduce((acc, i) => [...acc, getDataFromFieldsHits(i, dotField, fieldCategory)], []) + .reduce((acc, i) => { + acc.push(getDataFromFieldsHits(i, dotField, fieldCategory)); + return acc; + }, []) .flat() : getDataFromFieldsHits(item, prependField, fieldCategory); } diff --git a/x-pack/plugins/timelines/server/search_strategy/index_fields/index.ts b/x-pack/plugins/timelines/server/search_strategy/index_fields/index.ts index aec3c88222338..d9c9ee2374bf1 100644 --- a/x-pack/plugins/timelines/server/search_strategy/index_fields/index.ts +++ b/x-pack/plugins/timelines/server/search_strategy/index_fields/index.ts @@ -139,7 +139,12 @@ export const requestIndexFieldSearch = async ( const patternList = dataView.title.split(','); indicesExist = (await findExistingIndices(patternList, esUser)).reduce( - (acc: string[], doesIndexExist, i) => (doesIndexExist ? [...acc, patternList[i]] : acc), + (acc: string[], doesIndexExist, i) => { + if (doesIndexExist) { + acc.push(patternList[i]); + } + return acc; + }, [] ); @@ -152,7 +157,12 @@ export const requestIndexFieldSearch = async ( } else if ('indices' in request) { const patternList = dedupeIndexName(request.indices); indicesExist = (await findExistingIndices(patternList, esUser)).reduce( - (acc: string[], doesIndexExist, i) => (doesIndexExist ? [...acc, patternList[i]] : acc), + (acc: string[], doesIndexExist, i) => { + if (doesIndexExist) { + acc.push(patternList[i]); + } + return acc; + }, [] ); if (!request.onlyCheckIfIndicesExist) { diff --git a/x-pack/plugins/timelines/server/search_strategy/timeline/factory/events/all/index.ts b/x-pack/plugins/timelines/server/search_strategy/timeline/factory/events/all/index.ts index 2dc80acdfa7ea..e672be224d915 100644 --- a/x-pack/plugins/timelines/server/search_strategy/timeline/factory/events/all/index.ts +++ b/x-pack/plugins/timelines/server/search_strategy/timeline/factory/events/all/index.ts @@ -46,12 +46,7 @@ export const timelineEventsAll: TimelineFactory = { if (fieldRequested.includes('*') && hits.length > 0) { const fieldsReturned = hits.flatMap((hit) => Object.keys(hit.fields ?? {})); - fieldRequested = fieldsReturned.reduce((acc, f) => { - if (!acc.includes(f)) { - return [...acc, f]; - } - return acc; - }, fieldRequested); + fieldRequested = [...new Set(fieldsReturned)]; } const edges: TimelineEdges[] = await Promise.all( @@ -64,11 +59,11 @@ export const timelineEventsAll: TimelineFactory = { ) ); - const consumers: Record = producerBuckets.reduce( - (acc: Record, b: { key: string; doc_count: number }) => ({ - ...acc, - [b.key]: b.doc_count, - }), + const consumers = producerBuckets.reduce( + (acc: Record, b: { key: string; doc_count: number }) => { + acc[b.key] = b.doc_count; + return acc; + }, {} ); diff --git a/x-pack/plugins/timelines/server/search_strategy/timeline/factory/helpers/format_timeline_data.ts b/x-pack/plugins/timelines/server/search_strategy/timeline/factory/helpers/format_timeline_data.ts index e2ac37c12b669..6899222946fb3 100644 --- a/x-pack/plugins/timelines/server/search_strategy/timeline/factory/helpers/format_timeline_data.ts +++ b/x-pack/plugins/timelines/server/search_strategy/timeline/factory/helpers/format_timeline_data.ts @@ -70,12 +70,13 @@ const getValuesFromFields = async ( }; } const formattedData = await getDataSafety(getDataFromFieldsHits, fieldToEval); - return formattedData.reduce( - (acc: TimelineNonEcsData[], { field, values }) => - // nested fields return all field values, pick only the one we asked for - field.includes(fieldName) ? [...acc, { field, value: values }] : acc, - [] - ); + return formattedData.reduce((acc: TimelineNonEcsData[], { field, values }) => { + // nested fields return all field values, pick only the one we asked for + if (field.includes(fieldName)) { + acc.push({ field, value: values }); + } + return acc; + }, []); }; const mergeTimelineFieldsWithHit = async ( From 21a2923ebb105bf1b84f4e096f98e19308e995f6 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Mon, 15 May 2023 09:01:39 +0200 Subject: [PATCH 06/15] a bit more --- .../src/lib/aggregations/validation.ts | 2 +- x-pack/plugins/ml/common/util/validators.ts | 5 +---- .../get_partition_fields_values.ts | 13 +++++------ .../ml/server/routes/trained_models.ts | 10 ++------- .../server/kibana_monitoring/bulk_uploader.ts | 9 ++++---- .../metadata/endpoint_metadata_service.ts | 22 +++++++++---------- .../handlers/create_default_policy.ts | 7 +++--- .../get_rule_id_to_cases_map.ts | 4 +--- .../server/utils/build_query/reduce_fields.ts | 10 +++++---- 9 files changed, 36 insertions(+), 46 deletions(-) diff --git a/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/aggregations/validation.ts b/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/aggregations/validation.ts index d76f6023f663a..6af4023a15de1 100644 --- a/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/aggregations/validation.ts +++ b/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/aggregations/validation.ts @@ -196,7 +196,7 @@ const recursiveRewrite = ( memo[newKey] = newValue; return memo; - }, {} as Record); + }, {} as Record); }; const childContext = (context: ValidationContext, path: string): ValidationContext => { diff --git a/x-pack/plugins/ml/common/util/validators.ts b/x-pack/plugins/ml/common/util/validators.ts index e890db5893ad6..9ceeac4b29e82 100644 --- a/x-pack/plugins/ml/common/util/validators.ts +++ b/x-pack/plugins/ml/common/util/validators.ts @@ -52,10 +52,7 @@ export function composeValidators( ): (value: any) => { [key: string]: any } | null { return (value) => { const validationResult = validators.reduce((acc, validator) => { - return { - ...acc, - ...(validator(value) || {}), - }; + return Object.assign(acc, validator(value) || {}); }, {}); return Object.keys(validationResult).length > 0 ? validationResult : null; }; diff --git a/x-pack/plugins/ml/server/models/results_service/get_partition_fields_values.ts b/x-pack/plugins/ml/server/models/results_service/get_partition_fields_values.ts index 40479ce3c618c..1a4fb9af2fade 100644 --- a/x-pack/plugins/ml/server/models/results_service/get_partition_fields_values.ts +++ b/x-pack/plugins/ml/server/models/results_service/get_partition_fields_values.ts @@ -231,10 +231,10 @@ export const getPartitionFieldsValuesFactory = (mlClient: MlClient) => }, aggs: { ...ML_PARTITION_FIELDS.reduce((acc, key) => { - return { - ...acc, - ...getFieldAgg(key, isModelPlotSearch, searchTerm[key], fieldsConfig[key]), - }; + return Object.assign( + acc, + getFieldAgg(key, isModelPlotSearch, searchTerm[key], fieldsConfig[key]) + ); }, {}), }, }; @@ -250,9 +250,6 @@ export const getPartitionFieldsValuesFactory = (mlClient: MlClient) => ); return ML_PARTITION_FIELDS.reduce((acc, key) => { - return { - ...acc, - ...getFieldObject(key, body.aggregations!), - }; + return Object.assign(acc, getFieldObject(key, body.aggregations!)); }, {}); }; diff --git a/x-pack/plugins/ml/server/routes/trained_models.ts b/x-pack/plugins/ml/server/routes/trained_models.ts index 6fec964d1ce62..026bc3109b36f 100644 --- a/x-pack/plugins/ml/server/routes/trained_models.ts +++ b/x-pack/plugins/ml/server/routes/trained_models.ts @@ -97,16 +97,10 @@ export function trainedModelsRoutes({ router, routeGuard }: RouteInitialization) model.pipelines = { ...(pipelinesResponse.get(model.model_id) ?? {}), ...(model.metadata?.model_aliases ?? []).reduce((acc, alias) => { - return { - ...acc, - ...(pipelinesResponse.get(alias) ?? {}), - }; + return Object.assign(acc, pipelinesResponse.get(alias) ?? {}); }, {}), ...(modelDeploymentsMap[model.model_id] ?? []).reduce((acc, deploymentId) => { - return { - ...acc, - ...(pipelinesResponse.get(deploymentId) ?? {}), - }; + return Object.assign(acc, pipelinesResponse.get(deploymentId) ?? {}); }, {}), }; } diff --git a/x-pack/plugins/monitoring/server/kibana_monitoring/bulk_uploader.ts b/x-pack/plugins/monitoring/server/kibana_monitoring/bulk_uploader.ts index 8abbe4fea1f8e..aca7c23f00efc 100644 --- a/x-pack/plugins/monitoring/server/kibana_monitoring/bulk_uploader.ts +++ b/x-pack/plugins/monitoring/server/kibana_monitoring/bulk_uploader.ts @@ -137,6 +137,7 @@ export class BulkUploader implements IBulkUploader { public handleNotEnabled() { this.stop('Monitoring status upload endpoint is not enabled in Elasticsearch'); } + public handleConnectionLost() { this.stop('Connection issue detected'); } @@ -258,14 +259,14 @@ export class BulkUploader implements IBulkUploader { // convert the raw data into a flat array, with each payload prefixed // with an 'index' instruction, for bulk upload return rawData.reduce((accum, { type, result }) => { - return [ - ...accum, + accum.push( { index: { _type: type } }, { kibana: this.getKibanaStats(type), ...result, - }, - ]; + } + ); + return accum; }, [] as object[]); } } diff --git a/x-pack/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.ts b/x-pack/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.ts index 394461621ef3c..a7e00295c3a87 100644 --- a/x-pack/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.ts +++ b/x-pack/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.ts @@ -401,21 +401,21 @@ export class EndpointMetadataService { .getByIds(this.DANGEROUS_INTERNAL_SO_CLIENT, agentPolicyIds) .catch(catchAndWrapError)) ?? []; - const agentPoliciesMap: Record = agentPolicies.reduce( - (acc, agentPolicy) => ({ - ...acc, - [agentPolicy.id]: { + const agentPoliciesMap = agentPolicies.reduce>( + (acc, agentPolicy) => { + acc[agentPolicy.id] = { ...agentPolicy, - }, - }), + }; + return acc; + }, {} ); - const endpointPoliciesMap: Record = endpointPolicies.reduce( - (acc, packagePolicy) => ({ - ...acc, - [packagePolicy.policy_id]: packagePolicy, - }), + const endpointPoliciesMap = endpointPolicies.reduce>( + (acc, packagePolicy) => { + acc[packagePolicy.policy_id] = packagePolicy; + return acc; + }, {} ); diff --git a/x-pack/plugins/security_solution/server/fleet_integration/handlers/create_default_policy.ts b/x-pack/plugins/security_solution/server/fleet_integration/handlers/create_default_policy.ts index 52a686d198701..b78a8add376ff 100644 --- a/x-pack/plugins/security_solution/server/fleet_integration/handlers/create_default_policy.ts +++ b/x-pack/plugins/security_solution/server/fleet_integration/handlers/create_default_policy.ts @@ -49,10 +49,11 @@ export const createDefaultPolicy = ( /** * Create a copy of an object with all keys set to false */ -const falsyObjectKeys = >(obj: T): T => { +const falsyObjectKeys = >(obj: T): Record => { return Object.keys(obj).reduce((accumulator, key) => { - return { ...accumulator, [key]: false }; - }, {} as T); + accumulator[key as keyof T] = false; + return accumulator; + }, {} as Record); }; const getEndpointPolicyConfigPreset = (config: PolicyCreateEndpointConfig | undefined) => { diff --git a/x-pack/plugins/security_solution/server/usage/detections/rules/transform_utils/get_rule_id_to_cases_map.ts b/x-pack/plugins/security_solution/server/usage/detections/rules/transform_utils/get_rule_id_to_cases_map.ts index 361b195a06bde..c43d15122ddc1 100644 --- a/x-pack/plugins/security_solution/server/usage/detections/rules/transform_utils/get_rule_id_to_cases_map.ts +++ b/x-pack/plugins/security_solution/server/usage/detections/rules/transform_utils/get_rule_id_to_cases_map.ts @@ -22,9 +22,7 @@ export const getRuleIdToCasesMap = ( cache.set(ruleId, cacheCount + 1); } } - return cache; - } else { - return cache; } + return cache; }, new Map()); }; diff --git a/x-pack/plugins/security_solution/server/utils/build_query/reduce_fields.ts b/x-pack/plugins/security_solution/server/utils/build_query/reduce_fields.ts index 9da45356a23ae..3da2e5a26dc88 100644 --- a/x-pack/plugins/security_solution/server/utils/build_query/reduce_fields.ts +++ b/x-pack/plugins/security_solution/server/utils/build_query/reduce_fields.ts @@ -9,7 +9,9 @@ export const reduceFields = ( fields: readonly string[], fieldMap: Readonly> ): readonly string[] => - fields.reduce( - (res, field) => (fieldMap[field] != null ? [...res, fieldMap[field]] : res), - [] as readonly string[] - ); + fields.reduce((res, field) => { + if (fieldMap[field] != null) { + res.push(fieldMap[field]); + } + return res; + }, [] as string[]); From 048958880472cb27543c774bdcb4ebb4a2c27f7d Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Mon, 15 May 2023 11:14:20 +0200 Subject: [PATCH 07/15] last batch --- .../server/lib/beats/_beats_stats.ts | 12 ++++------ .../server/lib/beats/get_latest_stats.ts | 24 ++++++++----------- .../get_pipeline_vertex_stats_aggregation.ts | 2 +- .../routes/resolver/tree/queries/stats.ts | 10 ++++---- .../schedule_notification_actions.ts | 7 ++---- .../get_execution_event_aggregation/index.ts | 8 +++---- .../threshold/get_threshold_bucket_filters.ts | 3 ++- .../timelines/export_timelines/helpers.ts | 23 +++++++----------- .../factory/risk_score/all/index.ts | 16 +++++-------- 9 files changed, 43 insertions(+), 62 deletions(-) diff --git a/x-pack/plugins/monitoring/server/lib/beats/_beats_stats.ts b/x-pack/plugins/monitoring/server/lib/beats/_beats_stats.ts index 3b55a66561a88..e63e28f9f3e7a 100644 --- a/x-pack/plugins/monitoring/server/lib/beats/_beats_stats.ts +++ b/x-pack/plugins/monitoring/server/lib/beats/_beats_stats.ts @@ -104,13 +104,11 @@ export const beatsAggResponseHandler = (response?: BeatsElasticsearchResponse) = const buckets = response?.aggregations?.types?.buckets ?? []; const beatTotal = response?.aggregations?.total.value ?? 0; const beatTypes = buckets.reduce((types: BucketCount<{ type: string }>, typeBucket) => { - return [ - ...types, - { - type: upperFirst(typeBucket.key), - count: typeBucket.uuids.buckets.length, - }, - ]; + types.push({ + type: upperFirst(typeBucket.key), + count: typeBucket.uuids.buckets.length, + }); + return types; }, []); const eventsTotalMax = response?.aggregations?.max_events_total.value ?? 0; diff --git a/x-pack/plugins/monitoring/server/lib/beats/get_latest_stats.ts b/x-pack/plugins/monitoring/server/lib/beats/get_latest_stats.ts index 81cf42ab0094b..62c128492f8ee 100644 --- a/x-pack/plugins/monitoring/server/lib/beats/get_latest_stats.ts +++ b/x-pack/plugins/monitoring/server/lib/beats/get_latest_stats.ts @@ -38,26 +38,22 @@ export function handleResponse(response?: BeatsElasticsearchResponse) { const latestVersions = (aggs?.versions?.buckets ?? []).reduce( (accum: BucketCount<{ version: string }>, current) => { - return [ - ...accum, - { - version: current.key, - count: current.uuids.buckets.length, - }, - ]; + accum.push({ + version: current.key, + count: current.uuids.buckets.length, + }); + return accum; }, [] ); const latestTypes = (aggs?.types?.buckets ?? []).reduce( (accum: BucketCount<{ type: string }>, current) => { - return [ - ...accum, - { - type: upperFirst(current.key), - count: current.uuids.buckets.length, - }, - ]; + accum.push({ + type: upperFirst(current.key), + count: current.uuids.buckets.length, + }); + return accum; }, [] ); diff --git a/x-pack/plugins/monitoring/server/lib/logstash/get_pipeline_vertex_stats_aggregation.ts b/x-pack/plugins/monitoring/server/lib/logstash/get_pipeline_vertex_stats_aggregation.ts index 57a90c89038ce..52c738806c1ea 100644 --- a/x-pack/plugins/monitoring/server/lib/logstash/get_pipeline_vertex_stats_aggregation.ts +++ b/x-pack/plugins/monitoring/server/lib/logstash/get_pipeline_vertex_stats_aggregation.ts @@ -59,7 +59,7 @@ function scalarCounterAggregation( } function createAggsObjectFromAggsList(aggsList: any) { - return aggsList.reduce((aggsSoFar: object, agg: object) => ({ ...aggsSoFar, ...agg }), {}); + return aggsList.reduce((aggsSoFar: object, agg: object) => Object.assign(aggsSoFar, agg), {}); } function createNestedVertexAgg(statsPath: string, vertexId: string, maxBucketSize: number) { diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/stats.ts b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/stats.ts index 38986126f7051..d73acb5a86fe2 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/stats.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/queries/stats.ts @@ -109,11 +109,11 @@ export class StatsQuery extends BaseResolverQuery { }; } - const byCategory: Record = catAgg.categories.buckets.reduce( - (cummulative: Record, bucket: AggBucket) => ({ - ...cummulative, - [bucket.key]: bucket.doc_count, - }), + const byCategory = catAgg.categories.buckets.reduce>( + (cummulative: Record, bucket: AggBucket) => { + cummulative[bucket.key] = bucket.doc_count; + return cummulative; + }, {} ); return { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/schedule_notification_actions.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/schedule_notification_actions.ts index 4bede2c8b92a8..b54f74bd7ca20 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/schedule_notification_actions.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/notifications/schedule_notification_actions.ts @@ -26,13 +26,10 @@ const convertToLegacyAlert = (alert: DetectionAlert) => Object.entries(aadFieldConversion).reduce((acc, [legacyField, aadField]) => { const val = alert[aadField]; if (val != null) { - return { - ...acc, - [legacyField]: val, - }; + acc[legacyField] = val; } return acc; - }, {}); + }, {} as Record); export const normalizeAlertForNotificationActions = (alert: DetectionAlert) => { if (isThresholdRule(alert[ALERT_RULE_TYPE])) { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/get_execution_event_aggregation/index.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/get_execution_event_aggregation/index.ts index c1ebb5e77f98a..3bbfce43385af 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/get_execution_event_aggregation/index.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/get_execution_event_aggregation/index.ts @@ -346,10 +346,10 @@ export const formatExecutionEventResponse = ( */ export const formatSortForBucketSort = (sort: estypes.Sort) => { return (sort as estypes.SortCombinations[]).map((s) => - Object.keys(s).reduce( - (acc, curr) => ({ ...acc, [SORT_FIELD_TO_AGG_MAPPING[curr]]: get(s, curr) }), - {} - ) + Object.keys(s).reduce((acc, curr) => { + acc[SORT_FIELD_TO_AGG_MAPPING[curr]] = get(s, curr); + return acc; + }, {} as estypes.SortOptions) ); }; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/get_threshold_bucket_filters.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/get_threshold_bucket_filters.ts index 7bb04a8efa5b1..d39baa34f2664 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/get_threshold_bucket_filters.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/get_threshold_bucket_filters.ts @@ -49,7 +49,8 @@ export const getThresholdBucketFilters = async ({ } }); - return [...acc, filter]; + acc.push(filter); + return acc; }, [] as ESFilter[] ); diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/export_timelines/helpers.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/export_timelines/helpers.ts index 57e9b7fa55310..fcc3769e3d95c 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/export_timelines/helpers.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/export_timelines/helpers.ts @@ -28,21 +28,14 @@ const getGlobalEventNotesByTimelineId = (currentNotes: NoteSavedObject[]): Expor globalNotes: [], }; - return ( - currentNotes.reduce((acc, note) => { - if (note.eventId == null) { - return { - ...acc, - globalNotes: [...acc.globalNotes, note], - }; - } else { - return { - ...acc, - eventNotes: [...acc.eventNotes, note], - }; - } - }, initialNotes) ?? initialNotes - ); + return currentNotes.reduce((acc, note) => { + if (note.eventId == null) { + acc.globalNotes.push(note); + } else { + acc.eventNotes.push(note); + } + return acc; + }, initialNotes); }; const getPinnedEventsIdsByTimelineId = ( diff --git a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/all/index.ts b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/all/index.ts index 6506892c25287..28602d82dbed6 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/all/index.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/all/index.ts @@ -89,16 +89,12 @@ async function enhanceData( const response = await ruleDataReader?.search(query); const buckets: EnhancedDataBucket[] = getOr([], 'aggregations.alertsByEntity.buckets', response); - const enhancedAlertsDataByEntityName: Record< - string, - { count: number; oldestAlertTimestamp: string } - > = buckets.reduce( - (acc, { key, doc_count: count, oldestAlertTimestamp }) => ({ - ...acc, - [key]: { count, oldestAlertTimestamp: oldestAlertTimestamp.value_as_string }, - }), - {} - ); + const enhancedAlertsDataByEntityName = buckets.reduce< + Record + >((acc, { key, doc_count: count, oldestAlertTimestamp }) => { + acc[key] = { count, oldestAlertTimestamp: oldestAlertTimestamp.value_as_string as string }; + return acc; + }, {}); return data.map((risk) => ({ ...risk, From 6e99c4ddea63560813321a6b1a94f436c033a05b Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Mon, 15 May 2023 11:24:43 +0200 Subject: [PATCH 08/15] fix types --- .../actions/server/lib/get_execution_log_aggregation.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/x-pack/plugins/actions/server/lib/get_execution_log_aggregation.ts b/x-pack/plugins/actions/server/lib/get_execution_log_aggregation.ts index cc5b96205b5a5..ff11f831662cc 100644 --- a/x-pack/plugins/actions/server/lib/get_execution_log_aggregation.ts +++ b/x-pack/plugins/actions/server/lib/get_execution_log_aggregation.ts @@ -413,17 +413,17 @@ export function formatExecutionLogResult( export function formatSortForBucketSort(sort: estypes.Sort) { return (sort as estypes.SortCombinations[]).map((s) => Object.keys(s).reduce((acc, curr) => { - acc[ExecutionLogSortFields[curr]] = get(s, curr); + (acc as Record)[ExecutionLogSortFields[curr]] = get(s, curr); return acc; - }, {} as Record) + }, {}) ); } export function formatSortForTermSort(sort: estypes.Sort) { return (sort as estypes.SortCombinations[]).map((s) => Object.keys(s).reduce((acc, curr) => { - acc[ExecutionLogSortFields[curr]] = get(s, `${curr}.order`); + (acc as Record)[ExecutionLogSortFields[curr]] = get(s, `${curr}.order`); return acc; - }, {} as Record) + }, {}) ); } From 99aad44a40e31a7163d1093d21db8dbb89f42380 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Mon, 15 May 2023 11:50:50 +0200 Subject: [PATCH 09/15] more alerting type fixes --- .../alerting/server/lib/get_execution_log_aggregation.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.ts b/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.ts index 08665a547b1bc..551dfdce1ef42 100644 --- a/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.ts +++ b/x-pack/plugins/alerting/server/lib/get_execution_log_aggregation.ts @@ -634,17 +634,17 @@ export function getNumExecutions(dateStart: Date, dateEnd: Date, ruleSchedule: s export function formatSortForBucketSort(sort: estypes.Sort) { return (sort as estypes.SortCombinations[]).map((s) => Object.keys(s).reduce((acc, curr) => { - acc[ExecutionLogSortFields[curr]] = get(s, curr); + (acc as Record)[ExecutionLogSortFields[curr]] = get(s, curr); return acc; - }, {} as Record) + }, {}) ); } export function formatSortForTermSort(sort: estypes.Sort) { return (sort as estypes.SortCombinations[]).map((s) => Object.keys(s).reduce((acc, curr) => { - acc[ExecutionLogSortFields[curr]] = get(s, `${curr}.order`); + (acc as Record)[ExecutionLogSortFields[curr]] = get(s, `${curr}.order`); return acc; - }, {} as Record) + }, {}) ); } From d85a979317550df4154ce09694ff464f0a1c8300 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Mon, 15 May 2023 11:54:33 +0200 Subject: [PATCH 10/15] fix mutating usage --- .../lib/pipelines/ml_inference/get_ml_inference_pipelines.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.ts b/x-pack/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.ts index bf06e604e9a83..58e706926049a 100644 --- a/x-pack/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.ts +++ b/x-pack/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.ts @@ -46,11 +46,12 @@ export const getMlInferencePipelines = async ( const inferencePipelinesResult = Object.entries(fetchedInferencePipelines).reduce< Record >((currentPipelines, [name, inferencePipeline]) => { - currentPipelines[name] = Object.assign(inferencePipeline, { + currentPipelines[name] = { + ...inferencePipeline, processors: inferencePipeline.processors?.map((processor) => redactModelIdIfInaccessible(processor, accessibleModelIds) ), - }); + }; return currentPipelines; }, {}); From 03dd88798a50dbf7b4591cda9686200719cf8dbf Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Mon, 15 May 2023 13:25:10 +0200 Subject: [PATCH 11/15] fix more types and errors --- .../alerting/server/task_runner/rule_action_helper.ts | 2 +- .../server/usage/lib/group_connectors_by_consumers.ts | 4 ++-- .../adapters/telemetry/kibana_telemetry_adapter.ts | 11 ++++++----- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/x-pack/plugins/alerting/server/task_runner/rule_action_helper.ts b/x-pack/plugins/alerting/server/task_runner/rule_action_helper.ts index 11c24218e7d47..79fe92b079026 100644 --- a/x-pack/plugins/alerting/server/task_runner/rule_action_helper.ts +++ b/x-pack/plugins/alerting/server/task_runner/rule_action_helper.ts @@ -91,7 +91,7 @@ export const getSummaryActionsFromTaskState = ({ newObj[actionExists.uuid!] = val; } return newObj; - }, {} as Record); + }, {} as ThrottledActions); }; export const getSummaryActionTimeBounds = ( diff --git a/x-pack/plugins/alerting/server/usage/lib/group_connectors_by_consumers.ts b/x-pack/plugins/alerting/server/usage/lib/group_connectors_by_consumers.ts index 9dfaa9706b774..3c29f31f0eb9f 100644 --- a/x-pack/plugins/alerting/server/usage/lib/group_connectors_by_consumers.ts +++ b/x-pack/plugins/alerting/server/usage/lib/group_connectors_by_consumers.ts @@ -20,7 +20,7 @@ export function groupConnectorsByConsumers( acc[consumer.key] = consumer.actions.connector_types.buckets.reduce((accBucket, bucket) => { accBucket[replaceDotSymbols(bucket.key)] = bucket.doc_count; return accBucket; - }, {} as Record); + }, {} as Record); return acc; - }, {} as Record); + }, {} as Record>); } diff --git a/x-pack/plugins/synthetics/server/legacy_uptime/lib/adapters/telemetry/kibana_telemetry_adapter.ts b/x-pack/plugins/synthetics/server/legacy_uptime/lib/adapters/telemetry/kibana_telemetry_adapter.ts index 4f3760a2add5c..21c1542451058 100644 --- a/x-pack/plugins/synthetics/server/legacy_uptime/lib/adapters/telemetry/kibana_telemetry_adapter.ts +++ b/x-pack/plugins/synthetics/server/legacy_uptime/lib/adapters/telemetry/kibana_telemetry_adapter.ts @@ -416,11 +416,12 @@ export class KibanaTelemetryAdapter { }); return Object.values(this.collector).reduce( - (acc, cum) => ({ - overview_page: acc.overview_page + cum.overview_page, - monitor_page: acc.monitor_page + cum.monitor_page, - settings_page: acc.settings_page + cum.settings_page, - }), + (acc, cum) => + Object.assign(cum, { + overview_page: acc.overview_page + cum.overview_page, + monitor_page: acc.monitor_page + cum.monitor_page, + settings_page: acc.settings_page + cum.settings_page, + }), { overview_page: 0, monitor_page: 0, settings_page: 0 } ); } From 2b61dbdf6a8a2cb0911084a5c28bd57bb3b9a03f Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Mon, 15 May 2023 13:53:48 +0200 Subject: [PATCH 12/15] more type fixes --- x-pack/plugins/canvas/public/lib/filter.ts | 5 +++-- x-pack/plugins/cases/server/telemetry/types.ts | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/x-pack/plugins/canvas/public/lib/filter.ts b/x-pack/plugins/canvas/public/lib/filter.ts index 1ae0a423d19a9..767cf53e16f6d 100644 --- a/x-pack/plugins/canvas/public/lib/filter.ts +++ b/x-pack/plugins/canvas/public/lib/filter.ts @@ -12,6 +12,7 @@ import { FilterField, FilterViewInstance, FlattenFilterViewInstance, + FormattedFilterViewInstance, } from '../../types/filters'; const SELECT_FILTER = 'selectFilter'; @@ -30,11 +31,11 @@ export const formatFilterView = return filterViewKeys.reduce((acc, key) => { acc[key] = { label: filterView[key].label, - formattedValue: (filterView[key].formatter ?? defaultFormatter)(filterValue[key]), + formattedValue: (filterView[key].formatter ?? defaultFormatter)(filterValue[key])!, component: filterView[key].component, }; return acc; - }, {} as Record); + }, {} as FormattedFilterViewInstance); }; export const flattenFilterView = (filterValue: FilterType) => (filterView: FilterViewInstance) => { diff --git a/x-pack/plugins/cases/server/telemetry/types.ts b/x-pack/plugins/cases/server/telemetry/types.ts index b38d46d04283b..a68ed0a36b7d5 100644 --- a/x-pack/plugins/cases/server/telemetry/types.ts +++ b/x-pack/plugins/cases/server/telemetry/types.ts @@ -11,7 +11,7 @@ import type { Owner } from '../../common/constants/types'; export type BucketKeyString = Omit & { key: string }; -interface Bucket { +export interface Bucket { doc_count: number; key: T; } From 5b4fdfa4618ed21b153d0b3a832d64fe7a44f66f Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Mon, 15 May 2023 14:38:29 +0200 Subject: [PATCH 13/15] more type fixes, again --- x-pack/plugins/fleet/common/authz.ts | 66 +++++++++++++++------------- 1 file changed, 36 insertions(+), 30 deletions(-) diff --git a/x-pack/plugins/fleet/common/authz.ts b/x-pack/plugins/fleet/common/authz.ts index 55e46bfaef9f0..27e72857392a8 100644 --- a/x-pack/plugins/fleet/common/authz.ts +++ b/x-pack/plugins/fleet/common/authz.ts @@ -65,6 +65,8 @@ interface CalculateParams { isSuperuser: boolean; } +type PrivilegeMap = Record; + export const calculateAuthz = ({ fleet, integrations, @@ -102,23 +104,26 @@ export function calculatePackagePrivilegesFromCapabilities( return {}; } - const endpointActions = Object.entries(ENDPOINT_PRIVILEGES).reduce< - FleetAuthz['packagePrivileges']['endpoint'] - >((acc, [privilege, { privilegeName }]) => { - acc[privilege] = { - executePackageAction: (capabilities.siem && capabilities.siem[privilegeName]) || false, - }; - return acc; - }, {}); - - const transformActions = Object.keys(capabilities.transform).reduce< - FleetAuthz['packagePrivileges']['transform'] - >((acc, privilegeName) => { - acc[privilegeName] = { - executePackageAction: capabilities.transform[privilegeName] || false, - }; - return acc; - }, {}); + const endpointActions = Object.entries(ENDPOINT_PRIVILEGES).reduce( + (acc, [privilege, { privilegeName }]) => { + acc[privilege] = { + executePackageAction: + (capabilities.siem && (capabilities.siem[privilegeName] as boolean)) || false, + }; + return acc; + }, + {} + ); + + const transformActions = Object.keys(capabilities.transform).reduce( + (acc, privilegeName) => { + acc[privilegeName] = { + executePackageAction: (capabilities.transform[privilegeName] as boolean) || false, + }; + return acc; + }, + {} + ); return { endpoint: { @@ -158,19 +163,20 @@ export function calculatePackagePrivilegesFromKibanaPrivileges( return {}; } - const endpointActions = Object.entries(ENDPOINT_PRIVILEGES).reduce< - FleetAuthz['packagePrivileges']['endpoint'] - >((acc, [privilege, { appId, privilegeSplit, privilegeName }]) => { - const kibanaPrivilege = getAuthorizationFromPrivileges( - kibanaPrivileges, - `${appId}${privilegeSplit}`, - privilegeName - ); - acc[privilege] = { - executePackageAction: kibanaPrivilege, - }; - return acc; - }, {}); + const endpointActions = Object.entries(ENDPOINT_PRIVILEGES).reduce( + (acc, [privilege, { appId, privilegeSplit, privilegeName }]) => { + const kibanaPrivilege = getAuthorizationFromPrivileges( + kibanaPrivileges, + `${appId}${privilegeSplit}`, + privilegeName + ); + acc[privilege] = { + executePackageAction: kibanaPrivilege, + }; + return acc; + }, + {} + ); const hasTransformAdmin = getAuthorizationFromPrivileges( kibanaPrivileges, From 3980d564d786c7702a026066804173b44de40571 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Mon, 15 May 2023 15:21:26 +0200 Subject: [PATCH 14/15] more type fixes, again --- .../server/routes/settings/apm_indices/save_apm_indices.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/apm/server/routes/settings/apm_indices/save_apm_indices.ts b/x-pack/plugins/apm/server/routes/settings/apm_indices/save_apm_indices.ts index d51e2f927925c..a5926c6dfc0cb 100644 --- a/x-pack/plugins/apm/server/routes/settings/apm_indices/save_apm_indices.ts +++ b/x-pack/plugins/apm/server/routes/settings/apm_indices/save_apm_indices.ts @@ -33,7 +33,7 @@ function removeEmpty(apmIndices: Partial) { .map(([key, value]) => [key, value?.trim()]) .filter(([_, value]) => !!value) .reduce((obj, [key, value]) => { - obj[key as string] = value; + obj[key] = value; return obj; - }, {}); + }, {} as Record); } From bd9388017970403ffff362558c24a4f3c3added6 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Mon, 22 May 2023 11:52:35 +0200 Subject: [PATCH 15/15] fix type --- .../src/document_migrator/document_migrator.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/document_migrator/document_migrator.ts b/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/document_migrator/document_migrator.ts index 50e9409900ced..1c46bd0764fc5 100644 --- a/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/document_migrator/document_migrator.ts +++ b/packages/core/saved-objects/core-saved-objects-migration-server-internal/src/document_migrator/document_migrator.ts @@ -99,7 +99,7 @@ export class DocumentMigrator implements VersionedTransformer { throw new Error('Migrations are not ready. Make sure prepareMigrations is called first.'); } - return Object.entries(this.migrations).reduce( + return Object.entries(this.migrations).reduce( (acc, [type, { latestVersion, immediateVersion }]) => { const version = includeDeferred ? latestVersion : immediateVersion; const latestMigrationVersion =