import * as path from "path" ; import * as Utils from "./utils" ; import * as Messages from "./messages" ; import { promises as fs } from "fs" ; param model returns export default async function getModelFolderContents ( model ) { try { const modelPath = `${ model }${ ( ! path . extname ( model ) && ".pass" ) || "" }` ; const modelFilesList = await fs . readdir ( modelPath ) ; const filteredModelRecords = Utils . removeHidden ( modelFilesList ) . filter ( ( f ) => ! /(manifest|signature)/i . test ( f ) && /.+$/ . test ( path . parse ( f ) . ext ) ) ; const modelRecords = ( await Promise . all ( filteredModelRecords . map ( ( fileOrDirectoryPath ) => { const fullPath = path . resolve ( modelPath , fileOrDirectoryPath ) ; return readFileOrDirectory ( fullPath ) ; } ) ) ) . flat ( 1 ) . reduce ( ( acc , current ) => ( { ... acc , ... current } ) , { } ) ; return modelRecords ; } catch ( _err ) { const err = _err as NodeJS . ErrnoException ; if ( err ?. code === "ENOENT" ) { if ( err . syscall === "open" ) { throw new Error ( Messages . format ( Messages . MODELS . FILE_NO_OPEN , JSON . stringify ( err ) ) ) ; } else if ( err . syscall === "scandir" ) { throw new Error ( Messages . format ( Messages . MODELS . DIR_NOT_FOUND , err . path ) ) ; } } throw err ; } } param filePath returns async function readFileOrDirectory ( filePath ) { if ( ( await fs . lstat ( filePath ) ) . isDirectory ( ) ) { return Promise . all ( await readDirectory ( filePath ) ) ; } else { return fs . readFile ( filePath ) . then ( ( content ) => getObjectFromModelFile ( filePath , content , 1 ) ) ; } } param filePath param content param depthFromEnd returns function getObjectFromModelFile ( filePath , content , depthFromEnd ) { const fileComponents = filePath . split ( path . sep ) ; const fileName = fileComponents . slice ( fileComponents . length - depthFromEnd ) . join ( "/" ) ; return { [ fileName ] : content } ; } param filePath returns async function readDirectory ( filePath ) { const dirContent = await fs . readdir ( filePath ) . then ( Utils . removeHidden ) ; return dirContent . map ( async ( fileName ) => { const content = await fs . readFile ( path . resolve ( filePath , fileName ) ) ; return getObjectFromModelFile ( path . resolve ( filePath , fileName ) , content , 2 ) ; } ) ; }