import FS from 'fs' ; import Path from 'path' ; import type { Downloader } from '../../types' ; interface DownloaderLoader { getDownloader : ( ) => Downloader | Downloader [ ] ; } type DownloaderLoaderPartial = Partial < DownloaderLoader > ; function getDownloaderLoaders ( dir ) { return FS . readdirSync ( dir , { encoding : 'utf8' } ) . filter ( ( file ) => file . endsWith ( '.js' ) && file !== Path . basename ( __filename ) ) . map ( ( file ) => { try { const loader = require ( `${ dir }/${ file }` ) ; if ( ! loader . getDownloader ) { return undefined ; } return loader as DownloaderLoader ; } catch ( err ) { console . warn ( `Failed to load downloader: ${ file }` , err ) ; return undefined ; } } ) . filter ( ( loader ) => loader !== undefined ) as DownloaderLoader [ ] ; } const downloaderLoaders = getDownloaderLoaders ( __dirname ) ; export function getDownloaders ( ) { return ( downloaderLoaders . map ( ( loader ) => { const downloaders = loader . getDownloader ( ) ; return Array . isArray ( downloaders ) ? downloaders : [ downloaders ] ; } ) . reduce ( ( acc , val ) => acc . concat ( val ) , [ ] ) . filter ( ( task ) => task !== undefined ) ) ; }