11import * as ts from 'typescript' ;
2- import { promises as fs } from 'fs' ;
32import * as tmp from 'tmp-promise' ;
43import * as path from 'path' ;
54
6- tmp . setGracefulCleanup ( ) ;
7-
85interface RunOptions {
96 input : Buffer ;
107}
@@ -14,19 +11,32 @@ interface RunResult {
1411}
1512
1613export 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 ( / \. t s $ / , '' ) ) } ;
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