Skip to content

Commit 938b248

Browse files
committed
Don't create a temporary file
1 parent 06688ce commit 938b248

File tree

1 file changed

+19
-9
lines changed

1 file changed

+19
-9
lines changed

src/index.ts

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
import * as ts from 'typescript';
2-
import { promises as fs } from 'fs';
32
import * as tmp from 'tmp-promise';
43
import * as path from 'path';
54

6-
tmp.setGracefulCleanup();
7-
85
interface RunOptions {
96
input: Buffer;
107
}
@@ -14,19 +11,32 @@ interface RunResult {
1411
}
1512

1613
export async function run(fileName: string, { input = Buffer.of() }: Partial<RunOptions> = {}): Promise<RunResult> {
17-
const { path: callerFileName, cleanup } = await tmp.file({ prefix: `compile-time-typescript`, postfix: `caller.ts` });
18-
await fs.writeFile(callerFileName, `
14+
const callerFileName = await tmp.tmpName({ prefix: `compile-time-typescript`, postfix: `caller.ts` });
15+
const callerSourceFile = ts.createSourceFile(callerFileName, `
1916
import Main from ${JSON.stringify(path.resolve(fileName).replace(/\.ts$/, ''))};
2017
type Input = ${JSON.stringify(input.toString('binary'))};
2118
type Output = Main<Input>;
22-
`);
19+
`, ts.ScriptTarget.Latest);
20+
21+
const defaultCompilerHost = ts.createCompilerHost({});
22+
const customCompilerHost: ts.CompilerHost = {
23+
...defaultCompilerHost,
24+
getSourceFile(fileName: string, languageVersion: ts.ScriptTarget, onError?: ((message: string) => void), shouldCreateNewSourceFile?: boolean): ts.SourceFile | undefined {
25+
if (fileName === callerFileName) {
26+
return callerSourceFile;
27+
} else {
28+
return defaultCompilerHost.getSourceFile.call(this, fileName, languageVersion, onError, shouldCreateNewSourceFile);
29+
}
30+
},
31+
};
32+
2333
const program = ts.createProgram({
2434
rootNames: [callerFileName],
2535
options: {
2636
strict: true,
2737
},
38+
host: customCompilerHost,
2839
});
29-
const source = program.getSourceFile(callerFileName)!;
3040
const checker = program.getTypeChecker();
3141
const outputList: Buffer[] = [];
3242

@@ -43,8 +53,8 @@ export async function run(fileName: string, { input = Buffer.of() }: Partial<Run
4353
node.forEachChild(visit);
4454
}
4555

46-
source.forEachChild(visit);
47-
await cleanup();
56+
callerSourceFile.forEachChild(visit);
57+
4858
return {
4959
output: Buffer.concat(outputList),
5060
};

0 commit comments

Comments
 (0)