import * as esKuery from '@kbn/es-query' ; import { LegacyUrlAlias , LEGACY_URL_ALIAS_TYPE } from '../../../object_types' ; import { getObjectKey } from '../internal_utils' ; import type { CreatePointInTimeFinderFn } from '../point_in_time_finder' ; interface FindLegacyUrlAliasesObject { type : string ; id : string ; } internal export async function findLegacyUrlAliases ( createPointInTimeFinder , objects , perPage ? ) { if ( ! objects . length ) { return new Map < string , Set < string > > ( ) ; } const filter = createAliasKueryFilter ( objects ) ; const finder = createPointInTimeFinder < LegacyUrlAlias > ( { type : LEGACY_URL_ALIAS_TYPE , perPage , filter , } ) ; const aliasesMap = new Map < string , Set < string > > ( ) ; let error ; try { for await ( const { saved_objects : savedObjects } of finder . find ( ) ) { for ( const alias of savedObjects ) { const { sourceId , targetType , targetNamespace } = alias . attributes ; const key = getObjectKey ( { type : targetType , id : sourceId } ) ; const val = aliasesMap . get ( key ) ?? new Set < string > ( ) ; val . add ( targetNamespace ) ; aliasesMap . set ( key , val ) ; } } } catch ( e ) { error = e ; } try { await finder . close ( ) ; } catch ( e ) { if ( ! error ) { error = e ; } } if ( error ) { throw new Error ( `Failed to retrieve legacy URL aliases: ${ error . message }` ) ; } return aliasesMap ; } function createAliasKueryFilter ( objects ) { const { buildNode } = esKuery . nodeTypes . function ; const kueryNodes = objects . reduce < unknown [ ] > ( ( acc , { type , id } ) => { const match1 = buildNode ( 'is' , `${ LEGACY_URL_ALIAS_TYPE }.attributes.targetType` , type ) ; const match2 = buildNode ( 'is' , `${ LEGACY_URL_ALIAS_TYPE }.attributes.sourceId` , id ) ; acc . push ( buildNode ( 'and' , [ match1 , match2 ] ) ) ; return acc ; } , [ ] ) ; return buildNode ( 'and' , [ buildNode ( 'not' , buildNode ( 'is' , `${ LEGACY_URL_ALIAS_TYPE }.attributes.disabled` , true ) ) , buildNode ( 'or' , kueryNodes ) , ] ) ; }