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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
|
// Because we're bootstrapping the TS compiler without dependencies on Node,
// this is written in JS.
const ASSETS = "$asset$";
let replacements;
function main(configText, rootNames, replacements_) {
println(`>>> ts version ${ts.version}`);
println(`>>> rootNames ${rootNames}`);
replacements = replacements_;
replacements["DENO_REPLACE_TS_VERSION"] = ts.version;
println(`>>> replacements ${JSON.stringify(replacements)}`);
const host = new Host();
assert(rootNames.length > 0);
let { options, diagnostics } = configure(configText);
handleDiagnostics(host, diagnostics);
println(`>>> TS config: ${JSON.stringify(options)}`);
const program = ts.createProgram(rootNames, options, host);
diagnostics = ts.getPreEmitDiagnostics(program).filter(({ code }) => {
// TS2691: An import path cannot end with a '.ts' extension. Consider
// importing 'bad-module' instead.
if (code === 2691) return false;
// TS5009: Cannot find the common subdirectory path for the input files.
if (code === 5009) return false;
return true;
});
handleDiagnostics(host, diagnostics);
const emitResult = program.emit();
handleDiagnostics(host, emitResult.diagnostics);
dispatch("setEmitResult", emitResult);
}
function println(...s) {
Deno.core.print(s.join(" ") + "\n");
}
function unreachable() {
throw Error("unreachable");
}
function assert(cond) {
if (!cond) {
throw Error("assert");
}
}
// decode(Uint8Array): string
function decodeAscii(ui8) {
let out = "";
for (let i = 0; i < ui8.length; i++) {
out += String.fromCharCode(ui8[i]);
}
return out;
}
function encode(str) {
const charCodes = str.split("").map(c => c.charCodeAt(0));
const ui8 = new Uint8Array(charCodes);
return ui8;
}
// Warning! The op_id values below are shared between this code and
// the Rust side. Update with care!
const ops = {
readFile: 49,
exit: 50,
writeFile: 51,
resolveModuleNames: 52,
setEmitResult: 53
};
// interface CompilerHost extends ModuleResolutionHost {
class Host {
// fileExists(fileName: string): boolean;
fileExists(fileName) {
return true;
}
// readFile(fileName: string): string | undefined;
readFile() {
unreachable();
}
// trace?(s: string): void;
// directoryExists?(directoryName: string): boolean;
// realpath?(path: string): string;
// getCurrentDirectory?(): string;
// getDirectories?(path: string): string[];
// useCaseSensitiveFileNames(): boolean;
useCaseSensitiveFileNames() {
return false;
}
// getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibFileName(options) {
return "lib.deno_core.d.ts";
}
// getDefaultLibLocation?(): string;
getDefaultLibLocation() {
return ASSETS;
}
// getCurrentDirectory(): string;
getCurrentDirectory() {
return ".";
}
// getCanonicalFileName(fileName: string): string
getCanonicalFileName(fileName) {
unreachable();
}
// getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?:
// (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile
// | undefined;
getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) {
assert(!shouldCreateNewSourceFile); // We haven't yet encountered this.
// This hacks around the fact that TypeScript tries to magically guess the
// d.ts filename.
if (fileName.startsWith("$typeRoots$")) {
assert(fileName.startsWith("$typeRoots$/"));
assert(fileName.endsWith("/index.d.ts"));
fileName = fileName
.replace("$typeRoots$/", "")
.replace("/index.d.ts", "");
}
let { sourceCode, moduleName } = dispatch("readFile", {
fileName,
languageVersion,
shouldCreateNewSourceFile
});
// TODO(ry) A terrible hack. Please remove ASAP.
if (fileName.endsWith("typescript.d.ts")) {
sourceCode = sourceCode.replace("export = ts;", "");
}
// TODO(ry) A terrible hack. Please remove ASAP.
for (let key of Object.keys(replacements)) {
let val = replacements[key];
sourceCode = sourceCode.replace(key, val);
}
let sourceFile = ts.createSourceFile(fileName, sourceCode, languageVersion);
sourceFile.moduleName = moduleName;
return sourceFile;
}
/*
writeFile(
fileName: string,
data: string,
writeByteOrderMark: boolean,
onError?: (message: string) => void,
sourceFiles?: ReadonlyArray<ts.SourceFile>
): void
*/
writeFile(
fileName,
data,
writeByteOrderMark,
onError = null,
sourceFiles = null
) {
const moduleName = sourceFiles[sourceFiles.length - 1].moduleName;
return dispatch("writeFile", { fileName, moduleName, data });
}
// getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined;
getSourceFileByPath(
fileName,
path,
languageVersion,
onError,
shouldCreateNewSourceFile
) {
unreachable();
}
// getCancellationToken?(): CancellationToken;
getCancellationToken() {
unreachable();
}
// getCanonicalFileName(fileName: string): string;
getCanonicalFileName(fileName) {
return fileName;
}
// getNewLine(): string
getNewLine() {
return "\n";
}
// readDirectory?(rootDir: string, extensions: ReadonlyArray<string>, excludes: ReadonlyArray<string> | undefined, includes: ReadonlyArray<string>, depth?: number): string[];
readDirectory() {
unreachable();
}
// resolveModuleNames?(
// moduleNames: string[],
// containingFile: string,
// reusedNames?: string[],
// redirectedReference?: ResolvedProjectReference
// ): (ResolvedModule | undefined)[];
resolveModuleNames(moduleNames, containingFile) {
const resolvedNames = dispatch("resolveModuleNames", {
moduleNames,
containingFile
});
const r = resolvedNames.map(resolvedFileName => {
const extension = getExtension(resolvedFileName);
return { resolvedFileName, extension };
});
return r;
}
// resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[];
/*
resolveTypeReferenceDirectives() {
unreachable();
}
*/
// getEnvironmentVariable?(name: string): string | undefined;
getEnvironmentVariable() {
unreachable();
}
// createHash?(data: string): string;
createHash() {
unreachable();
}
// getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined;
getParsedCommandLine() {
unreachable();
}
}
function configure(configurationText) {
const { config, error } = ts.parseConfigFileTextToJson(
"tsconfig.json",
configurationText
);
if (error) {
return { diagnostics: [error] };
}
const { options, errors } = ts.convertCompilerOptionsFromJson(
config.compilerOptions,
""
);
return {
options,
diagnostics: errors.length ? errors : undefined
};
}
function dispatch(opName, obj) {
const s = JSON.stringify(obj);
const msg = encode(s);
const resUi8 = Deno.core.dispatch(ops[opName], msg);
const resStr = decodeAscii(resUi8);
const res = JSON.parse(resStr);
if (!res["ok"]) {
throw Error(`${opName} failed ${res["err"]}. Args: ${JSON.stringify(obj)}`);
}
return res["ok"];
}
function exit(code) {
dispatch("exit", { code });
unreachable();
}
// Maximum number of diagnostics to display.
const MAX_ERRORS = 5;
function handleDiagnostics(host, diagnostics) {
if (diagnostics && diagnostics.length) {
let rest = 0;
if (diagnostics.length > MAX_ERRORS) {
rest = diagnostics.length - MAX_ERRORS;
diagnostics = diagnostics.slice(0, MAX_ERRORS);
}
const msg = ts.formatDiagnosticsWithColorAndContext(diagnostics, host);
println(msg);
if (rest) {
println(`And ${rest} other errors.`);
}
exit(1);
}
}
/** Returns the TypeScript Extension enum for a given media type. */
function getExtension(fileName) {
if (fileName.endsWith(".d.ts")) {
return ts.Extension.Dts;
} else if (fileName.endsWith(".ts")) {
return ts.Extension.Ts;
} else if (fileName.endsWith(".js")) {
return ts.Extension.Js;
} else {
throw TypeError(`Cannot resolve extension for ${fileName}`);
}
}
|