"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const path_1 = require("path");
const typescript_1 = require("typescript");
const diagnosticToString_1 = require("./diagnosticToString");
function findTsConfig(cwd = process.cwd()) {
    const configPath = typescript_1.findConfigFile(cwd, (fileName) => fs.existsSync(fileName));
    if (!configPath) {
        throw new Error('Unable to find TypeScript configuration');
    }
    const baseConfig = parseConfigFile(cwd, configPath);
    if (baseConfig.extends) {
        const extensions = Array.isArray(baseConfig.extends) ? baseConfig.extends : [baseConfig.extends];
        const extendedConfigPaths = extensions.map(ext => path_1.join(path_1.dirname(configPath), ext));
        const extendedConfigs = extendedConfigPaths.map(path => parseConfigFile(cwd, path));
        if (extendedConfigs.length === 1) {
            return mergeConfigs(baseConfig, extendedConfigs[0]);
        }
        return extendedConfigs.reduceRight(mergeConfigs, baseConfig);
    }
    return baseConfig;
}
exports.findTsConfig = findTsConfig;
function mergeConfigs(base, extension) {
    return Object.assign({}, extension, base, { compilerOptions: Object.assign({}, extension.compilerOptions, base.compilerOptions) });
}
function parseConfigFile(cwd, filePath) {
    const fileName = path_1.basename(filePath);
    const contents = fs.readFileSync(filePath).toString();
    const { config } = typescript_1.parseConfigFileTextToJson(filePath, contents);
    const { options, errors } = typescript_1.convertCompilerOptionsFromJson(config.compilerOptions, cwd, fileName);
    if (errors && errors.length > 0) {
        throw new Error(errors.map(x => diagnosticToString_1.diagnosticToString(x, cwd)).join('\n'));
    }
    return Object.assign({}, config, { compilerOptions: options, configPath: filePath });
}
//# sourceMappingURL=findTsConfig.js.map