import { createError } from '@cirrusct/error'; import { fsStatSync } from '@cirrusct/fs'; import * as fs from 'fs'; import { merge } from 'lodash'; import * as nodePath from 'path'; import * as ts from 'typescript'; import { TsConfig } from './types'; export const findTsConfigFilePath = (path: string): string | undefined => { const stats = fsStatSync(path); let entryFilePath: string; if (stats) { entryFilePath = stats.isDirectory() ? ts.findConfigFile(path, ts.sys.fileExists) : path; } return entryFilePath; }; const readJsonFile = (filePath: string): TsConfig => { try { const content = fs.readFileSync(filePath, { encoding: 'utf8' }).toString(); return JSON.parse(content); } catch (e) { throw createError(`loadJsonFile '${filePath}' failed: ${e.message}`); } }; const _load = (filePath: string): TsConfig | undefined => { const tsConfig = readJsonFile(filePath); if (tsConfig.extends) { const extendedFilePath = nodePath.resolve(nodePath.dirname(filePath), tsConfig.extends); if (!fs.existsSync(extendedFilePath)) { throw createError(`TsConfig file '${filePath}' extends file '${extendedFilePath}' which does not exist`); } const extendsTsConfig = _load(extendedFilePath); delete tsConfig.extends; return merge(extendsTsConfig, tsConfig); } return tsConfig; }; export const loadTsConfig = (path: string): TsConfig | undefined => { const entryFilePath = findTsConfigFilePath(path); if (entryFilePath) { const tsConfig = _load(entryFilePath); return tsConfig; } return undefined; };