-
Notifications
You must be signed in to change notification settings - Fork 11.9k
Expand file tree
/
Copy pathtransform-javascript.ts
More file actions
217 lines (185 loc) · 5.68 KB
/
transform-javascript.ts
File metadata and controls
217 lines (185 loc) · 5.68 KB
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { RawSourceMap } from 'source-map';
import * as ts from 'typescript';
export interface TransformJavascriptOptions {
content: string;
inputFilePath?: string;
outputFilePath?: string;
emitSourceMap?: boolean;
strict?: boolean;
typeCheck?: boolean;
getTransforms: Array<(program?: ts.Program) => ts.TransformerFactory<ts.SourceFile>>;
}
export interface TransformJavascriptOutput {
content: string | null;
sourceMap: RawSourceMap | null;
emitSkipped: boolean;
}
interface DiagnosticSourceFile extends ts.SourceFile {
readonly parseDiagnostics?: ReadonlyArray<ts.Diagnostic>;
}
function validateDiagnostics(diagnostics: ReadonlyArray<ts.Diagnostic>, strict?: boolean): boolean {
// Print error diagnostics.
const hasError = diagnostics.some(diag => diag.category === ts.DiagnosticCategory.Error);
if (hasError) {
// Throw only if we're in strict mode, otherwise return original content.
if (strict) {
const errorMessages = ts.formatDiagnostics(diagnostics, {
getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
getNewLine: () => ts.sys.newLine,
getCanonicalFileName: (f: string) => f,
});
throw new Error(`
TS failed with the following error messages:
${errorMessages}
`);
} else {
return false;
}
}
return true;
}
export function transformJavascript(
options: TransformJavascriptOptions,
): TransformJavascriptOutput {
const {
content,
getTransforms,
emitSourceMap,
inputFilePath,
outputFilePath,
strict,
} = options;
// Bail if there's no transform to do.
if (getTransforms.length === 0) {
return {
content: null,
sourceMap: null,
emitSkipped: true,
};
}
const allowFastPath = options.typeCheck === false && !emitSourceMap;
const outputs = new Map<string, string>();
const tempFilename = 'bo-default-file.js';
const tempSourceFile = ts.createSourceFile(
tempFilename,
content,
ts.ScriptTarget.Latest,
allowFastPath,
);
const parseDiagnostics = (tempSourceFile as DiagnosticSourceFile).parseDiagnostics;
const tsOptions: ts.CompilerOptions = {
// We target latest so that there is no downleveling.
target: ts.ScriptTarget.Latest,
isolatedModules: true,
suppressOutputPathCheck: true,
allowNonTsExtensions: true,
noLib: true,
noResolve: true,
sourceMap: emitSourceMap,
inlineSources: emitSourceMap,
inlineSourceMap: false,
};
if (allowFastPath && parseDiagnostics) {
if (!validateDiagnostics(parseDiagnostics, strict)) {
return {
content: null,
sourceMap: null,
emitSkipped: true,
};
}
const transforms = getTransforms.map((getTf) => getTf(undefined));
const result = ts.transform(tempSourceFile, transforms, tsOptions);
if (result.transformed.length === 0 || result.transformed[0] === tempSourceFile) {
return {
content: null,
sourceMap: null,
emitSkipped: true,
};
}
const printer = ts.createPrinter(
undefined,
{
onEmitNode: result.emitNodeWithNotification,
substituteNode: result.substituteNode,
},
);
const output = printer.printFile(result.transformed[0]);
result.dispose();
return {
content: output,
sourceMap: null,
emitSkipped: false,
};
}
const host: ts.CompilerHost = {
getSourceFile: (fileName) => {
if (fileName !== tempFilename) {
throw new Error(`File ${fileName} does not have a sourceFile.`);
}
return tempSourceFile;
},
getDefaultLibFileName: () => 'lib.d.ts',
getCurrentDirectory: () => '',
getDirectories: () => [],
getCanonicalFileName: (fileName) => fileName,
useCaseSensitiveFileNames: () => true,
getNewLine: () => '\n',
fileExists: (fileName) => fileName === tempFilename,
readFile: (_fileName) => '',
writeFile: (fileName, text) => outputs.set(fileName, text),
};
const program = ts.createProgram([tempFilename], tsOptions, host);
const diagnostics = program.getSyntacticDiagnostics(tempSourceFile);
if (!validateDiagnostics(diagnostics, strict)) {
return {
content: null,
sourceMap: null,
emitSkipped: true,
};
}
// We need the checker inside transforms.
const transforms = getTransforms.map((getTf) => getTf(program));
program.emit(undefined, undefined, undefined, undefined, { before: transforms, after: [] });
let transformedContent = outputs.get(tempFilename);
if (!transformedContent) {
return {
content: null,
sourceMap: null,
emitSkipped: true,
};
}
let sourceMap: RawSourceMap | null = null;
const tsSourceMap = outputs.get(`${tempFilename}.map`);
if (emitSourceMap && tsSourceMap) {
const urlRegExp = /^\/\/# sourceMappingURL=[^\r\n]*/gm;
sourceMap = JSON.parse(tsSourceMap) as RawSourceMap;
// Fix sourcemaps file references.
if (outputFilePath) {
sourceMap.file = outputFilePath;
transformedContent = transformedContent.replace(urlRegExp,
`//# sourceMappingURL=${sourceMap.file}.map\n`);
if (inputFilePath) {
sourceMap.sources = [inputFilePath];
} else {
sourceMap.sources = [''];
}
} else {
// TODO: figure out if we should inline sources here.
transformedContent = transformedContent.replace(urlRegExp, '');
sourceMap.file = '';
sourceMap.sources = [''];
}
}
return {
content: transformedContent,
sourceMap,
emitSkipped: false,
};
}