-
-
Notifications
You must be signed in to change notification settings - Fork 62
/
compiler.ts
194 lines (166 loc) · 5.34 KB
/
compiler.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import * as ESTree from "estree";
import * as ts from "typescript";
import { Transformer } from "./Transformer";
import fs from "fs";
import path from "path";
let SOURCEMAPPING_URL = "sourceMa";
SOURCEMAPPING_URL += "ppingURL";
const SOURCEMAPPING_URL_RE = new RegExp(`^//#\\s+${SOURCEMAPPING_URL}=.+\\n?`, "m");
export enum CompileMode {
Types = "dts",
Js = "js",
}
interface CacheOptions {
tsconfig: string;
compilerOptions: ts.CompilerOptions;
mode: CompileMode;
}
interface CacheEntry {
parsedCompilerOptions: ts.CompilerOptions;
compiler: ts.Program;
}
const OPTIONS_OVERRIDES: ts.CompilerOptions = {
module: ts.ModuleKind.ES2015,
noEmitOnError: false,
noEmit: false,
skipLibCheck: true,
declaration: true,
allowJs: true,
checkJs: true,
resolveJsonModule: true,
sourceMap: true,
inlineSourceMap: false,
declarationMap: true,
};
const COMPILERCACHE = new Map<string, CacheEntry>();
function createCompiler(options: CacheOptions) {
const file =
!fs.existsSync(options.tsconfig) || fs.lstatSync(options.tsconfig).isFile()
? path.basename(options.tsconfig)
: undefined;
const configFileName = ts.findConfigFile(
options.tsconfig,
ts.sys.fileExists,
path.extname(options.tsconfig) ? file : undefined,
);
// istanbul ignore if
if (!configFileName) {
throw new Error(`rollup-plugin-dts: Couldn't find tsconfig file`);
}
const compilerOptions: ts.CompilerOptions = {
...options.compilerOptions,
...OPTIONS_OVERRIDES,
};
let diagnostic;
const configParseResult = ts.getParsedCommandLineOfConfigFile(configFileName, compilerOptions, {
...ts.sys,
onUnRecoverableConfigFileDiagnostic(d) {
// istanbul ignore next
diagnostic = d;
},
});
// istanbul ignore if
if (!configParseResult) {
console.log(diagnostic);
throw new Error(`rollup-plugin-dts: Couldn't process compiler options`);
}
const { fileNames, options: parsedCompilerOptions } = configParseResult;
return {
parsedCompilerOptions,
compiler: ts.createProgram(fileNames, parsedCompilerOptions),
};
}
interface EmitFiles {
dts: string;
dtsMap: string;
js: string;
jsMap: string;
}
function getEmitFiles(compiler: ts.Program, fileName: string): EmitFiles {
const result: EmitFiles = {
dts: "",
dtsMap: `{"mappings": ""}`,
js: "",
jsMap: `{"mappings": ""}`,
};
if (fileName.endsWith(".d.ts")) {
result.dts = ts.sys.readFile(fileName, "utf-8")!;
return result;
}
const sourceFile = compiler.getSourceFile(fileName)!;
const emitResult = compiler.emit(sourceFile, (fileName, data) => {
data = data.replace(SOURCEMAPPING_URL_RE, "").trim();
if (fileName.endsWith(".d.ts")) {
result.dts = data;
} else if (fileName.endsWith(".js")) {
result.js = data;
// NOTE(swatinem): hm, there are still issues with this,
// I couldn’t get it to work locally
// See https://github.com/Microsoft/TypeScript/issues/25662
// } else if (fileName.endsWith(".d.ts.map")) {
// result.dtsMap = data;
} else if (fileName.endsWith(".js.map")) {
result.jsMap = data;
}
});
if (emitResult.emitSkipped) {
throw new Error(emitResult.diagnostics.join("\n"));
}
return result;
}
export function getCachedCompiler(options: CacheOptions) {
const cacheKey = JSON.stringify(options);
function lazyCreate() {
let compiler = COMPILERCACHE.get(cacheKey);
if (!compiler) {
compiler = createCompiler(options);
COMPILERCACHE.set(cacheKey, compiler);
}
return compiler;
}
return {
resolve(importee: string, importer: string): string | void {
const { parsedCompilerOptions } = lazyCreate();
const result = ts.nodeModuleNameResolver(importee, importer, parsedCompilerOptions, ts.sys);
// hm, maybe we should use `isExternalLibraryImport` at some point…
// istanbul ignore else
if (result.resolvedModule && result.resolvedModule.resolvedFileName) {
return result.resolvedModule.resolvedFileName;
} else {
return;
}
},
load(fileName: string): { code: string; map: string; ast?: ESTree.Program } {
const { compiler } = lazyCreate();
const emitFiles = getEmitFiles(compiler, fileName);
if (options.mode === CompileMode.Js) {
return {
code: emitFiles.js,
map: emitFiles.jsMap,
};
}
let code = emitFiles.dts;
let dtsFileName = fileName;
if (!fileName.endsWith(".d.ts")) {
dtsFileName = fileName.slice(0, -path.extname(fileName).length) + ".d.ts";
}
const dtsSource = ts.createSourceFile(dtsFileName, code, ts.ScriptTarget.Latest, true);
const converter = new Transformer(dtsSource);
const { ast, fixups } = converter.transform();
// NOTE(swatinem):
// hm, typescript generates `export default` without a declare,
// but rollup moves the `export default` to a different place, which leaves
// the function declaration without a `declare`.
// Well luckily both words have the same length, haha :-D
code = code.replace(/(export\s+)default(\s+(function|class))/m, "$1declare$2");
for (const fixup of fixups) {
code = code.slice(0, fixup.range.start) + fixup.identifier + code.slice(fixup.range.end);
}
return {
code,
ast,
map: emitFiles.dtsMap,
};
},
};
}