import FS from 'fs' ; import Path from 'path' ; import type { Database , RouterTask } from '../types' ; interface TaskLoader { getTask : ( database : Database ) => RouterTask | RouterTask [ ] | undefined ; } type TaskLoaderOptionalTask = Partial < TaskLoader > ; function getTaskLoaders ( 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 . getTask ) { return undefined ; } return loader as TaskLoader ; } catch ( err ) { console . warn ( `Failed to load task: ${ file }` , err ) ; return undefined ; } } ) . filter ( ( loader ) => loader !== undefined ) as TaskLoader [ ] ; } const taskLoaders = [ ... getTaskLoaders ( __dirname ) , ... getTaskLoaders ( `${ __dirname }/tensorflow` ) ] ; export function getTasks ( database ) { return ( taskLoaders . map ( ( loader ) => { const tasks = loader . getTask ( database ) ; return Array . isArray ( tasks ) ? tasks : [ tasks ] ; } ) . reduce ( ( acc , val ) => acc . concat ( val ) , [ ] ) . filter ( ( task ) => task !== undefined ) as RouterTask [ ] ) ; }