Skip to content

Commit

Permalink
feat: add tsconfig.json parsing capability
Browse files Browse the repository at this point in the history
  • Loading branch information
leoweyr committed Jan 23, 2025
1 parent 13da182 commit fa8f3b9
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions src/nodejs/TypeScriptConfiguration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import * as Path from "path";

import ts, { ParsedCommandLine, Program } from "typescript";

import { Project } from "../project/Project";


export class TypeScriptConfiguration {
private static parseFile(filePath: string): ParsedCommandLine {
const file: any = ts.readConfigFile(filePath, ts.sys.readFile);

if (file.error) {
throw new Error("Error reading tsconfig.json.");
}

const parsedCommandLine: ParsedCommandLine = ts.parseJsonConfigFileContent(
file.config,
ts.sys,
Path.dirname(filePath)
);

if (parsedCommandLine.errors.length > 0) {
throw new Error(`Error parsing tsconfig.json: ${JSON.stringify(parsedCommandLine.errors)}.`);
}

return parsedCommandLine;
}

private readonly filePath: string;

public constructor(project: Project) {
this.filePath = Path.join(project.getPath(), "tsconfig.json");
}

public getEmittedDirectory(): string {
const parsedCommandLine: ParsedCommandLine = TypeScriptConfiguration.parseFile(this.filePath);
const emittedDirectory: string | undefined = parsedCommandLine.options.outDir;

if (!emittedDirectory) {
throw new Error("No `outDir` configuration in tsconfig.json.");
}

return emittedDirectory;
}

public getCompiledDirectoryStructure(): Array<string> {
const parsedCommandLine: ParsedCommandLine = TypeScriptConfiguration.parseFile(this.filePath);

const program: Program = ts.createProgram({
rootNames: parsedCommandLine.fileNames,
options: parsedCommandLine.options,
});

const emittedFilePaths: Array<string> = new Array<string>();
const emittedDirectory: string = this.getEmittedDirectory();

program.emit(undefined, (fileName: string): void => {
emittedFilePaths.push(fileName);
});

return emittedFilePaths.map((filePath: string): string => {
return Path.relative(emittedDirectory, filePath).replace(/\\/g, "/")
});
}
}

0 comments on commit fa8f3b9

Please # to comment.