diff --git a/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/search/aggregations/validation.ts b/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/search/aggregations/validation.ts index d5dfbb8e8cb1d..d058feb31ba78 100644 --- a/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/search/aggregations/validation.ts +++ b/packages/core/saved-objects/core-saved-objects-api-server-internal/src/lib/search/aggregations/validation.ts @@ -98,13 +98,14 @@ const validateAggregationContainer = ( ) => { return Object.entries(container).reduce( (memo, [aggName, aggregation]) => { - if (aggregationKeys.includes(aggName)) { - return memo; + if (!aggregationKeys.includes(aggName)) { + (memo as Record)[aggName] = validateAggregationType( + aggName, + aggregation, + childContext(context, aggName) + ); } - return { - ...memo, - [aggName]: validateAggregationType(aggName, aggregation, childContext(context, aggName)), - }; + return memo; }, {} ); diff --git a/packages/kbn-config-schema/src/types/object_type.ts b/packages/kbn-config-schema/src/types/object_type.ts index fa72ee61ab7ff..8a77d80ad4ad3 100644 --- a/packages/kbn-config-schema/src/types/object_type.ts +++ b/packages/kbn-config-schema/src/types/object_type.ts @@ -159,10 +159,7 @@ export class ObjectType

extends Type> ...newProps, }).reduce((memo, [key, value]) => { if (value !== null && value !== undefined) { - return { - ...memo, - [key]: value, - }; + (memo as Record)[key] = value; } return memo; }, {} as ExtendedProps); @@ -178,10 +175,7 @@ export class ObjectType

extends Type> public extendsDeep(options: ExtendsDeepOptions) { const extendedProps = Object.entries(this.props).reduce((memo, [key, value]) => { if (value !== null && value !== undefined) { - return { - ...memo, - [key]: value.extendsDeep(options), - }; + Object.assign(memo, { [key]: value.extendsDeep(options) }); } return memo; }, {} as P); diff --git a/packages/kbn-custom-integrations/src/state_machines/create/pipelines/fields.ts b/packages/kbn-custom-integrations/src/state_machines/create/pipelines/fields.ts index 3a7fef9ce98a7..62becff6733c8 100644 --- a/packages/kbn-custom-integrations/src/state_machines/create/pipelines/fields.ts +++ b/packages/kbn-custom-integrations/src/state_machines/create/pipelines/fields.ts @@ -50,10 +50,10 @@ const updateTouchedFields = ...context, touchedFields: { ...context.touchedFields, - ...Object.keys(event.fields).reduce( - (acc, field) => ({ ...acc, [field]: true }), - {} as WithTouchedFields['touchedFields'] - ), + ...Object.keys(event.fields).reduce((acc, field) => { + acc[field as keyof WithTouchedFields['touchedFields']] = true; + return acc; + }, {} as WithTouchedFields['touchedFields']), }, }; return [mergedContext, event]; diff --git a/packages/kbn-es-query/src/kuery/functions/utils/get_full_field_name_node.ts b/packages/kbn-es-query/src/kuery/functions/utils/get_full_field_name_node.ts index 6d40a91f54b7f..d1278f26b6439 100644 --- a/packages/kbn-es-query/src/kuery/functions/utils/get_full_field_name_node.ts +++ b/packages/kbn-es-query/src/kuery/functions/utils/get_full_field_name_node.ts @@ -34,24 +34,17 @@ export function getFullFieldNameNode( const nestedPathFromField = subTypeNested?.nested.path; if (nestedPath && !nestedPathFromField) { - return [ - ...acc, - `${field.name} is not a nested field but is in nested group "${nestedPath}" in the KQL expression.`, - ]; - } - - if (nestedPathFromField && !nestedPath) { - return [ - ...acc, - `${field.name} is a nested field, but is not in a nested group in the KQL expression.`, - ]; - } - - if (nestedPathFromField !== nestedPath) { - return [ - ...acc, - `Nested field ${field.name} is being queried with the incorrect nested path. The correct path is ${subTypeNested?.nested.path}.`, - ]; + acc.push( + `${field.name} is not a nested field but is in nested group "${nestedPath}" in the KQL expression.` + ); + } else if (nestedPathFromField && !nestedPath) { + acc.push( + `${field.name} is a nested field, but is not in a nested group in the KQL expression.` + ); + } else if (nestedPathFromField !== nestedPath) { + acc.push( + `Nested field ${field.name} is being queried with the incorrect nested path. The correct path is ${subTypeNested?.nested.path}.` + ); } return acc; diff --git a/packages/kbn-i18n/src/core/helper.ts b/packages/kbn-i18n/src/core/helper.ts index 405f0596cd037..eef4bb88e4927 100644 --- a/packages/kbn-i18n/src/core/helper.ts +++ b/packages/kbn-i18n/src/core/helper.ts @@ -18,17 +18,12 @@ export const unique = (arr: T[] = []): T[] => [...new Set(arr)]; const merge = (a: any, b: any): { [k: string]: any } => unique([...Object.keys(a), ...Object.keys(b)]).reduce((acc, key) => { if (isObject(a[key]) && isObject(b[key]) && !Array.isArray(a[key]) && !Array.isArray(b[key])) { - return { - ...acc, - [key]: merge(a[key], b[key]), - }; + acc[key] = merge(a[key], b[key]); + } else { + acc[key] = b[key] === undefined ? a[key] : b[key]; } - - return { - ...acc, - [key]: b[key] === undefined ? a[key] : b[key], - }; - }, {}); + return acc; + }, {} as { [k: string]: any }); export const mergeAll = (...sources: any[]) => sources.filter(isObject).reduce((acc, source) => merge(acc, source)); diff --git a/packages/kbn-i18n/src/loader.ts b/packages/kbn-i18n/src/loader.ts index 5b4417b54646c..55c924e989daf 100644 --- a/packages/kbn-i18n/src/loader.ts +++ b/packages/kbn-i18n/src/loader.ts @@ -148,13 +148,10 @@ export async function getAllTranslations(): Promise<{ [key: string]: Translation const locales = getRegisteredLocales(); const translations = await Promise.all(locales.map(getTranslationsByLocale)); - return locales.reduce( - (acc, locale, index) => ({ - ...acc, - [locale]: translations[index], - }), - {} - ); + return locales.reduce((acc, locale, index) => { + acc[locale] = translations[index]; + return acc; + }, {} as { [key: string]: Translation }); } /** diff --git a/packages/kbn-json-ast/src/snip.ts b/packages/kbn-json-ast/src/snip.ts index 52ccaef46df2e..e0430aef0b4cc 100644 --- a/packages/kbn-json-ast/src/snip.ts +++ b/packages/kbn-json-ast/src/snip.ts @@ -25,7 +25,8 @@ export function snip(source: string, snips: Snip[]) { .reduce((acc: Snip[], s) => { const prev = acc.at(-1); if (!prev || prev[1] < s[0]) { - return [...acc, s]; + acc.push(s); + return acc; } if (prev[2] || s[2]) { diff --git a/packages/kbn-rule-data-utils/src/alerts_as_data_rbac.ts b/packages/kbn-rule-data-utils/src/alerts_as_data_rbac.ts index 06fe06c63b4b9..3320e016c4657 100644 --- a/packages/kbn-rule-data-utils/src/alerts_as_data_rbac.ts +++ b/packages/kbn-rule-data-utils/src/alerts_as_data_rbac.ts @@ -77,12 +77,14 @@ export const getEsQueryConfig = (params?: GetEsQueryConfigParamType): EsQueryCon if (params == null) { return defaultConfigValues; } - const paramKeysWithValues = Object.keys(params).reduce((acc: EsQueryConfig, key) => { + const paramKeysWithValues = Object.keys(params).reduce((acc, key) => { const configKey = key as ConfigKeys; if (params[configKey] != null) { - return { [key]: params[configKey], ...acc }; + acc[key] = params[configKey]; + } else { + acc[key] = defaultConfigValues[configKey]; } - return { [key]: defaultConfigValues[configKey], ...acc }; - }, {} as EsQueryConfig); - return paramKeysWithValues; + return acc; + }, {} as Record); + return paramKeysWithValues as EsQueryConfig; }; diff --git a/packages/kbn-securitysolution-grouping/src/containers/query/helpers.ts b/packages/kbn-securitysolution-grouping/src/containers/query/helpers.ts index 530af49c7e6f0..4ef6a34681bb9 100644 --- a/packages/kbn-securitysolution-grouping/src/containers/query/helpers.ts +++ b/packages/kbn-securitysolution-grouping/src/containers/query/helpers.ts @@ -7,6 +7,7 @@ */ import { Filter, FILTERS } from '@kbn/es-query'; + export const getEmptyValue = () => '—'; type StrictFilter = Filter & { @@ -19,9 +20,8 @@ export const createGroupFilter = ( ): StrictFilter[] => values != null && values.length > 0 ? values.reduce( - (acc: StrictFilter[], query) => [ - ...acc, - { + (acc: StrictFilter[], query) => { + acc.push({ meta: { alias: null, disabled: false, @@ -39,8 +39,9 @@ export const createGroupFilter = ( }, }, }, - }, - ], + }); + return acc; + }, [ { meta: { diff --git a/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.ts b/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.ts index a1ab4c14728e4..f3f6089a86217 100644 --- a/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.ts +++ b/packages/kbn-securitysolution-list-utils/src/get_ids_and_namespaces/index.ts @@ -28,9 +28,10 @@ export const getIdsAndNamespaces = ({ } }) .reduce<{ ids: string[]; namespaces: NamespaceType[] }>( - (acc, { listId, namespaceType }) => ({ - ids: [...acc.ids, listId], - namespaces: [...acc.namespaces, namespaceType], - }), + (acc, { listId, namespaceType }) => { + acc.ids.push(listId); + acc.namespaces.push(namespaceType); + return acc; + }, { ids: [], namespaces: [] } ); diff --git a/packages/kbn-securitysolution-list-utils/src/helpers/index.ts b/packages/kbn-securitysolution-list-utils/src/helpers/index.ts index 0c9be1359552f..f53e71c882fc7 100644 --- a/packages/kbn-securitysolution-list-utils/src/helpers/index.ts +++ b/packages/kbn-securitysolution-list-utils/src/helpers/index.ts @@ -853,7 +853,8 @@ export const getFormattedBuilderEntries = ( parentIndex, allowCustomFieldOptions ); - return [...acc, newItemEntry]; + acc.push(newItemEntry); + return acc; } else { const parentEntry: FormattedBuilderEntry = { correspondingKeywordField: undefined, diff --git a/packages/kbn-std/src/iteration/map.ts b/packages/kbn-std/src/iteration/map.ts index 44765d69e1bd0..a65951cc14db5 100644 --- a/packages/kbn-std/src/iteration/map.ts +++ b/packages/kbn-std/src/iteration/map.ts @@ -58,5 +58,8 @@ export async function asyncMapWithLimit( return results .sort(([a], [b]) => a - b) - .reduce((acc: T2[], [, result]) => acc.concat(result), []); + .reduce((acc: T2[], [, result]) => { + acc.push(...result); + return acc; + }, []); } diff --git a/packages/kbn-telemetry-tools/src/tools/serializer.ts b/packages/kbn-telemetry-tools/src/tools/serializer.ts index a33d2d78e4137..25a00571430a0 100644 --- a/packages/kbn-telemetry-tools/src/tools/serializer.ts +++ b/packages/kbn-telemetry-tools/src/tools/serializer.ts @@ -90,7 +90,8 @@ export function getConstraints(node: ts.Node, program: ts.Program): any { return types.reduce((acc, typeNode) => { const constraints = getConstraints(typeNode, program); const contraintsArray = Array.isArray(constraints) ? constraints : [constraints]; - return [...acc, ...contraintsArray]; + acc.push(...contraintsArray); + return acc; }, []); } @@ -178,7 +179,7 @@ export function getDescriptor(node: ts.Node, program: ts.Program): Descriptor | const constraints = getConstraints(constraint, program); const constraintsArray = Array.isArray(constraints) ? constraints : [constraints]; if (typeof constraintsArray[0] === 'string') { - return constraintsArray.reduce((acc, c) => ({ ...acc, [c]: descriptor }), {}); + return constraintsArray.reduce((acc, c) => Object.assign(acc, { [c]: descriptor }), {}); } } return { '@@INDEX@@': descriptor }; diff --git a/packages/kbn-test/src/kbn_archiver_cli.ts b/packages/kbn-test/src/kbn_archiver_cli.ts index 6cf1a0496146f..65eb57eda863f 100644 --- a/packages/kbn-test/src/kbn_archiver_cli.ts +++ b/packages/kbn-test/src/kbn_archiver_cli.ts @@ -34,10 +34,10 @@ function parseTypesFlag(flags: Flags) { } const types = typeof flags.type === 'string' ? [flags.type] : flags.type; - return types.reduce( - (acc: string[], type) => [...acc, ...type.split(',').map((t) => t.trim())], - [] - ); + return types.reduce((acc: string[], type) => { + acc.push(...type.split(',').map((t) => t.trim())); + return acc; + }, []); } export function runKbnArchiverCli() { diff --git a/src/plugins/chart_expressions/expression_xy/common/expression_functions/common_data_layer_args.ts b/src/plugins/chart_expressions/expression_xy/common/expression_functions/common_data_layer_args.ts index b9e2bd6dbac67..949264f330057 100644 --- a/src/plugins/chart_expressions/expression_xy/common/expression_functions/common_data_layer_args.ts +++ b/src/plugins/chart_expressions/expression_xy/common/expression_functions/common_data_layer_args.ts @@ -28,13 +28,13 @@ export const commonDataLayerArgs: Omit< seriesType: { aliases: ['_'], types: ['string'], - options: [...Object.values(SeriesTypes)], + options: Object.values(SeriesTypes), help: strings.getSeriesTypeHelp(), required: true, strict: true, }, xScaleType: { - options: [...Object.values(XScaleTypes)], + options: Object.values(XScaleTypes), help: strings.getXScaleTypeHelp(), strict: true, }, @@ -60,7 +60,7 @@ export const commonDataLayerArgs: Omit< }, curveType: { types: ['string'], - options: [...Object.values(XYCurveTypes)], + options: Object.values(XYCurveTypes), help: strings.getCurveTypeHelp(), strict: true, }, diff --git a/src/plugins/chart_expressions/expression_xy/common/expression_functions/common_xy_args.ts b/src/plugins/chart_expressions/expression_xy/common/expression_functions/common_xy_args.ts index 799dc12b1ea5b..cf6e6fbff1205 100644 --- a/src/plugins/chart_expressions/expression_xy/common/expression_functions/common_xy_args.ts +++ b/src/plugins/chart_expressions/expression_xy/common/expression_functions/common_xy_args.ts @@ -27,13 +27,13 @@ export const commonXYArgs: CommonXYFn['args'] = { }, fittingFunction: { types: ['string'], - options: [...Object.values(FittingFunctions)], + options: Object.values(FittingFunctions), help: strings.getFittingFunctionHelp(), strict: true, }, endValue: { types: ['string'], - options: [...Object.values(EndValues)], + options: Object.values(EndValues), help: strings.getEndValueHelp(), strict: true, }, @@ -44,7 +44,7 @@ export const commonXYArgs: CommonXYFn['args'] = { }, valueLabels: { types: ['string'], - options: [...Object.values(ValueLabelModes)], + options: Object.values(ValueLabelModes), help: strings.getValueLabelsHelp(), strict: true, default: ValueLabelModes.HIDE, diff --git a/src/plugins/chart_expressions/expression_xy/common/expression_functions/reference_line.ts b/src/plugins/chart_expressions/expression_xy/common/expression_functions/reference_line.ts index d19d9e38333d7..37bd8a5efa0b9 100644 --- a/src/plugins/chart_expressions/expression_xy/common/expression_functions/reference_line.ts +++ b/src/plugins/chart_expressions/expression_xy/common/expression_functions/reference_line.ts @@ -59,7 +59,7 @@ export const referenceLineFunction: ReferenceLineFn = { }, lineStyle: { types: ['string'], - options: [...Object.values(LineStyles)], + options: Object.values(LineStyles), help: i18n.translate('expressionXY.decorationConfig.lineStyle.help', { defaultMessage: 'The style of the reference line', }), @@ -78,12 +78,12 @@ export const referenceLineFunction: ReferenceLineFn = { help: i18n.translate('expressionXY.decorationConfig.icon.help', { defaultMessage: 'An optional icon used for reference lines', }), - options: [...Object.values(AvailableReferenceLineIcons)], + options: Object.values(AvailableReferenceLineIcons), strict: true, }, iconPosition: { types: ['string'], - options: [...Object.values(IconPositions)], + options: Object.values(IconPositions), help: i18n.translate('expressionXY.decorationConfig.iconPosition.help', { defaultMessage: 'The placement of the icon for the reference line', }), @@ -98,7 +98,7 @@ export const referenceLineFunction: ReferenceLineFn = { }, fill: { types: ['string'], - options: [...Object.values(FillStyles)], + options: Object.values(FillStyles), help: i18n.translate('expressionXY.decorationConfig.fill.help', { defaultMessage: 'Fill', }), diff --git a/src/plugins/chart_expressions/expression_xy/common/expression_functions/reference_line_decoration_config.ts b/src/plugins/chart_expressions/expression_xy/common/expression_functions/reference_line_decoration_config.ts index ad25d7e0c3226..6dd6b36a3b051 100644 --- a/src/plugins/chart_expressions/expression_xy/common/expression_functions/reference_line_decoration_config.ts +++ b/src/plugins/chart_expressions/expression_xy/common/expression_functions/reference_line_decoration_config.ts @@ -39,7 +39,7 @@ export const referenceLineDecorationConfigFunction: ReferenceLineDecorationConfi }, lineStyle: { types: ['string'], - options: [...Object.values(LineStyles)], + options: Object.values(LineStyles), help: i18n.translate('expressionXY.decorationConfig.lineStyle.help', { defaultMessage: 'The style of the reference line', }), @@ -56,12 +56,12 @@ export const referenceLineDecorationConfigFunction: ReferenceLineDecorationConfi help: i18n.translate('expressionXY.decorationConfig.icon.help', { defaultMessage: 'An optional icon used for reference lines', }), - options: [...Object.values(AvailableReferenceLineIcons)], + options: Object.values(AvailableReferenceLineIcons), strict: true, }, iconPosition: { types: ['string'], - options: [...Object.values(IconPositions)], + options: Object.values(IconPositions), help: i18n.translate('expressionXY.decorationConfig.iconPosition.help', { defaultMessage: 'The placement of the icon for the reference line', }), @@ -75,7 +75,7 @@ export const referenceLineDecorationConfigFunction: ReferenceLineDecorationConfi }, fill: { types: ['string'], - options: [...Object.values(FillStyles)], + options: Object.values(FillStyles), help: i18n.translate('expressionXY.decorationConfig.fill.help', { defaultMessage: 'Fill', }), diff --git a/src/plugins/chart_expressions/expression_xy/common/expression_functions/y_axis_config.ts b/src/plugins/chart_expressions/expression_xy/common/expression_functions/y_axis_config.ts index 64f58dc5acb98..9a2a3d5f68870 100644 --- a/src/plugins/chart_expressions/expression_xy/common/expression_functions/y_axis_config.ts +++ b/src/plugins/chart_expressions/expression_xy/common/expression_functions/y_axis_config.ts @@ -22,7 +22,7 @@ export const yAxisConfigFunction: YAxisConfigFn = { ...commonAxisConfigArgs, mode: { types: ['string'], - options: [...Object.values(AxisModes)], + options: Object.values(AxisModes), help: strings.getAxisModeHelp(), }, boundsMargin: { @@ -30,7 +30,7 @@ export const yAxisConfigFunction: YAxisConfigFn = { help: strings.getAxisBoundsMarginHelp(), }, scaleType: { - options: [...Object.values(YScaleTypes)], + options: Object.values(YScaleTypes), help: strings.getAxisScaleTypeHelp(), default: YScaleTypes.LINEAR, }, diff --git a/src/plugins/chart_expressions/expression_xy/common/utils/log_datatables.ts b/src/plugins/chart_expressions/expression_xy/common/utils/log_datatables.ts index 4cb20a44b5c92..64487ac93dc0a 100644 --- a/src/plugins/chart_expressions/expression_xy/common/utils/log_datatables.ts +++ b/src/plugins/chart_expressions/expression_xy/common/utils/log_datatables.ts @@ -99,8 +99,8 @@ export const logDatatable = ( if (layer.layerType === LayerTypes.ANNOTATIONS || layer.type === REFERENCE_LINE) { return dimensions; } - - return [...dimensions, ...getLayerDimensions(layer)]; + dimensions.push(...getLayerDimensions(layer)); + return dimensions; }, []); layerDimensions.push([ diff --git a/src/plugins/controls/common/control_group/control_group_migrations.ts b/src/plugins/controls/common/control_group/control_group_migrations.ts index 4f119ebeae4d6..80c3adf8d8ec1 100644 --- a/src/plugins/controls/common/control_group/control_group_migrations.ts +++ b/src/plugins/controls/common/control_group/control_group_migrations.ts @@ -48,10 +48,9 @@ export const removeHideExcludeAndHideExists = (input: ControlGroupInput) => { delete explicitInput.hideExclude; delete explicitInput.hideExists; } - return { - ...panelAccumulator, - [panelId]: panel, - }; + + panelAccumulator[panelId] = panel; + return panelAccumulator; }, {} ); diff --git a/src/plugins/controls/public/control_group/embeddable/control_group_helpers.ts b/src/plugins/controls/public/control_group/embeddable/control_group_helpers.ts index 7318a489feac9..4f7306db6f914 100644 --- a/src/plugins/controls/public/control_group/embeddable/control_group_helpers.ts +++ b/src/plugins/controls/public/control_group/embeddable/control_group_helpers.ts @@ -19,8 +19,7 @@ export const getNextPanelOrder = (panels?: ControlsPanels) => { if (Object.keys(panels ?? {}).length > 0) { nextOrder = Object.values(panels ?? {}).reduce((highestSoFar, panel) => { - if (panel.order > highestSoFar) highestSoFar = panel.order; - return highestSoFar; + return Math.max(highestSoFar, panel.order); }, 0) + 1; } return nextOrder; diff --git a/src/plugins/data/common/search/aggs/agg_configs.ts b/src/plugins/data/common/search/aggs/agg_configs.ts index 7cab863fba11d..4386ef38d7e89 100644 --- a/src/plugins/data/common/search/aggs/agg_configs.ts +++ b/src/plugins/data/common/search/aggs/agg_configs.ts @@ -509,7 +509,10 @@ export class AggConfigs { getResponseAggs(): AggConfig[] { return this.getRequestAggs().reduce(function (responseValuesAggs, agg: AggConfig) { const aggs = agg.getResponseAggs(); - return aggs ? responseValuesAggs.concat(aggs) : responseValuesAggs; + if (aggs) { + responseValuesAggs.push(...aggs); + } + return responseValuesAggs; }, [] as AggConfig[]); } diff --git a/src/plugins/data/common/search/search_source/search_source.ts b/src/plugins/data/common/search/search_source/search_source.ts index b42cb7fdf4f25..5fa1157bf5b4f 100644 --- a/src/plugins/data/common/search/search_source/search_source.ts +++ b/src/plugins/data/common/search/search_source/search_source.ts @@ -265,7 +265,8 @@ export class SearchSource { typeof queryString === 'string' ? this.parseActiveIndexPatternFromQueryString(queryString) : queryString?.reduce((acc: string[], currStr: string) => { - return acc.concat(this.parseActiveIndexPatternFromQueryString(currStr)); + acc.push(...this.parseActiveIndexPatternFromQueryString(currStr)); + return acc; }, []) ?? []; const activeIndexPattern = filters?.reduce((acc, f) => { @@ -280,12 +281,9 @@ export class SearchSource { } else { return difference(acc, filtersArray); } - } else { - return acc; } - } else { - return acc; } + return acc; }, indexPatternFromQuery); const dedupActiveIndexPattern = new Set([...activeIndexPattern]); diff --git a/src/plugins/data_views/common/data_views/data_view.ts b/src/plugins/data_views/common/data_views/data_view.ts index 3cea4505b572c..f12b0b640e3c5 100644 --- a/src/plugins/data_views/common/data_views/data_view.ts +++ b/src/plugins/data_views/common/data_views/data_view.ts @@ -555,10 +555,10 @@ export class DataView implements DataViewBase { getAllRuntimeFields(): Record { return Object.keys(this.runtimeFieldMap).reduce>( - (acc, fieldName) => ({ - ...acc, - [fieldName]: this.getRuntimeField(fieldName)!, - }), + (acc, fieldName) => { + acc[fieldName] = this.getRuntimeField(fieldName)!; + return acc; + }, {} ); } diff --git a/src/plugins/data_views/common/fields/field_list.ts b/src/plugins/data_views/common/fields/field_list.ts index 660f2f8ad2f97..ca89331f8b671 100644 --- a/src/plugins/data_views/common/fields/field_list.ts +++ b/src/plugins/data_views/common/fields/field_list.ts @@ -92,7 +92,7 @@ export const fieldList = ( constructor() { super(); - specs.map((field) => this.add(field)); + specs.forEach((field) => this.add(field)); } public readonly getAll = () => [...this.byName.values()]; diff --git a/src/plugins/event_annotation/common/fetch_event_annotations/request_event_annotations.ts b/src/plugins/event_annotation/common/fetch_event_annotations/request_event_annotations.ts index 56748495a3456..d1d3ccc3f07ae 100644 --- a/src/plugins/event_annotation/common/fetch_event_annotations/request_event_annotations.ts +++ b/src/plugins/event_annotation/common/fetch_event_annotations/request_event_annotations.ts @@ -89,7 +89,8 @@ export const requestEventAnnotations = ( .map((g) => g.dataView.value) .reduce((acc, current) => { if (acc.find((el) => el.id === current.id)) return acc; - return [...acc, current]; + acc.push(current); + return acc; }, []); const loadedDataViews = await Promise.all( diff --git a/src/plugins/expressions/common/executor/executor.ts b/src/plugins/expressions/common/executor/executor.ts index e8d01b15fd81d..66f29cf195dd1 100644 --- a/src/plugins/expressions/common/executor/executor.ts +++ b/src/plugins/expressions/common/executor/executor.ts @@ -255,10 +255,8 @@ export class Executor = Record 0 ? newAst.chain.slice(0, realIndex) : []; const nextChain = newAst.chain.slice(realIndex + 1); - return { - ...newAst, - chain: [...prevChain, transformedFn, ...nextChain], - }; + newAst.chain = [...prevChain, transformedFn, ...nextChain]; + return newAst; } if (transformedFn.type === 'expression') { @@ -266,10 +264,8 @@ export class Executor = Record 0 ? newAst.chain.slice(0, realIndex) : []; const nextChain = newAst.chain.slice(realIndex + 1); additionalFunctions += chain.length - 1; - return { - ...newAst, - chain: [...prevChain, ...chain, ...nextChain], - }; + newAst.chain = [...prevChain, ...chain, ...nextChain]; + return newAst; } return newAst; diff --git a/src/plugins/files/server/file_service/internal_file_service.ts b/src/plugins/files/server/file_service/internal_file_service.ts index b224a28313a70..3325a4dfc2c86 100644 --- a/src/plugins/files/server/file_service/internal_file_service.ts +++ b/src/plugins/files/server/file_service/internal_file_service.ts @@ -122,13 +122,10 @@ export class InternalFileService { return format === 'array' ? result - : ids.reduce<{ [id: string]: IFile | null }>( - (acc, id, i) => ({ - ...acc, - [id]: result[i], - }), - {} - ); + : ids.reduce<{ [id: string]: IFile | null }>((acc, id, i) => { + acc[id] = result[i]; + return acc; + }, {}); } catch (e) { this.logger.error(`Could not retrieve files: ${e}`); throw e; 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 d51830bf307d3..e56c4ac12dd96 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 @@ -59,13 +59,10 @@ export class RollupSearchCapabilities extends DefaultSearchCapabilities { return acc; }, this.createUiRestriction({}) as Record); - return Object.keys(this.availableMetrics).reduce( - (acc, item) => ({ - ...acc, - [item]: getFields(this.availableMetrics[item]), - }), - baseRestrictions - ); + return Object.keys(this.availableMetrics).reduce((acc, item) => { + (acc as Record)[item] = getFields(this.availableMetrics[item]); + return acc; + }, baseRestrictions); } public get whiteListedGroupByFields() { diff --git a/src/plugins/vis_types/timeseries/server/lib/vis_data/get_series_data.ts b/src/plugins/vis_types/timeseries/server/lib/vis_data/get_series_data.ts index 55d71fb69eb36..1d5aca2191111 100644 --- a/src/plugins/vis_types/timeseries/server/lib/vis_data/get_series_data.ts +++ b/src/plugins/vis_types/timeseries/server/lib/vis_data/get_series_data.ts @@ -117,7 +117,10 @@ export async function getSeriesData( [panel.id]: { annotations, id: panel.id, - series: series.reduce((acc, s) => acc.concat(s), []), + series: series.reduce((acc, s) => { + acc.push(...s); + return acc; + }, []), }, }; } catch (err) { diff --git a/x-pack/plugins/actions/server/usage/lib/parse_connector_type_bucket.ts b/x-pack/plugins/actions/server/usage/lib/parse_connector_type_bucket.ts index 96e1610c635d8..d1ef5c14e73e7 100644 --- a/x-pack/plugins/actions/server/usage/lib/parse_connector_type_bucket.ts +++ b/x-pack/plugins/actions/server/usage/lib/parse_connector_type_bucket.ts @@ -20,11 +20,12 @@ export function parseActionRunOutcomeByConnectorTypesBucket( const connectorTypes = connectorTypeBuckets as AvgActionRunOutcomeByConnectorTypeBucket[]; return connectorTypes.reduce((acc, connectorType) => { const outcomes = connectorType.outcome?.count?.buckets ?? []; - return { - ...acc, - [replaceFirstAndLastDotSymbols(connectorType.key)]: outcomes.reduce((accBucket, bucket) => { - return { ...accBucket, [replaceFirstAndLastDotSymbols(bucket.key)]: bucket.doc_count || 0 }; - }, {}), - }; + (acc as Record)[replaceFirstAndLastDotSymbols(connectorType.key)] = + outcomes.reduce((accBucket, bucket) => { + (accBucket as Record)[replaceFirstAndLastDotSymbols(bucket.key)] = + bucket.doc_count || 0; + return accBucket; + }, {}); + return acc; }, {}); } diff --git a/x-pack/plugins/alerting/server/lib/monitoring.ts b/x-pack/plugins/alerting/server/lib/monitoring.ts index bff533cfc591f..c460d1ce0fc66 100644 --- a/x-pack/plugins/alerting/server/lib/monitoring.ts +++ b/x-pack/plugins/alerting/server/lib/monitoring.ts @@ -128,7 +128,8 @@ export const convertMonitoringFromRawAndVerify = ( export const getExecutionDurationPercentiles = (history: RuleMonitoringHistory[]) => { const durationSamples = history.reduce((duration, historyItem) => { if (typeof historyItem.duration === 'number') { - return [...duration, historyItem.duration]; + duration.push(historyItem.duration); + return duration; } return duration; }, []); diff --git a/x-pack/plugins/alerting/server/rules_client/common/mapped_params_utils.ts b/x-pack/plugins/alerting/server/rules_client/common/mapped_params_utils.ts index 3479ca374e596..22c85e74038e3 100644 --- a/x-pack/plugins/alerting/server/rules_client/common/mapped_params_utils.ts +++ b/x-pack/plugins/alerting/server/rules_client/common/mapped_params_utils.ts @@ -99,7 +99,7 @@ export const getModifiedSearchFields = (searchFields: string[] | undefined) => { return searchFields.reduce((result, field) => { const modifiedField = getModifiedField(field); if (modifiedField) { - return [...result, modifiedField]; + result.push(modifiedField); } return result; }, []); diff --git a/x-pack/plugins/alerting/server/rules_client/common/retry_if_bulk_operation_conflicts.ts b/x-pack/plugins/alerting/server/rules_client/common/retry_if_bulk_operation_conflicts.ts index 7a652c5230f47..b1164ebe173bd 100644 --- a/x-pack/plugins/alerting/server/rules_client/common/retry_if_bulk_operation_conflicts.ts +++ b/x-pack/plugins/alerting/server/rules_client/common/retry_if_bulk_operation_conflicts.ts @@ -90,7 +90,7 @@ const handler = async ({ const ruleIdsWithConflictError = currentErrors.reduce((acc, error) => { if (error.status === 409) { - return [...acc, error.rule.id]; + acc.push(error.rule.id); } return acc; }, []); @@ -153,7 +153,10 @@ const handler = async ({ errors: [...acc.errors, ...item.errors], rules: [...acc.rules, ...item.rules], accListSpecificForBulkOperation: acc.accListSpecificForBulkOperation.map( - (element, index) => [...element, ...item.accListSpecificForBulkOperation[index]] + (element, index) => { + element.push(...item.accListSpecificForBulkOperation[index]); + return element; + } ), }; }, diff --git a/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/transform_legacy_actions.ts b/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/transform_legacy_actions.ts index 1218e96a8dfd7..f4eb8370b7d7b 100644 --- a/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/transform_legacy_actions.ts +++ b/x-pack/plugins/alerting/server/rules_client/lib/siem_legacy_actions/transform_legacy_actions.ts @@ -38,12 +38,8 @@ export const transformFromLegacyActions = ( return legacyActionsAttr.actions.reduce((acc, action) => { const { actionRef, action_type_id: actionTypeId, group, params } = action; - if (!actionReference[actionRef]) { - return acc; - } - return [ - ...acc, - { + if (actionReference[actionRef]) { + acc.push({ group, params, uuid: v4(), @@ -54,7 +50,8 @@ export const transformFromLegacyActions = ( notifyWhen: transformToNotifyWhen(legacyActionsAttr.ruleThrottle) ?? 'onActiveAlert', throttle: transformToAlertThrottle(legacyActionsAttr.ruleThrottle), }, - }, - ]; + }); + } + return acc; }, []); }; 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 49b7c7374213d..0808104c2f5d4 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 @@ -436,28 +436,16 @@ export function parseExecutionFailureByRuleType( if (acc[reason]) { if (acc[reason][ruleType]) { - return { - ...acc, - [reason]: { - ...acc[reason], - [ruleType]: acc[reason][ruleType] + bucket.doc_count, - }, - }; + acc[reason][ruleType] = acc[reason][ruleType] + bucket.doc_count; + } else { + acc[reason][ruleType] = bucket.doc_count; } - return { - ...acc, - [reason]: { - ...acc[reason], - [ruleType]: bucket.doc_count, - }, + } else { + acc[reason] = { + [ruleType]: bucket.doc_count, }; } - return { - ...acc, - [reason]: { - [ruleType]: bucket.doc_count, - }, - }; + return acc; }, {} ); @@ -472,22 +460,17 @@ export function parsePercentileAggs( ruleTypeId?: string ) { return Object.keys(percentiles ?? {}).reduce((acc, percentileKey: string) => { - let result = {}; const percentileKeyMapped = percentileFieldNameMapping[percentileKey]; if (percentileKeyMapped) { if (ruleTypeId) { - result = { - [percentileKeyMapped]: { - [ruleTypeId]: percentiles[percentileKey] ?? 0, - }, + (acc as Record)[percentileKeyMapped] = { + [ruleTypeId]: percentiles[percentileKey] ?? 0, }; } else { - result = { - [percentileKeyMapped]: percentiles[percentileKey] ?? 0, - }; + (acc as Record)[percentileKeyMapped] = percentiles[percentileKey] ?? 0; } } - return Object.assign(acc, result); + return acc; }, {}); } 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 dd81a2abeb57e..3a6b012f3688b 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 @@ -71,9 +71,7 @@ export async function getServicesCounts({ response?.aggregations?.service_groups.buckets ?? {}; return Object.keys(buckets).reduce>((acc, key) => { - return { - ...acc, - [key]: buckets[key].services_count.value, - }; + acc[key] = buckets[key].services_count.value; + return acc; }, {}); } diff --git a/x-pack/plugins/apm/server/routes/transactions/breakdown/index.ts b/x-pack/plugins/apm/server/routes/transactions/breakdown/index.ts index 69a79aac13bba..1cbb3770b870a 100644 --- a/x-pack/plugins/apm/server/routes/transactions/breakdown/index.ts +++ b/x-pack/plugins/apm/server/routes/transactions/breakdown/index.ts @@ -187,25 +187,27 @@ export async function getTransactionBreakdown({ const formattedValues = formatBucket(bucket); const time = bucket.key; - const updatedSeries = kpiNames.reduce((p, kpiName) => { - const { name, percentage } = formattedValues.find( - (val) => val.name === kpiName - ) || { - name: kpiName, - percentage: null, - }; - - if (!p[name]) { - p[name] = []; - } - return { - ...p, - [name]: p[name].concat({ + const updatedSeries = kpiNames.reduce( + (p, kpiName) => { + const { name, percentage } = formattedValues.find( + (val) => val.name === kpiName + ) || { + name: kpiName, + percentage: null, + }; + + if (!p[name]) { + p[name] = []; + } + + p[name] = p[name].concat({ x: time, y: percentage, - }), - }; - }, prev); + }); + return p; + }, + { ...prev } + ); const lastValues = Object.values(updatedSeries).map(last); diff --git a/x-pack/plugins/cases/server/client/cases/update.ts b/x-pack/plugins/cases/server/client/cases/update.ts index b2baff721302f..90cedb62090d6 100644 --- a/x-pack/plugins/cases/server/client/cases/update.ts +++ b/x-pack/plugins/cases/server/client/cases/update.ts @@ -469,7 +469,8 @@ export const update = async ( const builtUserActions = userActionsDict != null ? Object.keys(userActionsDict).reduce((acc, key) => { - return [...acc, ...userActionsDict[key]]; + acc.push(...userActionsDict[key]); + return acc; }, []) : []; diff --git a/x-pack/plugins/cases/server/client/metrics/actions/aggregations/isolate_host.ts b/x-pack/plugins/cases/server/client/metrics/actions/aggregations/isolate_host.ts index e75015730090c..358e0e03d1a93 100644 --- a/x-pack/plugins/cases/server/client/metrics/actions/aggregations/isolate_host.ts +++ b/x-pack/plugins/cases/server/client/metrics/actions/aggregations/isolate_host.ts @@ -15,6 +15,7 @@ interface ActionsAggregation { buckets: Array<{ key: string; doc_count: number }>; }; } + type ActionsAggregationResponse = ActionsAggregation | undefined; export class IsolateHostActions implements AggregationBuilder { @@ -35,7 +36,10 @@ export class IsolateHostActions implements AggregationBuilder>( - (result, { key, doc_count: total }) => ({ ...result, [key]: total }), + (result, { key, doc_count: total }) => { + result[key] = total; + return result; + }, {} ); return { diff --git a/x-pack/plugins/cases/server/services/transform.ts b/x-pack/plugins/cases/server/services/transform.ts index 20bdc795be763..6c750d544db16 100644 --- a/x-pack/plugins/cases/server/services/transform.ts +++ b/x-pack/plugins/cases/server/services/transform.ts @@ -84,14 +84,11 @@ export function transformFieldsToESModel(connector: CaseConnector): ConnectorPer return []; } - return Object.entries(connector.fields).reduce( - (acc, [key, value]) => [ - ...acc, - { - key, - value, - }, - ], - [] - ); + return Object.entries(connector.fields).reduce((acc, [key, value]) => { + acc.push({ + key, + value, + }); + return acc; + }, []); } diff --git a/x-pack/plugins/cases/server/services/user_actions/operations/create.ts b/x-pack/plugins/cases/server/services/user_actions/operations/create.ts index 1f2ba3dc8f046..e26931f8c63f3 100644 --- a/x-pack/plugins/cases/server/services/user_actions/operations/create.ts +++ b/x-pack/plugins/cases/server/services/user_actions/operations/create.ts @@ -313,11 +313,11 @@ export class UserActionPersister { payload: { attachment: attachment.attachment }, }); - if (commentUserAction == null) { - return acc; + if (commentUserAction != null) { + acc.push(commentUserAction); } - return [...acc, commentUserAction]; + return acc; }, []); await this.bulkCreateAndLog({ diff --git a/x-pack/plugins/cases/server/telemetry/queries/cases.ts b/x-pack/plugins/cases/server/telemetry/queries/cases.ts index abd1979d752e8..918193a3b7221 100644 --- a/x-pack/plugins/cases/server/telemetry/queries/cases.ts +++ b/x-pack/plugins/cases/server/telemetry/queries/cases.ts @@ -147,23 +147,20 @@ export const getCasesTelemetryData = async ({ const getCasesSavedObjectTelemetry = async ( savedObjectsClient: ISavedObjectsRepository ): Promise> => { - const caseByOwnerAggregationQuery = OWNERS.reduce( - (aggQuery, owner) => ({ - ...aggQuery, - [owner]: { - filter: { - term: { - [`${CASE_SAVED_OBJECT}.attributes.owner`]: owner, - }, - }, - aggs: { - ...getCountsAggregationQuery(CASE_SAVED_OBJECT), - ...getAssigneesAggregations(), + const caseByOwnerAggregationQuery = OWNERS.reduce((aggQuery, owner) => { + (aggQuery as Record)[owner] = { + filter: { + term: { + [`${CASE_SAVED_OBJECT}.attributes.owner`]: owner, }, }, - }), - {} - ); + aggs: { + ...getCountsAggregationQuery(CASE_SAVED_OBJECT), + ...getAssigneesAggregations(), + }, + }; + return aggQuery; + }, {}); return savedObjectsClient.find({ page: 0, @@ -254,22 +251,19 @@ const getCommentsSavedObjectTelemetry = async ( }, }); - const attachmentsByOwnerAggregationQuery = OWNERS.reduce( - (aggQuery, owner) => ({ - ...aggQuery, - [owner]: { - filter: { - term: { - [`${CASE_COMMENT_SAVED_OBJECT}.attributes.owner`]: owner, - }, - }, - aggs: { - ...attachmentRegistries(), + const attachmentsByOwnerAggregationQuery = OWNERS.reduce((aggQuery, owner) => { + (aggQuery as Record)[owner] = { + filter: { + term: { + [`${CASE_COMMENT_SAVED_OBJECT}.attributes.owner`]: owner, }, }, - }), - {} - ); + aggs: { + ...attachmentRegistries(), + }, + }; + return aggQuery; + }, {}); return savedObjectsClient.find({ page: 0, @@ -307,23 +301,20 @@ const getFilesTelemetry = async ( }, }); - const filesByOwnerAggregationQuery = OWNERS.reduce( - (aggQuery, owner) => ({ - ...aggQuery, - [owner]: { - filter: { - term: { - [`${FILE_SO_TYPE}.attributes.Meta.owner`]: owner, - }, - }, - aggs: { - ...averageSize(), - ...top20MimeTypes(), + const filesByOwnerAggregationQuery = OWNERS.reduce((aggQuery, owner) => { + (aggQuery as Record)[owner] = { + filter: { + term: { + [`${FILE_SO_TYPE}.attributes.Meta.owner`]: owner, }, }, - }), - {} - ); + aggs: { + ...averageSize(), + ...top20MimeTypes(), + }, + }; + return aggQuery; + }, {}); const filterCaseIdExists = fromKueryExpression(`${FILE_SO_TYPE}.attributes.Meta.caseIds: *`); diff --git a/x-pack/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/update_ml_inference_mappings.ts b/x-pack/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/update_ml_inference_mappings.ts index fa8d06bde503f..aca5edc2076d0 100644 --- a/x-pack/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/update_ml_inference_mappings.ts +++ b/x-pack/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/update_ml_inference_mappings.ts @@ -68,30 +68,8 @@ const generateTextExpansionMappingProperties = (sourceFields: string[], targetFi }, }, }, - ...targetFields.reduce( - (previous, targetField) => ({ - ...previous, - [targetField]: { - properties: { - model_id: { - type: 'keyword', - }, - predicted_value: { - type: 'sparse_vector', - }, - }, - }, - }), - {} - ), - }; -}; - -const formDefaultElserMappingProps = (sourceFields: string[]) => { - return sourceFields.reduce( - (previous, sourceField) => ({ - ...previous, - [`${sourceField}_expanded`]: { + ...targetFields.reduce((previous, targetField) => { + (previous as Record)[targetField] = { properties: { model_id: { type: 'keyword', @@ -100,10 +78,26 @@ const formDefaultElserMappingProps = (sourceFields: string[]) => { type: 'sparse_vector', }, }, + }; + return previous; + }, {}), + }; +}; + +const formDefaultElserMappingProps = (sourceFields: string[]) => { + return sourceFields.reduce((previous, sourceField) => { + (previous as Record)[`${sourceField}_expanded`] = { + properties: { + model_id: { + type: 'keyword', + }, + predicted_value: { + type: 'sparse_vector', + }, }, - }), - {} - ); + }; + return previous; + }, {}); }; const isTextExpansionModel = async (modelId: string, esClient: ElasticsearchClient) => { diff --git a/x-pack/plugins/fleet/common/services/simplified_package_policy_helper.ts b/x-pack/plugins/fleet/common/services/simplified_package_policy_helper.ts index ca42d65d8a399..6a366df2b177e 100644 --- a/x-pack/plugins/fleet/common/services/simplified_package_policy_helper.ts +++ b/x-pack/plugins/fleet/common/services/simplified_package_policy_helper.ts @@ -69,10 +69,7 @@ export function generateInputId(input: NewPackagePolicyInput) { export function formatInputs(inputs: NewPackagePolicy['inputs']) { return inputs.reduce((acc, input) => { const inputId = generateInputId(input); - if (!acc) { - acc = {}; - } - acc[inputId] = { + acc![inputId] = { enabled: input.enabled, vars: formatVars(input.vars), streams: formatStreams(input.streams), @@ -101,9 +98,6 @@ export function formatVars(vars: NewPackagePolicy['inputs'][number]['vars']) { function formatStreams(streams: NewPackagePolicy['inputs'][number]['streams']) { return streams.reduce((acc, stream) => { - if (!acc) { - acc = {}; - } acc[stream.data_stream.dataset] = { enabled: stream.enabled, vars: formatVars(stream.vars), diff --git a/x-pack/plugins/fleet/server/routes/utils/filter_utils.ts b/x-pack/plugins/fleet/server/routes/utils/filter_utils.ts index 4b34bd788d29a..8b30c98bb09ab 100644 --- a/x-pack/plugins/fleet/server/routes/utils/filter_utils.ts +++ b/x-pack/plugins/fleet/server/routes/utils/filter_utils.ts @@ -44,55 +44,56 @@ export const validateFilterKueryNode = ({ skipNormalization, }: ValidateFilterKueryNodeParams): ValidateFilterKueryNode[] => { let localNestedKeys: string | undefined; - return astFilter.arguments.reduce((kueryNode: string[], ast: KueryNode, index: number) => { - if (hasNestedKey && ast.type === 'literal' && ast.value != null) { - localNestedKeys = ast.value; - } else if (ast.type === 'literal' && ast.value && typeof ast.value === 'string') { - const key = ast.value.replace('.attributes', ''); - const mappingKey = 'properties.' + key.split('.').join('.properties.'); - const field = get(indexMapping, mappingKey); - - if (field != null && field.type === 'nested') { + return astFilter.arguments.reduce( + (kueryNode: ValidateFilterKueryNode[], ast: KueryNode, index: number) => { + if (hasNestedKey && ast.type === 'literal' && ast.value != null) { localNestedKeys = ast.value; + } else if (ast.type === 'literal' && ast.value && typeof ast.value === 'string') { + const key = ast.value.replace('.attributes', ''); + const mappingKey = 'properties.' + key.split('.').join('.properties.'); + const field = get(indexMapping, mappingKey); + + if (field != null && field.type === 'nested') { + localNestedKeys = ast.value; + } } - } - if (ast.arguments) { - const myPath = `${path}.${index}`; - return [ - ...kueryNode, - ...validateFilterKueryNode({ - astFilter: ast, - types, - indexMapping, - storeValue: ast.type === 'function' && astFunctionType.includes(ast.function), - path: `${myPath}.arguments`, - hasNestedKey: ast.type === 'function' && ast.function === 'nested', - nestedKeys: localNestedKeys || nestedKeys, - skipNormalization, - }), - ]; - } - if (storeValue && index === 0) { - const splitPath = path.split('.'); - const astPath = path.includes('.') - ? splitPath.slice(0, splitPath.length - 1).join('.') - : `${path}.${index}`; - const key = nestedKeys != null ? `${nestedKeys}.${ast.value}` : ast.value; - - return [ - ...kueryNode, - { + if (ast.arguments) { + const myPath = `${path}.${index}`; + kueryNode.push( + ...validateFilterKueryNode({ + astFilter: ast, + types, + indexMapping, + storeValue: ast.type === 'function' && astFunctionType.includes(ast.function), + path: `${myPath}.arguments`, + hasNestedKey: ast.type === 'function' && ast.function === 'nested', + nestedKeys: localNestedKeys || nestedKeys, + skipNormalization, + }) + ); + return kueryNode; + } + if (storeValue && index === 0) { + const splitPath = path.split('.'); + const astPath = path.includes('.') + ? splitPath.slice(0, splitPath.length - 1).join('.') + : `${path}.${index}`; + const key = nestedKeys != null ? `${nestedKeys}.${ast.value}` : ast.value; + + kueryNode.push({ astPath, - error: hasFilterKeyError(key, types, indexMapping, skipNormalization), + error: hasFilterKeyError(key, types, indexMapping, skipNormalization)!, isSavedObjectAttr: isSavedObjectAttr(key, indexMapping), key, type: getType(key), - }, - ]; - } - return kueryNode; - }, []); + } as ValidateFilterKueryNode); + return kueryNode; + } + return kueryNode; + }, + [] + ); }; const getType = (key: string | undefined | null) => { diff --git a/x-pack/plugins/fleet/server/services/actions/utils.ts b/x-pack/plugins/fleet/server/services/actions/utils.ts index a61b028d8c54f..b531a7b41ec69 100644 --- a/x-pack/plugins/fleet/server/services/actions/utils.ts +++ b/x-pack/plugins/fleet/server/services/actions/utils.ts @@ -150,33 +150,34 @@ export const validateFilterKueryNode = ({ indexType = 'actions', path = 'arguments', }: ValidateFilterKueryNodeParams): ValidateFilterKueryNode[] => { - return astFilter.arguments.reduce((kueryNode: string[], ast: KueryNode, index: number) => { - if (ast.arguments) { - const myPath = `${path}.${index}`; - return [ - ...kueryNode, - ...validateFilterKueryNode({ - astFilter: ast, - types, - indexMapping, - path: `${myPath}.arguments`, - }), - ]; - } - - if (index === 0) { - const splitPath = path.split('.'); - return [ - ...kueryNode, - { + return astFilter.arguments.reduce( + (kueryNode: ValidateFilterKueryNode[], ast: KueryNode, index: number) => { + if (ast.arguments) { + const myPath = `${path}.${index}`; + kueryNode.push( + ...validateFilterKueryNode({ + astFilter: ast, + types, + indexMapping, + path: `${myPath}.arguments`, + }) + ); + return kueryNode; + } + + if (index === 0) { + const splitPath = path.split('.'); + kueryNode.push({ astPath: splitPath.slice(0, splitPath.length - 1).join('.'), - error: hasFieldKeyError(ast.value, types, indexMapping, indexType), + error: hasFieldKeyError(ast.value, types, indexMapping, indexType)!, key: ast.value, type: getFieldType(ast.value, indexMapping), - }, - ]; - } + } as ValidateFilterKueryNode); + return kueryNode; + } - return kueryNode; - }, []); + return kueryNode; + }, + [] + ); }; 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 8309910be6f53..12372aea925a1 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 @@ -333,10 +333,8 @@ export class UninstallTokenService implements UninstallTokenServiceInterface { const newTokensMap = missingTokenPolicyIds.reduce((acc, policyId) => { const token = this.generateToken(); - return { - ...acc, - [policyId]: token, - }; + acc[policyId] = token; + return acc; }, {} as Record); await this.persistTokens(missingTokenPolicyIds, newTokensMap); diff --git a/x-pack/plugins/index_management/common/lib/component_template_serialization.ts b/x-pack/plugins/index_management/common/lib/component_template_serialization.ts index c9a272d2e98ee..db58e2f651ad4 100644 --- a/x-pack/plugins/index_management/common/lib/component_template_serialization.ts +++ b/x-pack/plugins/index_management/common/lib/component_template_serialization.ts @@ -39,7 +39,11 @@ const getIndexTemplatesToUsedBy = (indexTemplatesEs: TemplateFromEs[]) => { return indexTemplatesEs.reduce((acc, item) => { if (item.index_template.composed_of) { item.index_template.composed_of.forEach((component) => { - acc[component] = acc[component] ? [...acc[component], item.name] : [item.name]; + if (!acc[component]) { + acc[component] = []; + } + acc[component].push(item.name); + return acc; }); } return acc; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts index 3691367e4a8f2..e11dde1c33ca5 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts @@ -147,21 +147,20 @@ const parseFields = ( * If the children parsed have any error we concatenate them in our accumulator. */ if (parsedChildren.errors) { - acc.errors = [...acc.errors, ...parsedChildren.errors]; + acc.errors.push(...parsedChildren.errors); } } acc.value[fieldName] = parsedField; if (Boolean(parametersRemoved.length)) { - acc.errors = [ - ...acc.errors, + acc.errors.push( ...parametersRemoved.map((paramName) => ({ code: 'ERR_PARAMETER' as 'ERR_PARAMETER', fieldPath, paramName, - })), - ]; + })) + ); } } diff --git a/x-pack/plugins/infra/server/lib/alerting/common/utils.ts b/x-pack/plugins/infra/server/lib/alerting/common/utils.ts index dc518e1e08cf7..56120cca85a2f 100644 --- a/x-pack/plugins/infra/server/lib/alerting/common/utils.ts +++ b/x-pack/plugins/infra/server/lib/alerting/common/utils.ts @@ -277,8 +277,9 @@ export const getGroupByObject = ( groupByKeysObjectMapping[groupSet] = unflattenObject( Array.isArray(groupBy) ? groupBy.reduce((result, group, index) => { - return { ...result, [group]: groupSetKeys[index]?.trim() }; - }, {}) + result[group] = groupSetKeys[index]?.trim(); + return result; + }, {} as Record) : { [groupBy]: groupSet } ); }); diff --git a/x-pack/plugins/ingest_pipelines/server/lib/mapper.ts b/x-pack/plugins/ingest_pipelines/server/lib/mapper.ts index 421ee636856b8..806832301e117 100644 --- a/x-pack/plugins/ingest_pipelines/server/lib/mapper.ts +++ b/x-pack/plugins/ingest_pipelines/server/lib/mapper.ts @@ -70,10 +70,10 @@ function parseAndValidate(file: string) { } const missingHeaders = REQUIRED_CSV_HEADERS.reduce((acc, header) => { - if (meta.fields.includes(header)) { - return acc; + if (!meta.fields.includes(header)) { + acc.push(header); } - return [...acc, header]; + return acc; }, []); if (missingHeaders.length > 0) { diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_item_types.ts b/x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_item_types.ts index 14d12ceb950a3..90d8dc27581f3 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_item_types.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_item_types.ts @@ -148,11 +148,9 @@ export const getAllListItemTypes = async ( }); // Dictionary of found items - return transformedResponse.data.reduce( - (acc, item) => ({ - ...acc, - [item.item_id]: item, - }), - {} - ); + return transformedResponse.data.reduce((acc, item) => { + // eslint-disable-next-line no-param-reassign + acc[item.item_id] = item; + return acc; + }, {} as Record); }; diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_types.ts b/x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_types.ts index 870acc6cc4462..f13ef5f7f1111 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_types.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/utils/import/find_all_exception_list_types.ts @@ -20,6 +20,7 @@ export interface ExceptionListQueryInfo { listId: string; namespaceType: NamespaceType; } + /** * Helper to build out a filter using list_id * @param objects {array} - exception lists to add to filter @@ -129,11 +130,9 @@ export const getAllListTypes = async ( } // Dictionary of found lists - return foundListsResponse.data.reduce( - (acc, list) => ({ - ...acc, - [list.list_id]: list, - }), - {} - ); + return foundListsResponse.data.reduce((acc, list) => { + // eslint-disable-next-line no-param-reassign + acc[list.list_id] = list; + return acc; + }, {} as Record); }; diff --git a/x-pack/plugins/lists/server/services/items/create_list_items_bulk.ts b/x-pack/plugins/lists/server/services/items/create_list_items_bulk.ts index 54965751a058a..453fde25475c8 100644 --- a/x-pack/plugins/lists/server/services/items/create_list_items_bulk.ts +++ b/x-pack/plugins/lists/server/services/items/create_list_items_bulk.ts @@ -73,7 +73,8 @@ export const createListItemsBulk = async ({ ...elasticQuery, }; const createBody: CreateEsBulkTypeSchema = { create: { _index: listItemIndex } }; - return [...accum, createBody, elasticBody]; + accum.push(createBody, elasticBody); + return accum; } else { // TODO: Report errors with return values from the bulk insert into another index or saved object return accum; diff --git a/x-pack/plugins/log_explorer/public/state_machines/log_explorer_profile/src/url_state_storage_service.ts b/x-pack/plugins/log_explorer/public/state_machines/log_explorer_profile/src/url_state_storage_service.ts index 5fd46dec9bf0b..2dba4b7b965f1 100644 --- a/x-pack/plugins/log_explorer/public/state_machines/log_explorer_profile/src/url_state_storage_service.ts +++ b/x-pack/plugins/log_explorer/public/state_machines/log_explorer_profile/src/url_state_storage_service.ts @@ -244,8 +244,8 @@ const getVisibleControlPanels = (dataView: DataView | undefined) => export const getVisibleControlPanelsConfig = (dataView?: DataView) => { return getVisibleControlPanels(dataView).reduce((panelsMap, panelKey) => { const config = controlPanelConfigs[panelKey]; - - return { ...panelsMap, [panelKey]: config }; + panelsMap[panelKey] = config; + return panelsMap; }, {} as ControlPanels); }; diff --git a/x-pack/plugins/logs_shared/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts b/x-pack/plugins/logs_shared/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts index 66de5699cfb3e..f6627de68759f 100644 --- a/x-pack/plugins/logs_shared/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts +++ b/x-pack/plugins/logs_shared/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts @@ -201,16 +201,14 @@ export class LogsSharedKibanaLogEntriesAdapter implements LogEntriesAdapter { function mapHitsToLogEntryDocuments(hits: SortedSearchHit[], fields: string[]): LogEntryDocument[] { return hits.map((hit) => { const logFields = fields.reduce<{ [fieldName: string]: JsonArray }>( - (flattenedFields, field) => - field in hit.fields - ? { - ...flattenedFields, - [field]: hit.fields[field], - } - : flattenedFields, + (flattenedFields, field) => { + if (field in hit.fields) { + flattenedFields[field] = hit.fields[field]; + } + return flattenedFields; + }, {} ); - return { id: hit._id, index: hit._index, diff --git a/x-pack/plugins/logs_shared/server/lib/domains/log_entries_domain/log_entries_domain.ts b/x-pack/plugins/logs_shared/server/lib/domains/log_entries_domain/log_entries_domain.ts index 92829c676b935..e9c63c1605e50 100644 --- a/x-pack/plugins/logs_shared/server/lib/domains/log_entries_domain/log_entries_domain.ts +++ b/x-pack/plugins/logs_shared/server/lib/domains/log_entries_domain/log_entries_domain.ts @@ -66,12 +66,14 @@ export interface ILogsSharedLogEntriesDomain { params: LogEntriesAroundParams, columnOverrides?: LogViewColumnConfiguration[] ): Promise<{ entries: LogEntry[]; hasMoreBefore?: boolean; hasMoreAfter?: boolean }>; + getLogEntries( requestContext: LogsSharedPluginRequestHandlerContext, logView: LogViewReference, params: LogEntriesParams, columnOverrides?: LogViewColumnConfiguration[] ): Promise<{ entries: LogEntry[]; hasMoreBefore?: boolean; hasMoreAfter?: boolean }>; + getLogSummaryBucketsBetween( requestContext: LogsSharedPluginRequestHandlerContext, logView: LogViewReference, @@ -80,6 +82,7 @@ export interface ILogsSharedLogEntriesDomain { bucketSize: number, filterQuery?: LogEntryQuery ): Promise; + getLogSummaryHighlightBucketsBetween( requestContext: LogsSharedPluginRequestHandlerContext, logView: LogViewReference, @@ -89,6 +92,7 @@ export interface ILogsSharedLogEntriesDomain { highlightQueries: string[], filterQuery?: LogEntryQuery ): Promise; + getLogEntryDatasets( requestContext: LogsSharedPluginRequestHandlerContext, timestampField: string, @@ -390,7 +394,7 @@ const getRequiredFields = ( const fieldsFromCustomColumns = configuration.columns.reduce( (accumulatedFields, logColumn) => { if (logViewFieldColumnConfigurationRT.is(logColumn)) { - return [...accumulatedFields, logColumn.fieldColumn.field]; + accumulatedFields.push(logColumn.fieldColumn.field); } return accumulatedFields; }, diff --git a/x-pack/plugins/logs_shared/server/services/log_entries/log_entries_search_strategy.ts b/x-pack/plugins/logs_shared/server/services/log_entries/log_entries_search_strategy.ts index f0f5c6304d615..a6c089ce70234 100644 --- a/x-pack/plugins/logs_shared/server/services/log_entries/log_entries_search_strategy.ts +++ b/x-pack/plugins/logs_shared/server/services/log_entries/log_entries_search_strategy.ts @@ -255,7 +255,7 @@ const getRequiredFields = ( ): string[] => { const fieldsFromColumns = columns.reduce((accumulatedFields, logColumn) => { if (logViewFieldColumnConfigurationRT.is(logColumn)) { - return [...accumulatedFields, logColumn.fieldColumn.field]; + accumulatedFields.push(logColumn.fieldColumn.field); } return accumulatedFields; }, []); diff --git a/x-pack/plugins/logs_shared/server/services/log_entries/queries/log_entries.ts b/x-pack/plugins/logs_shared/server/services/log_entries/queries/log_entries.ts index 18ee4b0104366..37ce61ea9f0c6 100644 --- a/x-pack/plugins/logs_shared/server/services/log_entries/queries/log_entries.ts +++ b/x-pack/plugins/logs_shared/server/services/log_entries/queries/log_entries.ts @@ -87,13 +87,10 @@ const createHighlightClause = (highlightQuery: JsonObject | undefined, fields: s ? { highlight: { boundary_scanner: 'word' as const, - fields: fields.reduce( - (highlightFieldConfigs, fieldName) => ({ - ...highlightFieldConfigs, - [fieldName]: {}, - }), - {} - ), + fields: fields.reduce((highlightFieldConfigs, fieldName) => { + (highlightFieldConfigs as Record)[fieldName] = {}; + return highlightFieldConfigs; + }, {}), fragment_size: 1, number_of_fragments: 100, post_tags: [''], diff --git a/x-pack/plugins/monitoring/server/lib/elasticsearch/nodes/get_nodes/handle_response.ts b/x-pack/plugins/monitoring/server/lib/elasticsearch/nodes/get_nodes/handle_response.ts index 9fc06f1f9654f..f8e9142b1df66 100644 --- a/x-pack/plugins/monitoring/server/lib/elasticsearch/nodes/get_nodes/handle_response.ts +++ b/x-pack/plugins/monitoring/server/lib/elasticsearch/nodes/get_nodes/handle_response.ts @@ -44,10 +44,8 @@ export function handleResponse( accum: { [nodeId: string]: any }, { key: nodeId, by_date: byDate }: { key: string; by_date: any } ) => { - return { - ...accum, - [nodeId]: uncovertMetricNames(byDate), - }; + accum[nodeId] = uncovertMetricNames(byDate); + return accum; }, {} ); diff --git a/x-pack/plugins/monitoring/server/lib/logstash/merge_pipeline_versions.ts b/x-pack/plugins/monitoring/server/lib/logstash/merge_pipeline_versions.ts index d8eb6d2f0695b..069a96e2aa082 100644 --- a/x-pack/plugins/monitoring/server/lib/logstash/merge_pipeline_versions.ts +++ b/x-pack/plugins/monitoring/server/lib/logstash/merge_pipeline_versions.ts @@ -12,7 +12,8 @@ export const mergePipelineVersions = (versions: PipelineVersion[]): PipelineVers (acc: { [key: string]: PipelineVersion }, pipeline: PipelineVersion) => { const existing = acc[pipeline.hash]; if (!existing) { - return { ...acc, [pipeline.hash]: pipeline }; + acc[pipeline.hash] = pipeline; + return acc; } existing.firstSeen = Math.min(existing.firstSeen, pipeline.firstSeen); diff --git a/x-pack/plugins/monitoring/server/routes/api/v1/_health/errors_helpers/build_errors.ts b/x-pack/plugins/monitoring/server/routes/api/v1/_health/errors_helpers/build_errors.ts index 9e9704828548b..8d64f67652db1 100644 --- a/x-pack/plugins/monitoring/server/routes/api/v1/_health/errors_helpers/build_errors.ts +++ b/x-pack/plugins/monitoring/server/routes/api/v1/_health/errors_helpers/build_errors.ts @@ -41,14 +41,10 @@ interface ErrorDetails { export const buildErrors = (modulesBucket: any[]): Products => { return (modulesBucket ?? []).reduce((module, { key, errors_by_dataset: errorsByDataset }) => { const datasets = buildMetricsets(errorsByDataset.buckets); - if (Object.keys(datasets).length === 0) { - return { ...module }; + if (Object.keys(datasets).length > 0) { + module[key] = datasets; } - - return { - ...module, - [key]: datasets, - }; + return module; }, {} as Products); }; @@ -56,14 +52,10 @@ const buildMetricsets = (errorsByDataset: any[]): ErrorsByMetricset => { return (errorsByDataset ?? []).reduce((dataset, { key, latest_docs: latestDocs }) => { const errors = buildErrorMessages(latestDocs.hits.hits ?? []); - if (errors.length === 0) { - return { ...dataset }; + if (errors.length > 0) { + dataset[key] = errors; } - - return { - ...dataset, - [key]: errors, - }; + return dataset; }, {} as ErrorsByMetricset); }; diff --git a/x-pack/plugins/monitoring/server/telemetry_collection/get_kibana_stats.ts b/x-pack/plugins/monitoring/server/telemetry_collection/get_kibana_stats.ts index cc6a23a0646e1..cd6f9319a2895 100644 --- a/x-pack/plugins/monitoring/server/telemetry_collection/get_kibana_stats.ts +++ b/x-pack/plugins/monitoring/server/telemetry_collection/get_kibana_stats.ts @@ -26,6 +26,7 @@ export function rollUpTotals( const addOnTotal = addOn[field]?.total || 0; return { total: rolledUpTotal + addOnTotal }; } + export function rollUpIndices(rolledUp: ClusterUsageStats) { return rolledUp.indices + 1; } @@ -115,13 +116,11 @@ export function getUsageStats(rawStats: estypes.SearchResponse // e.g: we want `xpack.reporting` to just be `reporting` const plugins = { ...pluginsTop, ...xpack }; - return { - ...accum, - [clusterUuid]: { - ...stats, - plugins, - }, + accum[clusterUuid] = { + ...stats, + plugins, }; + return accum; }, {} as ClustersUsageStats); } diff --git a/x-pack/plugins/observability/common/custom_threshold_rule/metrics_explorer.ts b/x-pack/plugins/observability/common/custom_threshold_rule/metrics_explorer.ts index 66913385123c4..84073ebea1d8a 100644 --- a/x-pack/plugins/observability/common/custom_threshold_rule/metrics_explorer.ts +++ b/x-pack/plugins/observability/common/custom_threshold_rule/metrics_explorer.ts @@ -15,7 +15,10 @@ type MetricExplorerAggregations = typeof METRIC_EXPLORER_AGGREGATIONS[number]; const metricsExplorerAggregationKeys = METRIC_EXPLORER_AGGREGATIONS.reduce< Record ->((acc, agg) => ({ ...acc, [agg]: null }), {} as Record); +>((acc, agg) => { + acc[agg] = null; + return acc; +}, {} as Record); export const metricsExplorerAggregationRT = rt.keyof(metricsExplorerAggregationKeys); @@ -26,10 +29,10 @@ export type MetricExplorerCustomMetricAggregations = Exclude< const metricsExplorerCustomMetricAggregationKeys = xor( METRIC_EXPLORER_AGGREGATIONS, OMITTED_AGGREGATIONS_FOR_CUSTOM_METRICS -).reduce>( - (acc, agg) => ({ ...acc, [agg]: null }), - {} as Record -); +).reduce>((acc, agg) => { + acc[agg as MetricExplorerCustomMetricAggregations] = null; + return acc; +}, {} as Record); export const metricsExplorerCustomMetricAggregationRT = rt.keyof( metricsExplorerCustomMetricAggregationKeys ); diff --git a/x-pack/plugins/observability/common/custom_threshold_rule/types.ts b/x-pack/plugins/observability/common/custom_threshold_rule/types.ts index dc5b434e0a7e9..897e4e6f7a744 100644 --- a/x-pack/plugins/observability/common/custom_threshold_rule/types.ts +++ b/x-pack/plugins/observability/common/custom_threshold_rule/types.ts @@ -272,7 +272,10 @@ export enum InfraFormatterType { export type SnapshotCustomAggregation = typeof SNAPSHOT_CUSTOM_AGGREGATIONS[number]; const snapshotCustomAggregationKeys = SNAPSHOT_CUSTOM_AGGREGATIONS.reduce< Record ->((acc, agg) => ({ ...acc, [agg]: null }), {} as Record); +>((acc, agg) => { + acc[agg] = null; + return acc; +}, {} as Record); export const SnapshotCustomAggregationRT = rt.keyof(snapshotCustomAggregationKeys); diff --git a/x-pack/plugins/observability/server/services/slo/aggregations/get_custom_metric_indicator_aggregation.ts b/x-pack/plugins/observability/server/services/slo/aggregations/get_custom_metric_indicator_aggregation.ts index ceb51bdfef199..35a858ffecec8 100644 --- a/x-pack/plugins/observability/server/services/slo/aggregations/get_custom_metric_indicator_aggregation.ts +++ b/x-pack/plugins/observability/server/services/slo/aggregations/get_custom_metric_indicator_aggregation.ts @@ -20,17 +20,15 @@ export class GetCustomMetricIndicatorAggregation { const filter = metric.filter ? getElastichsearchQueryOrThrow(metric.filter) : { match_all: {} }; - return { - ...acc, - [`_${type}_${metric.name}`]: { - filter, - aggs: { - sum: { - [metric.aggregation]: { field: metric.field }, - }, + (acc as Record)[`_${type}_${metric.name}`] = { + filter, + aggs: { + sum: { + [metric.aggregation]: { field: metric.field }, }, }, }; + return acc; }, {}); } @@ -42,10 +40,10 @@ export class GetCustomMetricIndicatorAggregation { } private buildMetricEquation(type: 'good' | 'total', metricDef: MetricCustomMetricDef) { - const bucketsPath = metricDef.metrics.reduce( - (acc, metric) => ({ ...acc, [metric.name]: `_${type}_${metric.name}>sum` }), - {} - ); + const bucketsPath = metricDef.metrics.reduce((acc, metric) => { + (acc as Record)[metric.name] = `_${type}_${metric.name}>sum`; + return acc; + }, {}); return { bucket_script: { buckets_path: bucketsPath, diff --git a/x-pack/plugins/osquery/server/routes/saved_query/utils.ts b/x-pack/plugins/osquery/server/routes/saved_query/utils.ts index f1fced9f10fda..08c69e4c3c3f0 100644 --- a/x-pack/plugins/osquery/server/routes/saved_query/utils.ts +++ b/x-pack/plugins/osquery/server/routes/saved_query/utils.ts @@ -20,7 +20,7 @@ export const getInstalledSavedQueriesMap = async (packageService: PackageClient installation.installed_kibana, (acc, item) => { if (item.type === savedQuerySavedObjectType) { - return { ...acc, [item.id]: item }; + acc[item.id] = item; } return acc; diff --git a/x-pack/plugins/osquery/server/utils/runtime_types.ts b/x-pack/plugins/osquery/server/utils/runtime_types.ts index 8bc781bfe3b14..fd6e5f86fc41f 100644 --- a/x-pack/plugins/osquery/server/utils/runtime_types.ts +++ b/x-pack/plugins/osquery/server/utils/runtime_types.ts @@ -90,20 +90,17 @@ const getExcessProps = ( const childrenObject = r[k] as Record; if (codecChildren != null && childrenProps != null && codecChildren._tag === 'DictionaryType') { const keys = Object.keys(childrenObject); - - return [ - ...acc, - ...keys.reduce( - (kAcc, i) => [...kAcc, ...getExcessProps(childrenProps, childrenObject[i])], - [] - ), - ]; - } - - if (codecChildren != null && childrenProps != null) { - return [...acc, ...getExcessProps(childrenProps, childrenObject)]; + acc.push( + ...keys.reduce((kAcc, i) => { + kAcc.push(...getExcessProps(childrenProps, childrenObject[i])); + + return kAcc; + }, []) + ); + } else if (codecChildren != null && childrenProps != null) { + acc.push(...getExcessProps(childrenProps, childrenObject)); } else if (codecChildren == null) { - return [...acc, k]; + acc.push(k); } return acc; diff --git a/x-pack/plugins/profiling/server/lib/setup/fleet_policies.ts b/x-pack/plugins/profiling/server/lib/setup/fleet_policies.ts index 326ebc19dd9f1..cdebeb91123b7 100644 --- a/x-pack/plugins/profiling/server/lib/setup/fleet_policies.ts +++ b/x-pack/plugins/profiling/server/lib/setup/fleet_policies.ts @@ -31,6 +31,7 @@ export function generateSecretToken() { } type PackagePolicyVars = PackageInputType & { secret_token?: string }; + export function getVarsFor({ config, includeSecretToken, @@ -48,10 +49,8 @@ export function getVarsFor({ >((acc, currKey) => { const value = currKey === 'secret_token' ? generateSecretToken() : config[currKey]; const type = typeof value === 'boolean' ? 'bool' : 'text'; - return { - ...acc, - [currKey]: { type, value }, - }; + acc[currKey] = { type, value }; + return acc; }, {}); } diff --git a/x-pack/plugins/reporting/server/usage/get_reporting_usage.ts b/x-pack/plugins/reporting/server/usage/get_reporting_usage.ts index c8ef2790932f6..d6d0263c72eea 100644 --- a/x-pack/plugins/reporting/server/usage/get_reporting_usage.ts +++ b/x-pack/plugins/reporting/server/usage/get_reporting_usage.ts @@ -52,6 +52,7 @@ enum keys { PNG_CPU = 'png_cpu', PNG_MEM = 'png_memory', } + enum fields { JOB_TYPE = 'jobtype', LAYOUT = 'meta.layout.keyword', @@ -73,28 +74,28 @@ const METRIC_PERCENTILES = [50, 75, 95, 99]; // indexes some key/count buckets by the "key" property const getKeyCount = (buckets: KeyCountBucket[]): BucketType => - buckets.reduce( - (accum, { key, doc_count: count }) => ({ ...accum, [key]: count }), - {} as BucketType - ); + buckets.reduce((accum, { key, doc_count: count }) => { + (accum as Record)[key] = count; + return accum; + }, {} as BucketType); // indexes some key/count buckets by statusType > jobType > appName: statusCount const getAppStatuses = (buckets: StatusByAppBucket[]) => buckets.reduce((statuses, statusBucket) => { - return { - ...statuses, - [statusBucket.key]: statusBucket.jobTypes.buckets.reduce((jobTypes, job) => { - return { - ...jobTypes, - [job.key]: job.appNames.buckets.reduce((apps, app) => { - return { - ...apps, - [app.key]: app.doc_count, - }; - }, {}), - }; - }, {}), - }; + (statuses as Record)[statusBucket.key] = statusBucket.jobTypes.buckets.reduce( + (jobTypes, job) => { + (jobTypes as Record)[job.key] = job.appNames.buckets.reduce( + (apps, app) => { + (apps as Record)[app.key] = app.doc_count; + return apps; + }, + {} + ); + return jobTypes; + }, + {} + ); + return statuses; }, {}); type JobType = Omit & { @@ -131,7 +132,9 @@ function normalizeJobtypes(jobBuckets: KeyCountBucket[], jobTypeMetrics?: JobTyp layout: getKeyCount(get(layoutTypes, 'buckets', [])), execution_times: pick(executionTimes ?? {}, ['min', 'max', 'avg']), }; - return { ...accum, [key]: jobType }; + + (accum as Record)[key] = jobType; + return accum; }, {} as JobTypes); } @@ -176,17 +179,15 @@ function normalizeMetrics(metrics: estypes.AggregationsStringTermsAggregate | un { key: string } & { [key: string]: estypes.AggregationsPercentilesAggregateBase } >; return metricBuckets.reduce((accum, next) => { - return { - ...accum, - [next.key]: { - pdf_pages: next.pdf_pages, - pdf_cpu: next.pdf_cpu, - pdf_memory: next.pdf_memory, - png_cpu: next.png_cpu, - png_memory: next.png_memory, - csv_rows: next.csv_rows, - }, + (accum as Record)[next.key] = { + pdf_pages: next.pdf_pages, + pdf_cpu: next.pdf_cpu, + pdf_memory: next.pdf_memory, + png_cpu: next.png_cpu, + png_memory: next.png_memory, + csv_rows: next.csv_rows, }; + return accum; }, {} as { [K in keyof JobTypes]: MetricsStats }); } diff --git a/x-pack/plugins/security/server/authorization/authorization_service.tsx b/x-pack/plugins/security/server/authorization/authorization_service.tsx index a2b32a0a6b13e..3b5a36ac72595 100644 --- a/x-pack/plugins/security/server/authorization/authorization_service.tsx +++ b/x-pack/plugins/security/server/authorization/authorization_service.tsx @@ -111,7 +111,6 @@ export class AuthorizationService { setup({ http, capabilities, - packageVersion, buildNumber, getClusterClient, license, diff --git a/x-pack/plugins/security/server/authorization/check_privileges.ts b/x-pack/plugins/security/server/authorization/check_privileges.ts index 0e842da4e4851..abc0b791dd49a 100644 --- a/x-pack/plugins/security/server/authorization/check_privileges.ts +++ b/x-pack/plugins/security/server/authorization/check_privileges.ts @@ -144,13 +144,11 @@ export function checkPrivilegesFactory( const indexPrivileges = Object.entries(hasPrivilegesResponse.index ?? {}).reduce< CheckPrivilegesResponse['privileges']['elasticsearch']['index'] >((acc, [index, indexResponse]) => { - return { - ...acc, - [index]: Object.entries(indexResponse).map(([privilege, authorized]) => ({ - privilege, - authorized, - })), - }; + acc[index] = Object.entries(indexResponse).map(([privilege, authorized]) => ({ + privilege, + authorized, + })); + return acc; }, {}); // we need to filter out the non requested privileges from the response diff --git a/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts b/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts index e3cd51bc77015..7283b955e906c 100644 --- a/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts +++ b/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts @@ -37,10 +37,8 @@ export function disableUICapabilitiesFactory( const elasticsearchFeatureMap = elasticsearchFeatures.reduce< Record> >((acc, esFeature) => { - return { - ...acc, - [esFeature.id]: esFeature.privileges, - }; + acc[esFeature.id] = esFeature.privileges; + return acc; }, {}); const allRequiredClusterPrivileges = Array.from( @@ -59,11 +57,9 @@ export function disableUICapabilitiesFactory( return { ...acc, ...Object.entries(p.requiredIndexPrivileges!).reduce((acc2, [indexName, privileges]) => { - return { - ...acc2, - [indexName]: [...(acc[indexName] ?? []), ...privileges], - }; - }, {}), + acc2[indexName] = [...(acc[indexName] ?? []), ...privileges]; + return acc2; + }, {} as Record), }; }, {}); @@ -157,14 +153,16 @@ export function disableUICapabilitiesFactory( } const uiActions = Object.entries(uiCapabilities).reduce( - (acc, [featureId, featureUICapabilities]) => [ - ...acc, - ...flatten( - Object.entries(featureUICapabilities).map(([uiCapability, value]) => { - return getActionsForFeatureCapability(featureId, uiCapability, value); - }) - ), - ], + (acc, [featureId, featureUICapabilities]) => { + acc.push( + ...flatten( + Object.entries(featureUICapabilities).map(([uiCapability, value]) => { + return getActionsForFeatureCapability(featureId, uiCapability, value); + }) + ) + ); + return acc; + }, [] ); diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/management.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/management.ts index 72cc28f5570b5..ef84f8696a212 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/management.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/management.ts @@ -18,7 +18,8 @@ export class FeaturePrivilegeManagementBuilder extends BaseFeaturePrivilegeBuild } return Object.entries(managementSections).reduce((acc, [sectionId, items]) => { - return [...acc, ...items.map((item) => this.actions.ui.get('management', sectionId, item))]; + acc.push(...items.map((item) => this.actions.ui.get('management', sectionId, item))); + return acc; }, [] as string[]); } } diff --git a/x-pack/plugins/security/server/authorization/privileges/privileges.ts b/x-pack/plugins/security/server/authorization/privileges/privileges.ts index 20de4011c39f4..e9ef404283ae6 100644 --- a/x-pack/plugins/security/server/authorization/privileges/privileges.ts +++ b/x-pack/plugins/security/server/authorization/privileges/privileges.ts @@ -37,8 +37,8 @@ export function privilegesFactory( (feature) => !feature.excludeFromBasePrivileges ); - let allActions: string[] = []; - let readActions: string[] = []; + const allActionsSet: Set = new Set(); + const readActionsSet: Set = new Set(); basePrivilegeFeatures.forEach((feature) => { for (const { privilegeId, privilege } of featuresService.featurePrivilegeIterator(feature, { @@ -47,15 +47,15 @@ export function privilegesFactory( predicate: (pId, featurePrivilege) => !featurePrivilege.excludeFromBasePrivileges, })) { const privilegeActions = featurePrivilegeBuilder.getActions(privilege, feature); - allActions = [...allActions, ...privilegeActions]; + privilegeActions.forEach((action) => allActionsSet.add(action)); if (privilegeId === 'read') { - readActions = [...readActions, ...privilegeActions]; + privilegeActions.forEach((action) => readActionsSet.add(action)); } } }); - allActions = uniq(allActions); - readActions = uniq(readActions); + const allActions = [...allActionsSet]; + const readActions = [...readActionsSet]; const featurePrivileges: Record> = {}; for (const feature of features) { diff --git a/x-pack/plugins/security/server/routes/authorization/privileges/get.ts b/x-pack/plugins/security/server/routes/authorization/privileges/get.ts index 8817fca4831ae..aa3b8fa73fb88 100644 --- a/x-pack/plugins/security/server/routes/authorization/privileges/get.ts +++ b/x-pack/plugins/security/server/routes/authorization/privileges/get.ts @@ -38,12 +38,10 @@ export function defineGetPrivilegesRoutes({ router, authz }: RouteDefinitionPara space: Object.keys(privileges.space), features: Object.entries(privileges.features).reduce( (acc, [featureId, featurePrivileges]) => { - return { - ...acc, - [featureId]: Object.keys(featurePrivileges), - }; + acc[featureId] = Object.keys(featurePrivileges); + return acc; }, - {} + {} as Record ), reserved: Object.keys(privileges.reserved), }; diff --git a/x-pack/plugins/security/server/saved_objects/ensure_authorized.ts b/x-pack/plugins/security/server/saved_objects/ensure_authorized.ts index e945848d71105..79e15be650773 100644 --- a/x-pack/plugins/security/server/saved_objects/ensure_authorized.ts +++ b/x-pack/plugins/security/server/saved_objects/ensure_authorized.ts @@ -104,7 +104,10 @@ export async function ensureAuthorized( // Neither fully nor partially authorized. Bail with error. const uniqueUnauthorizedPrivileges = [...missingPrivileges.entries()].reduce( - (acc, [, privilegeSet]) => new Set([...acc, ...privilegeSet]), + (acc, [, privilegeSet]) => { + privilegeSet.forEach((entry) => acc.add(entry)); + return acc; + }, new Set() ); const targetTypesAndActions = [...uniqueUnauthorizedPrivileges] diff --git a/x-pack/plugins/security/server/spaces/secure_spaces_client_wrapper.ts b/x-pack/plugins/security/server/spaces/secure_spaces_client_wrapper.ts index 18c6ae824584c..1e9e25b6b800d 100644 --- a/x-pack/plugins/security/server/spaces/secure_spaces_client_wrapper.ts +++ b/x-pack/plugins/security/server/spaces/secure_spaces_client_wrapper.ts @@ -81,10 +81,13 @@ export class SecureSpacesClientWrapper implements ISpacesClient { // Collect all privileges which need to be checked const allPrivileges = Object.entries(PURPOSE_PRIVILEGE_MAP).reduce( - (acc, [getSpacesPurpose, privilegeFactory]) => - !includeAuthorizedPurposes && getSpacesPurpose !== purpose - ? acc - : { ...acc, [getSpacesPurpose]: privilegeFactory(this.authorization) }, + (acc, [getSpacesPurpose, privilegeFactory]) => { + if (!includeAuthorizedPurposes && getSpacesPurpose !== purpose) { + return acc; + } + acc[getSpacesPurpose as GetAllSpacesPurpose] = privilegeFactory(this.authorization); + return acc; + }, {} as Record ); @@ -117,7 +120,8 @@ export class SecureSpacesClientWrapper implements ISpacesClient { const requiredActions = privilegeFactory(this.authorization); const hasAllRequired = checkHasAllRequired(space, requiredActions); hasAnyAuthorization = hasAnyAuthorization || hasAllRequired; - return { ...acc, [purposeKey]: hasAllRequired }; + acc[purposeKey as GetAllSpacesPurpose] = hasAllRequired; + return acc; }, {} as Record ); diff --git a/x-pack/plugins/security/server/usage_collector/security_usage_collector.ts b/x-pack/plugins/security/server/usage_collector/security_usage_collector.ts index f73ac0bbb25a3..e713a4d0d171b 100644 --- a/x-pack/plugins/security/server/usage_collector/security_usage_collector.ts +++ b/x-pack/plugins/security/server/usage_collector/security_usage_collector.ts @@ -161,10 +161,10 @@ export function registerSecurityUsageCollector({ usageCollection, config, licens const authProviderCount = config.authc.sortedProviders.length; const enabledAuthProviders = [ ...new Set( - config.authc.sortedProviders.reduce( - (acc, provider) => [...acc, provider.type], - [] as string[] - ) + config.authc.sortedProviders.reduce((acc, provider) => { + acc.push(provider.type); + return acc; + }, [] as string[]) ), ]; const accessAgreementEnabled = diff --git a/x-pack/plugins/security_solution/common/utils/field_formatters.ts b/x-pack/plugins/security_solution/common/utils/field_formatters.ts index da41cbd3bee94..b25ba23913d2e 100644 --- a/x-pack/plugins/security_solution/common/utils/field_formatters.ts +++ b/x-pack/plugins/security_solution/common/utils/field_formatters.ts @@ -56,16 +56,14 @@ export const getDataFromFieldsHits = ( const fieldCategory = prependFieldCategory != null ? prependFieldCategory : getFieldCategory(field); if (isGeoField(field)) { - return [ - ...accumulator, - { - category: fieldCategory, - field, - values: formatGeoLocation(item), - originalValue: formatGeoLocation(item), - isObjectArray: true, // important for UI - }, - ]; + accumulator.push({ + category: fieldCategory, + field, + values: formatGeoLocation(item), + originalValue: formatGeoLocation(item), + isObjectArray: true, // important for UI + }); + return accumulator; } const objArrStr = toObjectArrayOfStrings(item); @@ -80,16 +78,14 @@ export const getDataFromFieldsHits = ( (ecsField) => ecsField === field ) === undefined ) { - return [ - ...accumulator, - { - category: fieldCategory, - field: dotField, - values: strArr, - originalValue: strArr, - isObjectArray, - }, - ]; + accumulator.push({ + category: fieldCategory, + field: dotField, + values: strArr, + originalValue: strArr, + isObjectArray, + }); + return accumulator; } const threatEnrichmentObject = isThreatEnrichmentFieldOrSubfield(field, prependField) diff --git a/x-pack/plugins/security_solution/common/utils/sourcerer.ts b/x-pack/plugins/security_solution/common/utils/sourcerer.ts index cb58c0ecf1e05..a47193003ef88 100644 --- a/x-pack/plugins/security_solution/common/utils/sourcerer.ts +++ b/x-pack/plugins/security_solution/common/utils/sourcerer.ts @@ -6,10 +6,14 @@ */ export const sortWithExcludesAtEnd = (indices: string[]) => { const allSorted = indices.reduce( - (acc: { includes: string[]; excludes: string[] }, index) => - index.trim().startsWith('-') - ? { includes: acc.includes, excludes: [...acc.excludes, index] } - : { includes: [...acc.includes, index], excludes: acc.excludes }, + (acc: { includes: string[]; excludes: string[] }, index) => { + if (index.trim().startsWith('-')) { + acc.excludes.push(index); + } else { + acc.includes.push(index); + } + return acc; + }, { includes: [], excludes: [] } ); return [...allSorted.includes.sort(), ...allSorted.excludes.sort()]; @@ -18,6 +22,9 @@ export const sortWithExcludesAtEnd = (indices: string[]) => { export const ensurePatternFormat = (patternList: string[]): string[] => sortWithExcludesAtEnd([ ...new Set( - patternList.reduce((acc: string[], pattern: string) => [...pattern.split(','), ...acc], []) + patternList.reduce((acc: string[], pattern: string) => { + acc.unshift(...pattern.split(',')); + return acc; + }, []) ), ]); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/get_signal_versions_by_index.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/get_signal_versions_by_index.ts index 5bed307b69164..f7bfbc0aa068f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/get_signal_versions_by_index.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/get_signal_versions_by_index.ts @@ -83,9 +83,7 @@ export const getSignalVersionsByIndex = async ({ count: sb.doc_count, })); - return { - ...agg, - [_index]: signalsVersions, - }; + (agg as Record)[_index] = signalsVersions; + return agg; }, {}); }; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.ts index a200afdd34199..597ca7ee4d4d2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/utils.ts @@ -20,6 +20,7 @@ export interface OutputError { message: string; statusCode: number; } + export interface BulkError { // Id can be single id or stringified ids. id?: string; @@ -193,6 +194,7 @@ export const convertToSnakeCase = >( } return Object.keys(obj).reduce((acc, item) => { const newKey = snakeCase(item); - return { ...acc, [newKey]: obj[item] }; + (acc as Record)[newKey] = obj[item]; + return acc; }, {}); }; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_management/logic/import/gather_referenced_exceptions.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_management/logic/import/gather_referenced_exceptions.ts index 2ae8c56e73c74..90ee57d917733 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_management/logic/import/gather_referenced_exceptions.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_management/logic/import/gather_referenced_exceptions.ts @@ -25,10 +25,9 @@ export const parseReferencedExceptionsLists = ( rule.exceptions_list != null && rule.exceptions_list.length > 0 ) { - return [...acc, ...rule.exceptions_list]; - } else { - return acc; + acc.push(...rule.exceptions_list); } + return acc; }, []); if (lists == null || lists.length === 0) { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/aggregations/execution_results/index.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/aggregations/execution_results/index.ts index e4e394fd16149..348bc15ed41d0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/aggregations/execution_results/index.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_monitoring/logic/rule_execution_log/event_log/aggregations/execution_results/index.ts @@ -362,10 +362,10 @@ export const formatSortForBucketSort = (sort: estypes.Sort) => { */ export const formatSortForTermsSort = (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}.order`) }), - {} - ) + Object.keys(s).reduce((acc, curr) => { + (acc as Record)[SORT_FIELD_TO_AGG_MAPPING[curr]] = get(s, `${curr}.order`); + return acc; + }, {}) ); }; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/eql/wrap_sequences_factory.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/eql/wrap_sequences_factory.ts index e21f09438e8b8..204243ab40da1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/eql/wrap_sequences_factory.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/eql/wrap_sequences_factory.ts @@ -36,9 +36,8 @@ export const wrapSequencesFactory = publicBaseUrl: string | undefined; }): WrapSequences => (sequences, buildReasonMessage) => - sequences.reduce( - (acc: Array>, sequence) => [ - ...acc, + sequences.reduce((acc: Array>, sequence) => { + acc.push( ...buildAlertGroupFromSequence( ruleExecutionLogger, sequence, @@ -49,7 +48,7 @@ export const wrapSequencesFactory = indicesToQuery, alertTimestampOverride, publicBaseUrl - ), - ], - [] - ); + ) + ); + return acc; + }, []); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/utils.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/utils.ts index de5822d29b1b5..5b3d97d30efd4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/utils.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/new_terms/utils.ts @@ -94,10 +94,10 @@ export const createFieldValuesMap = ( return undefined; } - const valuesMap = newTermsFields.reduce>>( - (acc, field) => ({ ...acc, [field]: {} }), - {} - ); + const valuesMap = newTermsFields.reduce>>((acc, field) => { + acc[field] = {}; + return acc; + }, {}); buckets .map((bucket) => bucket.key) @@ -134,14 +134,14 @@ export const getNewTermsRuntimeMappings = ( // ES has limit in 100 values for runtime field, after this query will fail int emitLimit = 100; stack.add([0, '']); - + while (stack.length > 0) { if (emitLimit == 0) { break; } def tuple = stack.pop(); def index = tuple[0]; - def line = tuple[1]; + def line = tuple[1]; if (index === params['fields'].length) { emit(line); emitLimit = emitLimit - 1; @@ -154,7 +154,7 @@ export const getNewTermsRuntimeMappings = ( } def delimiter = index === 0 ? '' : '${DELIMITER}'; def nextLine = line + delimiter + fieldStr.encodeBase64(); - + stack.add([index + 1, nextLine]) } } 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 4974e6bd0edda..c1979820786fe 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 @@ -58,12 +58,15 @@ const getTimelinesFromObjects = async ( ), ]); - const myNotes = notes.reduce((acc, note) => [...acc, ...note], []); + const myNotes = notes.reduce((acc, note) => { + acc.push(...note); + return acc; + }, []); - const myPinnedEventIds = pinnedEvents.reduce( - (acc, pinnedEventId) => [...acc, ...pinnedEventId], - [] - ); + const myPinnedEventIds = pinnedEvents.reduce((acc, pinnedEventId) => { + acc.push(...pinnedEventId); + return acc; + }, []); const myResponse = exportedIds.reduce((acc, timelineId) => { const myTimeline = timelines.find((t) => t.savedObjectId === timelineId); @@ -71,14 +74,11 @@ const getTimelinesFromObjects = async ( const timelineNotes = myNotes.filter((n) => n.timelineId === timelineId); const timelinePinnedEventIds = myPinnedEventIds.filter((p) => p.timelineId === timelineId); const exportedTimeline = omit(['status', 'excludedRowRendererIds'], myTimeline); - return [ - ...acc, - { - ...exportedTimeline, - ...getGlobalEventNotesByTimelineId(timelineNotes), - pinnedEventIds: getPinnedEventsIdsByTimelineId(timelinePinnedEventIds), - }, - ]; + acc.push({ + ...exportedTimeline, + ...getGlobalEventNotesByTimelineId(timelineNotes), + pinnedEventIds: getPinnedEventsIdsByTimelineId(timelinePinnedEventIds), + }); } return acc; }, []); diff --git a/x-pack/plugins/security_solution/server/lib/timeline/saved_object/timelines/index.ts b/x-pack/plugins/security_solution/server/lib/timeline/saved_object/timelines/index.ts index e966a2d9f9f32..2494271a038a2 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/saved_object/timelines/index.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/saved_object/timelines/index.ts @@ -725,10 +725,10 @@ export const getSelectedTimelines = async ( const savedObjects = await Promise.resolve( savedObjectsClient.bulkGet( - (exportedIds ?? []).reduce( - (acc, timelineId) => [...acc, { id: timelineId, type: timelineSavedObjectType }], - [] as Array<{ id: string; type: string }> - ) + (exportedIds ?? []).reduce((acc, timelineId) => { + acc.push({ id: timelineId, type: timelineSavedObjectType }); + return acc; + }, [] as Array<{ id: string; type: string }>) ) ); @@ -740,13 +740,12 @@ export const getSelectedTimelines = async ( if (savedObject.error == null) { const populatedTimeline = timelineFieldsMigrator.populateFieldsFromReferences(savedObject); - return { - errors: acc.errors, - timelines: [...acc.timelines, convertSavedObjectToSavedTimeline(populatedTimeline)], - }; + acc.timelines.push(convertSavedObjectToSavedTimeline(populatedTimeline)); + return acc; } - return { errors: [...acc.errors, savedObject.error], timelines: acc.timelines }; + acc.errors.push(savedObject.error); + return acc; }, { timelines: [] as TimelineSavedObject[], diff --git a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/kpi/index.ts b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/kpi/index.ts index 333b59bc15c04..eee0e812306ba 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/kpi/index.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/risk_score/kpi/index.ts @@ -36,10 +36,10 @@ export const kpiRiskScore: SecuritySolutionFactory = { const riskBuckets = getOr([], 'aggregations.risk.buckets', response.rawResponse); const result: Record = riskBuckets.reduce( - (cummulative: Record, bucket: AggBucket) => ({ - ...cummulative, - [bucket.key]: getOr(0, 'unique_entries.value', bucket), - }), + (cummulative: Record, bucket: AggBucket) => { + cummulative[bucket.key] = getOr(0, 'unique_entries.value', bucket); + return cummulative; + }, {} ); diff --git a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/users/all/index.ts b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/users/all/index.ts index a8eab4d4b92db..8ee4d6d04f15f 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/users/all/index.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/users/all/index.ts @@ -110,13 +110,11 @@ async function enhanceEdges( isNewRiskScoreModuleInstalled ); const usersRiskByUserName: Record | undefined = - userRiskData?.hits.hits.reduce( - (acc, hit) => ({ - ...acc, - [hit._source?.user.name ?? '']: hit._source?.user?.risk?.calculated_level, - }), - {} - ); + userRiskData?.hits.hits.reduce((acc, hit) => { + (acc as Record)[hit._source?.user.name ?? ''] = + hit._source?.user?.risk?.calculated_level; + return acc; + }, {}); return usersRiskByUserName ? edges.map(({ name, lastSeen, domain }) => ({ diff --git a/x-pack/plugins/security_solution/server/usage/queries/get_case_comments.ts b/x-pack/plugins/security_solution/server/usage/queries/get_case_comments.ts index 43acb1db00c1b..4bdedd2c7f631 100644 --- a/x-pack/plugins/security_solution/server/usage/queries/get_case_comments.ts +++ b/x-pack/plugins/security_solution/server/usage/queries/get_case_comments.ts @@ -36,16 +36,13 @@ export const getCaseComments = async ({ }; logger.debug(`Getting cases with point in time (PIT) query:', ${JSON.stringify(query)}`); const finder = savedObjectsClient.createPointInTimeFinder(query); - let responses: Array> = []; + const responses: Array> = []; for await (const response of finder.find()) { const extra = responses.length + response.saved_objects.length - maxSize; if (extra > 0) { - responses = [ - ...responses, - ...response.saved_objects.slice(-response.saved_objects.length, -extra), - ]; + responses.push(...response.saved_objects.slice(-response.saved_objects.length, -extra)); } else { - responses = [...responses, ...response.saved_objects]; + responses.push(...response.saved_objects); } } diff --git a/x-pack/plugins/security_solution/server/usage/queries/get_detection_rules.ts b/x-pack/plugins/security_solution/server/usage/queries/get_detection_rules.ts index 3452a364503ce..7487f0d0d94b3 100644 --- a/x-pack/plugins/security_solution/server/usage/queries/get_detection_rules.ts +++ b/x-pack/plugins/security_solution/server/usage/queries/get_detection_rules.ts @@ -60,21 +60,18 @@ export const getDetectionRules = async ({ `Getting detection rules with point in time (PIT) query:', ${JSON.stringify(query)}` ); const finder = savedObjectsClient.createPointInTimeFinder(query); - let responses: Array> = []; + const responses: Array> = []; for await (const response of finder.find()) { const extra = responses.length + response.saved_objects.length - maxSize; if (extra > 0) { - responses = [ - ...responses, - ...response.saved_objects.slice(-response.saved_objects.length, -extra), - ]; + responses.push(...response.saved_objects.slice(-response.saved_objects.length, -extra)); } else { - responses = [...responses, ...response.saved_objects]; + responses.push(...response.saved_objects); } } try { - finder.close(); + await finder.close(); } catch (exception) { // This is just a pre-caution in case the finder does a throw we don't want to blow up // the response. We have seen this within e2e test containers but nothing happen in normal diff --git a/x-pack/plugins/security_solution/server/usage/queries/legacy_get_rule_actions.ts b/x-pack/plugins/security_solution/server/usage/queries/legacy_get_rule_actions.ts index 9b7140d734d16..f8b249e8cc519 100644 --- a/x-pack/plugins/security_solution/server/usage/queries/legacy_get_rule_actions.ts +++ b/x-pack/plugins/security_solution/server/usage/queries/legacy_get_rule_actions.ts @@ -46,22 +46,20 @@ export const legacyGetRuleActions = async ({ savedObjectsClient.createPointInTimeFinder( query ); - let responses: Array> = - []; + const responses: Array< + SavedObjectsFindResult + > = []; for await (const response of finder.find()) { const extra = responses.length + response.saved_objects.length - maxSize; if (extra > 0) { - responses = [ - ...responses, - ...response.saved_objects.slice(-response.saved_objects.length, -extra), - ]; + responses.push(...response.saved_objects.slice(-response.saved_objects.length, -extra)); } else { - responses = [...responses, ...response.saved_objects]; + responses.push(...response.saved_objects); } } try { - finder.close(); + await finder.close(); } catch (exception) { // This is just a pre-caution in case the finder does a throw we don't want to blow up // the response. We have seen this within e2e test containers but nothing happen in normal diff --git a/x-pack/plugins/security_solution/server/utils/runtime_types.ts b/x-pack/plugins/security_solution/server/utils/runtime_types.ts index 50045568357a0..ac1dc8d59f007 100644 --- a/x-pack/plugins/security_solution/server/utils/runtime_types.ts +++ b/x-pack/plugins/security_solution/server/utils/runtime_types.ts @@ -65,18 +65,16 @@ const getExcessProps = ( const childrenObject = r[k] as Record; if (codecChildren != null && childrenProps != null && codecChildren._tag === 'DictionaryType') { const keys = Object.keys(childrenObject); - return [ - ...acc, - ...keys.reduce( - (kAcc, i) => [...kAcc, ...getExcessProps(childrenProps, childrenObject[i])], - [] - ), - ]; - } - if (codecChildren != null && childrenProps != null) { - return [...acc, ...getExcessProps(childrenProps, childrenObject)]; + acc.push( + ...keys.reduce((kAcc, i) => { + kAcc.push(...getExcessProps(childrenProps, childrenObject[i])); + return kAcc; + }, []) + ); + } else if (codecChildren != null && childrenProps != null) { + acc.push(...getExcessProps(childrenProps, childrenObject)); } else if (codecChildren == null) { - return [...acc, k]; + acc.push(k); } return acc; }, []); diff --git a/x-pack/plugins/security_solution_serverless/server/endpoint/services/metering_service.ts b/x-pack/plugins/security_solution_serverless/server/endpoint/services/metering_service.ts index 765ffcfeb76a4..0135672194083 100644 --- a/x-pack/plugins/security_solution_serverless/server/endpoint/services/metering_service.ts +++ b/x-pack/plugins/security_solution_serverless/server/endpoint/services/metering_service.ts @@ -61,7 +61,8 @@ export class EndpointMeteringService { projectId: cloudSetup?.serverless?.projectId, }); - return [...acc, record]; + acc.push(record); + return acc; }, [] as UsageRecord[]); }; diff --git a/x-pack/plugins/spaces/server/capabilities/capabilities_switcher.ts b/x-pack/plugins/spaces/server/capabilities/capabilities_switcher.ts index e3183185022f6..b5d9be07d91af 100644 --- a/x-pack/plugins/spaces/server/capabilities/capabilities_switcher.ts +++ b/x-pack/plugins/spaces/server/capabilities/capabilities_switcher.ts @@ -63,14 +63,19 @@ function toggleDisabledFeatures( ) { const disabledFeatureKeys = activeSpace.disabledFeatures; - const [enabledFeatures, disabledFeatures] = features.reduce( + const { enabledFeatures, disabledFeatures } = features.reduce( (acc, feature) => { if (disabledFeatureKeys.includes(feature.id)) { - return [acc[0], [...acc[1], feature]]; + acc.disabledFeatures.push(feature); + } else { + acc.enabledFeatures.push(feature); } - return [[...acc[0], feature], acc[1]]; + return acc; }, - [[], []] as [KibanaFeature[], KibanaFeature[]] + { enabledFeatures: [], disabledFeatures: [] } as { + enabledFeatures: KibanaFeature[]; + disabledFeatures: KibanaFeature[]; + } ); const navLinks = capabilities.navLinks; diff --git a/x-pack/plugins/stack_connectors/server/connector_types/jira/service.ts b/x-pack/plugins/stack_connectors/server/connector_types/jira/service.ts index 771c5f25e92d6..7e742ff578345 100644 --- a/x-pack/plugins/stack_connectors/server/connector_types/jira/service.ts +++ b/x-pack/plugins/stack_connectors/server/connector_types/jira/service.ts @@ -454,10 +454,10 @@ export const createExternalService = ( }); const fields = res.data.values.reduce( - (acc: { [x: string]: {} }, value: { fieldId: string }) => ({ - ...acc, - [value.fieldId]: { ...value }, - }), + (acc: { [x: string]: {} }, value: { fieldId: string }) => { + (acc as Record)[value.fieldId] = { ...value }; + return acc; + }, {} ); return normalizeFields(fields); @@ -484,13 +484,12 @@ export const createExternalService = ( const currentListOfFields = Object.keys(acc); return currentListOfFields.length === 0 ? fieldTypesByIssue - : currentListOfFields.reduce( - (add: GetCommonFieldsResponse, field) => - Object.keys(fieldTypesByIssue).includes(field) - ? { ...add, [field]: acc[field] } - : add, - {} - ); + : currentListOfFields.reduce((add: GetCommonFieldsResponse, field) => { + if (Object.keys(fieldTypesByIssue).includes(field)) { + (add as Record)[field] = acc[field]; + } + return add; + }, {}); }, {}); } catch (error) { // errors that happen here would be thrown in the contained async calls diff --git a/x-pack/plugins/stack_connectors/server/connector_types/lib/servicenow/utils.ts b/x-pack/plugins/stack_connectors/server/connector_types/lib/servicenow/utils.ts index 2e6ba5327ed2b..256b8a97b5e1f 100644 --- a/x-pack/plugins/stack_connectors/server/connector_types/lib/servicenow/utils.ts +++ b/x-pack/plugins/stack_connectors/server/connector_types/lib/servicenow/utils.ts @@ -26,10 +26,10 @@ import * as i18n from './translations'; export const prepareIncident = (useOldApi: boolean, incident: PartialIncident): PartialIncident => useOldApi ? incident - : Object.entries(incident).reduce( - (acc, [key, value]) => ({ ...acc, [`${FIELD_PREFIX}${key}`]: value }), - {} as Incident - ); + : Object.entries(incident).reduce((acc, [key, value]) => { + (acc as Record)[`${FIELD_PREFIX}${key}`] = value; + return acc; + }, {} as Incident); const createErrorMessage = (errorResponse?: ServiceNowError): string => { if (errorResponse == null) { diff --git a/x-pack/plugins/stack_connectors/server/connector_types/servicenow_itom/api.ts b/x-pack/plugins/stack_connectors/server/connector_types/servicenow_itom/api.ts index c68f1d4419eb1..9baec9f877e2c 100644 --- a/x-pack/plugins/stack_connectors/server/connector_types/servicenow_itom/api.ts +++ b/x-pack/plugins/stack_connectors/server/connector_types/servicenow_itom/api.ts @@ -37,13 +37,12 @@ const formatTimeOfEvent = (timeOfEvent: string | null): string | undefined => { const removeNullValues = ( params: ExecutorSubActionAddEventParams ): ExecutorSubActionAddEventParams => - (Object.keys(params) as Array).reduce( - (acc, key) => ({ - ...acc, - ...(params[key] != null ? { [key]: params[key] } : {}), - }), - {} as ExecutorSubActionAddEventParams - ); + (Object.keys(params) as Array).reduce((acc, key) => { + if (params[key] != null) { + (acc as Record)[key] = params[key]; + } + return acc; + }, {} as ExecutorSubActionAddEventParams); export const prepareParams = ( params: ExecutorSubActionAddEventParams 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 6af36c4ad6f73..2a3cd3cf34e51 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 @@ -224,7 +224,7 @@ export const requestIndexFieldSearch = async ( export const dedupeIndexName = (indices: string[]) => indices.reduce((acc, index) => { if (index.trim() !== '' && index.trim() !== '_all' && !acc.includes(index.trim())) { - return [...acc, index]; + acc.push(index); } return acc; }, []); diff --git a/x-pack/plugins/timelines/server/search_strategy/timeline/factory/helpers/build_ecs_objects.ts b/x-pack/plugins/timelines/server/search_strategy/timeline/factory/helpers/build_ecs_objects.ts index 0f24be8526d05..83cad1e67404a 100644 --- a/x-pack/plugins/timelines/server/search_strategy/timeline/factory/helpers/build_ecs_objects.ts +++ b/x-pack/plugins/timelines/server/search_strategy/timeline/factory/helpers/build_ecs_objects.ts @@ -14,8 +14,7 @@ import { buildObjectRecursive } from './build_object_recursive'; import { getNestedParentPath } from './get_nested_parent_path'; export const buildEcsObjects = (hit: EventHit): Ecs => { - const ecsFields = [...TIMELINE_EVENTS_FIELDS]; - return ecsFields.reduce( + return TIMELINE_EVENTS_FIELDS.reduce( (acc, field) => { const nestedParentPath = getNestedParentPath(field, hit.fields); if ( diff --git a/x-pack/plugins/transform/server/routes/api/transforms.ts b/x-pack/plugins/transform/server/routes/api/transforms.ts index 80d44c0e907bf..17c9db4077462 100644 --- a/x-pack/plugins/transform/server/routes/api/transforms.ts +++ b/x-pack/plugins/transform/server/routes/api/transforms.ts @@ -821,7 +821,7 @@ const previewTransformHandler: RequestHandler< if (isMetaField || isKeywordDuplicate(fieldName, fieldNamesSet)) { return acc; } - acc[fieldName] = { ...fieldDefinition }; + acc[fieldName] = fieldDefinition; return acc; }, {} as Record); diff --git a/x-pack/plugins/ux/common/ux_ui_filter.ts b/x-pack/plugins/ux/common/ux_ui_filter.ts index aeea1cddae30d..346b9d4802dae 100644 --- a/x-pack/plugins/ux/common/ux_ui_filter.ts +++ b/x-pack/plugins/ux/common/ux_ui_filter.ts @@ -109,12 +109,9 @@ export const uxLocalUIFilterNames = Object.keys( export const uxLocalUIFilters = uxLocalUIFilterNames.reduce((acc, key) => { const field = uxFiltersByName[key]; - - return { - ...acc, - [key]: { - ...field, - name: key, - }, - }; + acc[key] = { + ...field, + name: key, + } as UxLocalUIFilter; + return acc; }, {} as UxLocalUIFilterMap);