forked from TheLartians/TypeScript2Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
44 lines (36 loc) 路 1.29 KB
/
Copy pathutils.ts
File metadata and controls
44 lines (36 loc) 路 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { Ts2PyConfig } from "../config";
import { typeScriptToPython } from "../typeScriptToPython";
import { createProject, ts } from "@ts-morph/bootstrap";
/**
* We create only a single global project to improve performance when sequentially
* transpiling multiple files.
**/
let globalProject: ReturnType<typeof createProject> | undefined;
/** Each file should get a unique name to avoid issues. */
let i = 0;
export const transpileString = async (
code: string,
config: Ts2PyConfig = {},
compilerOptions: ts.CompilerOptions = {},
) => {
globalProject ??= createProject({
useInMemoryFileSystem: true,
});
const project = await globalProject;
const fileName = `source_${String(i++)}.ts`;
// instead of adding a new source file for each program, we update the existing one.
const sourceFile = project.updateSourceFile(fileName, code);
const program = project.createProgram({
rootNames: [fileName],
options: { ...project.compilerOptions, ...compilerOptions },
});
const diagnostics = ts.getPreEmitDiagnostics(program);
if (diagnostics.length > 0) {
throw new Error(
`code compiled with errors: ${project.formatDiagnosticsWithColorAndContext(
diagnostics,
)}`,
);
}
return typeScriptToPython(program.getTypeChecker(), [sourceFile], config);
};