import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey' ; import { isEmpty , isObject } from 'lodash/fp' ; import type { Type } from '@kbn/securitysolution-io-ts-list-types' ; export type QueryFilterType = estypes . QueryDslQueryContainer [ ] ; param type param value param listId export const getQueryFilterFromTypeValue = ( { type , value , listId , } ) : QueryFilterType => { const valueFlattened = value . flat ( Infinity ) . filter ( ( singleValue ) => singleValue != null && ! isObject ( singleValue ) ) ; if ( isEmpty ( valueFlattened ) ) { return getEmptyQuery ( { listId } ) ; } else if ( type === 'text' ) { return getTextQuery ( { listId , type , value } ) ; } else { return getTermsQuery ( { listId , type , value } ) ; } } ; param listId export const getEmptyQuery = ( { listId } ) : QueryFilterType => [ { term : { list_id : listId } } , { bool : { minimum_should_match : 1 , should : [ { match_none : { _name : 'empty' , } , } , ] , } , } , ] ; param value param type param listId export const getTermsQuery = ( { value , type , listId , } ) : QueryFilterType => { const should = value . reduce < unknown [ ] > ( ( accum , item , index ) => { if ( Array . isArray ( item ) ) { const itemFlattened = item . flat ( Infinity ) . filter ( ( singleValue ) => singleValue != null && ! isObject ( singleValue ) ) ; if ( itemFlattened . length === 0 ) { return accum ; } else { return [ ... accum , { terms : { _name : `${ index }.0` , [ type ] : itemFlattened } } ] ; } } else { if ( item == null || isObject ( item ) ) { return accum ; } else { return [ ... accum , { term : { [ type ] : { _name : `${ index }.0` , value : item } } } ] ; } } } , [ ] ) ; return getShouldQuery ( { listId , should } ) ; } ; param value param type param listId export const getTextQuery = ( { value , type , listId , } ) : QueryFilterType => { const should = value . reduce < unknown [ ] > ( ( accum , item , index ) => { if ( Array . isArray ( item ) ) { const itemFlattened = item . flat ( Infinity ) . filter ( ( singleValue ) => singleValue != null && ! isObject ( singleValue ) ) ; if ( itemFlattened . length === 0 ) { return accum ; } else { return [ ... accum , ... itemFlattened . map ( ( flatItem , secondIndex ) => ( { match : { [ type ] : { _name : `${ index }.${ secondIndex }` , operator : 'and' , query : flatItem } , } , } ) ) , ] ; } } else { if ( item == null || isObject ( item ) ) { return accum ; } else { return [ ... accum , { match : { [ type ] : { _name : `${ index }.0` , operator : 'and' , query : item } } } , ] ; } } } , [ ] ) ; return getShouldQuery ( { listId , should } ) ; } ; param listId param should export const getShouldQuery = ( { listId , should , } ) : QueryFilterType => { return [ { term : { list_id : listId } } , { bool : { minimum_should_match : 1 , should , } , } , ] ; } ;