/
index.ts
94 lines (77 loc) · 2.36 KB
/
index.ts
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import initTrace from "debug";
import * as fs from "fs";
import * as ts from "typescript";
import * as capnpc_ts from "capnpc-ts";
const trace = initTrace("capnpc");
trace("load");
/**
* The equivalent of tsconfig.json used when compiling the emitted .ts file to .js.
*
* The output of this tool should aim to be readable, documented javascript
* for the developers consuming it. They can (and probably already do) transpile
* the JS further to meet whatever ES version / module system / minification
* needs they have.
*/
const COMPILE_OPTIONS: ts.CompilerOptions = {
module: ts.ModuleKind.None,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
noEmitOnError: true,
noFallthroughCasesInSwitch: true,
noImplicitReturns: true,
noUnusedLocals: false,
noUnusedParameters: false,
preserveConstEnums: true,
removeComments: false,
sourceMap: false,
strict: true,
stripInternal: true,
target: ts.ScriptTarget.ES2015
};
export async function main() {
return capnpc_ts
.run()
.then(ctx => {
transpileAll(ctx);
})
.thenReturn()
.tapCatch(reason => {
// tslint:disable-next-line:no-console
console.error(reason);
process.exit(1);
});
}
export function transpileAll(ctx: capnpc_ts.CodeGeneratorContext): void {
trace("transpileAll()", ctx.files);
const tsFilePaths = ctx.files.map(f => f.tsPath);
const program = ts.createProgram(tsFilePaths, COMPILE_OPTIONS);
const emitResult = program.emit();
if (!emitResult.emitSkipped) {
trace("emit succeeded");
tsFilePaths.forEach(fs.unlinkSync);
} else {
trace("emit failed");
const allDiagnostics = ts
.getPreEmitDiagnostics(program)
.concat(emitResult.diagnostics);
allDiagnostics.forEach(diagnostic => {
const message = ts.flattenDiagnosticMessageText(
diagnostic.messageText,
"\n"
);
if (diagnostic.file && diagnostic.start) {
const {
line,
character
} = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
/* tslint:disable-next-line:no-console */
console.log(
`${diagnostic.file.fileName}:${line + 1}:${character + 1} ${message}`
);
} else {
/* tslint:disable-next-line:no-console */
console.log(`==> ${message}`);
}
});
throw new Error(capnpc_ts.errors.GEN_TS_EMIT_FAILED);
}
}