|
1 | | -import * as ts from 'typescript'; |
2 | | -import * as tmp from 'tmp-promise'; |
3 | | -import * as path from 'path'; |
| 1 | +import { run } from './temporary'; |
4 | 2 |
|
5 | | -interface RunOptions { |
6 | | - input: Buffer; |
7 | | -} |
8 | | - |
9 | | -interface RunResult { |
10 | | - output: Buffer; |
11 | | -} |
12 | | - |
13 | | -export async function run(fileName: string, { input = Buffer.of() }: Partial<RunOptions> = {}): Promise<RunResult> { |
14 | | - const callerFileName = await tmp.tmpName({ prefix: `compile-time-typescript`, postfix: `caller.ts` }); |
15 | | - const callerSourceFile = ts.createSourceFile(callerFileName, ` |
16 | | - import Main from ${JSON.stringify(path.resolve(fileName).replace(/\.ts$/, ''))}; |
17 | | - type Input = ${JSON.stringify(input.toString('binary'))}; |
18 | | - type Output = Main<Input>; |
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 | | - |
33 | | - const program = ts.createProgram({ |
34 | | - rootNames: [callerFileName], |
35 | | - options: { |
36 | | - strict: true, |
37 | | - }, |
38 | | - host: customCompilerHost, |
39 | | - }); |
40 | | - const checker = program.getTypeChecker(); |
41 | | - const outputList: Buffer[] = []; |
42 | | - |
43 | | - function visit(node: ts.Node) { |
44 | | - const symbol = checker.getSymbolAtLocation(node); |
45 | | - if (symbol && symbol.getName() === `Output`) { |
46 | | - const type = checker.getDeclaredTypeOfSymbol(symbol); |
47 | | - if (type.isStringLiteral()) { |
48 | | - outputList.push(Buffer.from(type.value)); |
49 | | - } else { |
50 | | - throw new Error(`type error: ${checker.typeToString(type)}`); |
51 | | - } |
52 | | - } |
53 | | - node.forEachChild(visit); |
54 | | - } |
55 | | - |
56 | | - callerSourceFile.forEachChild(visit); |
57 | | - |
58 | | - return { |
59 | | - output: Buffer.concat(outputList), |
60 | | - }; |
61 | | -} |
| 3 | +export { run } from './temporary'; |
62 | 4 |
|
63 | 5 | export async function main(...args: string[]) { |
64 | 6 | if (!(args.length === 1 && typeof args[0] === 'string')) { |
|
0 commit comments