import { NPMPackageConfig } from '../types' ; import * as fs from './fs' ; import * as helpers from '../helpers' ; import { app , project } from './path' ; const kEnvReplacementRegex = /\{ENV\.([^}]+)\}/g ; param { string } projectName returns { string } function toAppName ( projectName ) { const split = projectName . split ( '/' ) ; const moduleName = split [ split . length - 1 ] ; return moduleName . replace ( /-/g , '_' ) . split ( '_' ) . map ( w => `${ w [ 0 ] . toUpperCase ( ) }${ w . substring ( 1 ) }` ) . join ( '' ) ; } param { string } env returns { string } export function path ( env ) { return project . resolve ( 'env' , `env.${ env }.js` ) ; } param { object } configuration export function write ( configuration ) { fs . writeFileSync ( project . resolve ( 'env' , 'env.js' ) , `module.exports = ${ JSON . stringify ( configuration , null , 2 ) }` ) ; } param { object } configuration returns { object } function overwriteEnv ( configuration ) { return Object . keys ( configuration ) . reduce ( ( accumulator , key ) => { let value = configuration [ key ] ; if ( value && ! Array . isArray ( value ) ) { switch ( typeof value ) { case 'object' : value = overwriteEnv ( value ) ; break ; case 'string' : value = value . replace ( kEnvReplacementRegex , ( a , b ) => process . env [ b ] || '' ) ; break ; default : } } accumulator [ key ] = value ; return accumulator ; } , { } ) ; } param { string } env param { object } projectPackageJson returns { object } export function configuration ( env , projectPackageJson ) { let projectEnv ; try { projectEnv = require ( path ( env ) ) ; } catch ( err ) { helpers . logWarn ( 'Environment configuration not found, fallback to default.' ) ; projectEnv = { name : toAppName ( projectPackageJson . name ) } ; } helpers . logInfo ( `selected environment ${ helpers . colors . FgGreen }${ env }${ helpers . colors . Reset }` ) ; return { ... overwriteEnv ( projectEnv ) , version : projectPackageJson . version } ; } param { string } singleEnv export function createEnvIndex ( singleEnv ? ) { let envMatch = /env.[\w]+.js/ ; if ( singleEnv ) { envMatch = new RegExp ( 'env\\.' + singleEnv + '\\.js' ) ; helpers . logInfo ( 'Creating index file for default env' ) ; } else { helpers . logInfo ( 'Creating index file for project envs' ) ; } const envs = fs . readdirSync ( project . resolve ( 'env' ) ) . filter ( ( f ) => f . match ( envMatch ) ) ; const envIndexFile = `module.exports = {\n${ envs . map ( ( env ) => { const envName = env . match ( /env.([\w]+).js/ ) ; return envName && `"${ envName . pop ( ) }": require(${ JSON . stringify ( project . resolve ( 'env' , env ) ) })` ; } ) . join ( ',\n' ) }\n}` ; fs . writeFileSync ( app . resolve ( 'project_env_index.js' ) , envIndexFile ) ; }