import { existsSync } from "node:fs"; import path from "node:path"; import ts from "typescript"; export interface LoadedProject { program: ts.Program; checker: ts.TypeChecker; targetFile: ts.SourceFile; targetFilePath: string; projectFilePath: string; diagnostics: () => string[]; } export function normalizePath(filePath: string): string { return path.resolve(filePath).replaceAll(path.sep, "/"); } export function loadProject(targetFileInput: string, projectInput?: string): LoadedProject { const targetFilePath = normalizePath(targetFileInput); if (!existsSync(targetFilePath)) { throw new Error(`Target file not found: ${targetFileInput}`); } const projectFilePath = resolveProjectFile(projectInput); const config = ts.readConfigFile(projectFilePath, ts.sys.readFile); if (config.error) { throw new Error(formatDiagnostic(config.error)); } const parsed = ts.parseJsonConfigFileContent( config.config, ts.sys, path.dirname(projectFilePath), undefined, projectFilePath, ); if (parsed.errors.length > 0) { throw new Error(parsed.errors.map(formatDiagnostic).join("\n")); } const program = ts.createProgram({ rootNames: parsed.fileNames, options: parsed.options, }); const checker = program.getTypeChecker(); const targetFile = program .getSourceFiles() .find((sourceFile) => normalizePath(sourceFile.fileName) === targetFilePath); if (!targetFile) { throw new Error( `Target file is not included by ${projectFilePath}: ${targetFileInput}`, ); } let diagnosticsCache: string[] | undefined; return { program, checker, targetFile, targetFilePath, projectFilePath, diagnostics: () => { diagnosticsCache ??= ts .getPreEmitDiagnostics(program) .map(formatDiagnostic) .filter(Boolean); return diagnosticsCache; }, }; } function resolveProjectFile(projectInput?: string): string { if (projectInput) { const projectFilePath = normalizePath(projectInput); if (!existsSync(projectFilePath)) { throw new Error(`tsconfig.json not found: ${projectInput}`); } return projectFilePath; } const found = ts.findConfigFile(process.cwd(), ts.sys.fileExists, "tsconfig.json"); if (!found) { throw new Error("tsconfig.json not found from current directory"); } return normalizePath(found); } function formatDiagnostic(diagnostic: ts.Diagnostic): string { return ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); }