import { Config } from "@kosko/config" ; import { Environment } from "@kosko/env" ; import { localImportDefault , localRequireDefault } from "./require" ; import { BaseGenerateArguments } from "./types" ; import { isESMSupported } from "@kosko/require" ; import { createCLIEnvReducer } from "./set-option" ; const KOSKO_ENV = "@kosko/env" ; function excludeFalsyInArray < T > ( input ) { return input . filter ( Boolean ) as T [ ] ; } function pickEnvArray ( envs ) { if ( envs . length > 1 ) return envs ; return envs [ 0 ] ; } export async function setupEnv ( config , args ) { const cwd = args . cwd ; const envs = [ await localRequireDefault ( KOSKO_ENV , cwd ) ] ; if ( await isESMSupported ( ) ) { envs . push ( await localImportDefault ( KOSKO_ENV , cwd ) ) ; } const paths = config . paths ?. environment || { } ; const setReducer = args . set && args . set . length ? createCLIEnvReducer ( args . set ) : undefined ; for ( const env of envs ) { env . cwd = cwd ; env . env = pickEnvArray ( excludeFalsyInArray ( [ config . baseEnvironment , args . env ] ) ) ; if ( config . extensions ) env . extensions = [ ... config . extensions ] ; if ( paths . global ) env . paths . global = paths . global ; if ( paths . component ) env . paths . component = paths . component ; if ( setReducer ) { env . setReducers ( ( reducers ) => [ ... reducers , setReducer ] ) ; } } }