summaryrefslogtreecommitdiff
path: root/cli/js/compiler_util.ts
blob: f541ea46fc3ae82fcea0668460dcdf00cf979130 (plain)
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
321
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

import { bold, cyan, yellow } from "./colors.ts";
import { CompilerOptions } from "./compiler_api.ts";
import { buildBundle } from "./compiler_bundler.ts";
import { ConfigureResponse, Host } from "./compiler_host.ts";
import { SourceFile } from "./compiler_sourcefile.ts";
import { sendSync } from "./dispatch_json.ts";
import * as dispatch from "./dispatch.ts";
import { TextDecoder, TextEncoder } from "./text_encoding.ts";
import { core } from "./core.ts";
import * as util from "./util.ts";
import { assert } from "./util.ts";
import { writeFileSync } from "./write_file.ts";

/** Type for the write fall callback that allows delegation from the compiler
 * host on writing files. */
export type WriteFileCallback = (
  fileName: string,
  data: string,
  sourceFiles?: readonly ts.SourceFile[]
) => void;

/** An object which is passed to `createWriteFile` to be used to read and set
 * state related to the emit of a program. */
export interface WriteFileState {
  type: CompilerRequestType;
  bundle?: boolean;
  host?: Host;
  outFile?: string;
  rootNames: string[];
  emitMap?: Record<string, string>;
  emitBundle?: string;
  sources?: Record<string, string>;
}

// Warning! The values in this enum are duplicated in `cli/msg.rs`
// Update carefully!
export enum CompilerRequestType {
  Compile = 0,
  RuntimeCompile = 1,
  RuntimeTranspile = 2
}

export const OUT_DIR = "$deno$";

/** Cache the contents of a file on the trusted side. */
function cache(
  moduleId: string,
  emittedFileName: string,
  contents: string,
  checkJs = false
): void {
  util.log("compiler::cache", { moduleId, emittedFileName, checkJs });
  const sf = SourceFile.get(moduleId);

  if (sf) {
    // NOTE: If it's a `.json` file we don't want to write it to disk.
    // JSON files are loaded and used by TS compiler to check types, but we don't want
    // to emit them to disk because output file is the same as input file.
    if (sf.extension === ts.Extension.Json) {
      return;
    }

    // NOTE: JavaScript files are only cached to disk if `checkJs`
    // option in on
    if (sf.extension === ts.Extension.Js && !checkJs) {
      return;
    }
  }

  if (emittedFileName.endsWith(".map")) {
    // Source Map
    sendSync(dispatch.OP_CACHE, {
      extension: ".map",
      moduleId,
      contents
    });
  } else if (
    emittedFileName.endsWith(".js") ||
    emittedFileName.endsWith(".json")
  ) {
    // Compiled JavaScript
    sendSync(dispatch.OP_CACHE, {
      extension: ".js",
      moduleId,
      contents
    });
  } else {
    assert(false, `Trying to cache unhandled file type "${emittedFileName}"`);
  }
}

let OP_FETCH_ASSET: number;

/**
 * This op is called only during snapshotting.
 *
 * We really don't want to depend on JSON dispatch
 * during snapshotting, so this op exchanges strings with Rust
 * as raw byte arrays.
 */
export function getAsset(name: string): string {
  if (!OP_FETCH_ASSET) {
    const ops = core.ops();
    const opFetchAsset = ops["fetch_asset"];
    assert(opFetchAsset, "OP_FETCH_ASSET is not registered");
    OP_FETCH_ASSET = opFetchAsset;
  }

  const encoder = new TextEncoder();
  const decoder = new TextDecoder();
  const sourceCodeBytes = core.dispatch(OP_FETCH_ASSET, encoder.encode(name));
  return decoder.decode(sourceCodeBytes!);
}

/** Generates a `writeFile` function which can be passed to the compiler `Host`
 * to use when emitting files. */
export function createWriteFile(state: WriteFileState): WriteFileCallback {
  const encoder = new TextEncoder();
  if (state.type === CompilerRequestType.Compile) {
    return function writeFile(
      fileName: string,
      data: string,
      sourceFiles?: readonly ts.SourceFile[]
    ): void {
      assert(
        sourceFiles != null,
        `Unexpected emit of "${fileName}" which isn't part of a program.`
      );
      assert(state.host);
      if (!state.bundle) {
        assert(sourceFiles.length === 1);
        cache(
          sourceFiles[0].fileName,
          fileName,
          data,
          state.host.getCompilationSettings().checkJs
        );
      } else {
        // if the fileName is set to an internal value, just noop, this is
        // used in the Rust unit tests.
        if (state.outFile && state.outFile.startsWith(OUT_DIR)) {
          return;
        }
        // we only support single root names for bundles
        assert(
          state.rootNames.length === 1,
          `Only one root name supported.  Got "${JSON.stringify(
            state.rootNames
          )}"`
        );
        // this enriches the string with the loader and re-exports the
        // exports of the root module
        const content = buildBundle(state.rootNames[0], data, sourceFiles);
        if (state.outFile) {
          const encodedData = encoder.encode(content);
          console.warn(`Emitting bundle to "${state.outFile}"`);
          writeFileSync(state.outFile, encodedData);
          console.warn(`${util.humanFileSize(encodedData.length)} emitted.`);
        } else {
          console.log(content);
        }
      }
    };
  }

  return function writeFile(
    fileName: string,
    data: string,
    sourceFiles?: readonly ts.SourceFile[]
  ): void {
    assert(sourceFiles != null);
    assert(state.host);
    assert(state.emitMap);
    if (!state.bundle) {
      assert(sourceFiles.length === 1);
      state.emitMap[fileName] = data;
      // we only want to cache the compiler output if we are resolving
      // modules externally
      if (!state.sources) {
        cache(
          sourceFiles[0].fileName,
          fileName,
          data,
          state.host.getCompilationSettings().checkJs
        );
      }
    } else {
      // we only support single root names for bundles
      assert(state.rootNames.length === 1);
      state.emitBundle = buildBundle(state.rootNames[0], data, sourceFiles);
    }
  };
}

/** Take a runtime set of compiler options as stringified JSON and convert it
 * to a set of TypeScript compiler options. */
export function convertCompilerOptions(str: string): ts.CompilerOptions {
  const options: CompilerOptions = JSON.parse(str);
  const out: Record<string, unknown> = {};
  const keys = Object.keys(options) as Array<keyof CompilerOptions>;
  for (const key of keys) {
    switch (key) {
      case "jsx":
        const value = options[key];
        if (value === "preserve") {
          out[key] = ts.JsxEmit.Preserve;
        } else if (value === "react") {
          out[key] = ts.JsxEmit.React;
        } else {
          out[key] = ts.JsxEmit.ReactNative;
        }
        break;
      case "module":
        switch (options[key]) {
          case "amd":
            out[key] = ts.ModuleKind.AMD;
            break;
          case "commonjs":
            out[key] = ts.ModuleKind.CommonJS;
            break;
          case "es2015":
          case "es6":
            out[key] = ts.ModuleKind.ES2015;
            break;
          case "esnext":
            out[key] = ts.ModuleKind.ESNext;
            break;
          case "none":
            out[key] = ts.ModuleKind.None;
            break;
          case "system":
            out[key] = ts.ModuleKind.System;
            break;
          case "umd":
            out[key] = ts.ModuleKind.UMD;
            break;
          default:
            throw new TypeError("Unexpected module type");
        }
        break;
      case "target":
        switch (options[key]) {
          case "es3":
            out[key] = ts.ScriptTarget.ES3;
            break;
          case "es5":
            out[key] = ts.ScriptTarget.ES5;
            break;
          case "es6":
          case "es2015":
            out[key] = ts.ScriptTarget.ES2015;
            break;
          case "es2016":
            out[key] = ts.ScriptTarget.ES2016;
            break;
          case "es2017":
            out[key] = ts.ScriptTarget.ES2017;
            break;
          case "es2018":
            out[key] = ts.ScriptTarget.ES2018;
            break;
          case "es2019":
            out[key] = ts.ScriptTarget.ES2019;
            break;
          case "es2020":
            out[key] = ts.ScriptTarget.ES2020;
            break;
          case "esnext":
            out[key] = ts.ScriptTarget.ESNext;
            break;
          default:
            throw new TypeError("Unexpected emit target.");
        }
      default:
        out[key] = options[key];
    }
  }
  return out as ts.CompilerOptions;
}

/** An array of TypeScript diagnostic types we ignore. */
export const ignoredDiagnostics = [
  // TS1103: 'for-await-of' statement is only allowed within an async function
  // or async generator.
  1103,
  // TS1308: 'await' expression is only allowed within an async function.
  1308,
  // TS2691: An import path cannot end with a '.ts' extension. Consider
  // importing 'bad-module' instead.
  2691,
  // TS5009: Cannot find the common subdirectory path for the input files.
  5009,
  // TS5055: Cannot write file
  // 'http://localhost:4545/tests/subdir/mt_application_x_javascript.j4.js'
  // because it would overwrite input file.
  5055,
  // TypeScript is overly opinionated that only CommonJS modules kinds can
  // support JSON imports.  Allegedly this was fixed in
  // Microsoft/TypeScript#26825 but that doesn't seem to be working here,
  // so we will ignore complaints about this compiler setting.
  5070
];

/** When doing a host configuration, processing the response and logging out
 * and options which were ignored. */
export function processConfigureResponse(
  configResult: ConfigureResponse,
  configPath: string
): ts.Diagnostic[] | undefined {
  const { ignoredOptions, diagnostics } = configResult;
  if (ignoredOptions) {
    console.warn(
      yellow(`Unsupported compiler options in "${configPath}"\n`) +
        cyan(`  The following options were ignored:\n`) +
        `    ${ignoredOptions.map((value): string => bold(value)).join(", ")}`
    );
  }
  return diagnostics;
}