import debug from "debug" ; import * as fs from "fs" ; import { flatMap } from "lodash" ; import * as path from "path" ; import { IServiceDef , IServiceDefLoader } from "unmock-core" ; import { resolveUnmockDirectories } from "./utils" ; const debugLog = debug ( "unmock:fs-service-def-loader" ) ; /**
 * Read services from file system. Base directory is either
 * 1. Directory injected in configuration
 * 2. Environment variable `UNMOCK_SERVICES_DIRECTORY`
 * 3. `${process.cwd()}/__unmock__`
 */ export class FsServiceDefLoader implements IServiceDefLoader { param absoluteDirectory returns public static readServiceDirectory ( absoluteDirectory ) { const serviceFiles = fs . readdirSync ( absoluteDirectory ) . map ( ( fileName ) => path . join ( absoluteDirectory , fileName ) ) . filter ( ( fileName ) => fs . statSync ( fileName ) . isFile ( ) ) . map ( ( f ) => ( { basename : path . basename ( f ) , contents : fs . readFileSync ( f ) . toString ( "utf-8" ) , } ) ) ; return { absolutePath : absoluteDirectory , directoryName : path . basename ( absoluteDirectory ) , serviceFiles , } ; } public static loadSyncUnmockDirectory ( unmockDirectory ) { if ( ! ( fs . existsSync ( unmockDirectory ) && fs . statSync ( unmockDirectory ) . isDirectory ( ) ) ) { throw new Error ( `Directory ${ unmockDirectory } does not exist.` ) ; } debugLog ( `Reading services from ${ unmockDirectory }` ) ; const serviceDirectories = fs . readdirSync ( unmockDirectory ) . map ( ( f ) => path . join ( unmockDirectory , f ) ) . filter ( ( f ) => fs . statSync ( f ) . isDirectory ( ) ) ; debugLog ( `Found ${ serviceDirectories . length } services in ${ unmockDirectory }` ) ; const serviceDefs = serviceDirectories . map ( ( dir ) => FsServiceDefLoader . readServiceDirectory ( dir ) ) ; return serviceDefs ; } private readonly unmockDirectories : string [ ] ; public constructor ( options ) { this . unmockDirectories = options . unmockDirectories ; } /**
     * Asynchronously read service definitions.
     */ public async load ( ) { return this . loadSync ( ) ; } /**
     * Synchronously read service definitions.
     */ public loadSync ( ) { return flatMap ( this . unmockDirectories , ( directory ) => FsServiceDefLoader . loadSyncUnmockDirectory ( directory ) ) ; } } const createFsServiceDefLoader = ( servicesDirectory ? ) : IServiceDefLoader => { const unmockDirectories = servicesDirectory ? [ servicesDirectory ] : resolveUnmockDirectories ( ) ; debugLog ( `Found unmock directories: ${ JSON . stringify ( unmockDirectories ) }` ) ; return new FsServiceDefLoader ( { unmockDirectories } ) ; } ; export default createFsServiceDefLoader ;