@rushstack/heft-typescript-plugin 0.1.0-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +12 -0
  3. package/dist/heft-typescript-plugin.d.ts +111 -0
  4. package/dist/tsdoc-metadata.json +11 -0
  5. package/heft-plugin.json +10 -0
  6. package/lib/EmitFilesPatch.d.ts +28 -0
  7. package/lib/EmitFilesPatch.d.ts.map +1 -0
  8. package/lib/EmitFilesPatch.js +99 -0
  9. package/lib/EmitFilesPatch.js.map +1 -0
  10. package/lib/Performance.d.ts +7 -0
  11. package/lib/Performance.d.ts.map +1 -0
  12. package/lib/Performance.js +5 -0
  13. package/lib/Performance.js.map +1 -0
  14. package/lib/TypeScriptBuilder.d.ts +69 -0
  15. package/lib/TypeScriptBuilder.d.ts.map +1 -0
  16. package/lib/TypeScriptBuilder.js +681 -0
  17. package/lib/TypeScriptBuilder.js.map +1 -0
  18. package/lib/TypeScriptPlugin.d.ts +102 -0
  19. package/lib/TypeScriptPlugin.d.ts.map +1 -0
  20. package/lib/TypeScriptPlugin.js +191 -0
  21. package/lib/TypeScriptPlugin.js.map +1 -0
  22. package/lib/fileSystem/TypeScriptCachedFileSystem.d.ts +36 -0
  23. package/lib/fileSystem/TypeScriptCachedFileSystem.d.ts.map +1 -0
  24. package/lib/fileSystem/TypeScriptCachedFileSystem.js +163 -0
  25. package/lib/fileSystem/TypeScriptCachedFileSystem.js.map +1 -0
  26. package/lib/index.d.ts +8 -0
  27. package/lib/index.d.ts.map +1 -0
  28. package/lib/index.js +10 -0
  29. package/lib/index.js.map +1 -0
  30. package/lib/internalTypings/TypeScriptInternals.d.ts +90 -0
  31. package/lib/internalTypings/TypeScriptInternals.d.ts.map +1 -0
  32. package/lib/internalTypings/TypeScriptInternals.js +5 -0
  33. package/lib/internalTypings/TypeScriptInternals.js.map +1 -0
  34. package/lib/schemas/anything.schema.json +28 -0
  35. package/lib/schemas/typescript.schema.json +101 -0
  36. package/package.json +39 -0
@@ -0,0 +1,681 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
3
+ // See LICENSE in the project root for license information.
4
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
+ if (k2 === undefined) k2 = k;
6
+ var desc = Object.getOwnPropertyDescriptor(m, k);
7
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8
+ desc = { enumerable: true, get: function() { return m[k]; } };
9
+ }
10
+ Object.defineProperty(o, k2, desc);
11
+ }) : (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ o[k2] = m[k];
14
+ }));
15
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
17
+ }) : function(o, v) {
18
+ o["default"] = v;
19
+ });
20
+ var __importStar = (this && this.__importStar) || function (mod) {
21
+ if (mod && mod.__esModule) return mod;
22
+ var result = {};
23
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
24
+ __setModuleDefault(result, mod);
25
+ return result;
26
+ };
27
+ Object.defineProperty(exports, "__esModule", { value: true });
28
+ exports.TypeScriptBuilder = void 0;
29
+ const crypto = __importStar(require("crypto"));
30
+ const path = __importStar(require("path"));
31
+ const semver = __importStar(require("semver"));
32
+ const node_core_library_1 = require("@rushstack/node-core-library");
33
+ const EmitFilesPatch_1 = require("./EmitFilesPatch");
34
+ const TypeScriptCachedFileSystem_1 = require("./fileSystem/TypeScriptCachedFileSystem");
35
+ // type TWatchCompilerHost =
36
+ // TTypescript.WatchCompilerHostOfFilesAndCompilerOptions<TTypescript.EmitAndSemanticDiagnosticsBuilderProgram>;
37
+ // type TWatchSolutionHost =
38
+ // TTypescript.SolutionBuilderWithWatchHost<TTypescript.EmitAndSemanticDiagnosticsBuilderProgram>;
39
+ const EMPTY_JSON = {};
40
+ const OLDEST_SUPPORTED_TS_MAJOR_VERSION = 2;
41
+ const OLDEST_SUPPORTED_TS_MINOR_VERSION = 9;
42
+ const NEWEST_SUPPORTED_TS_MAJOR_VERSION = 4;
43
+ const NEWEST_SUPPORTED_TS_MINOR_VERSION = 7;
44
+ class TypeScriptBuilder {
45
+ constructor(configuration) {
46
+ this._tsReadJsonCache = new Map();
47
+ this._cachedFileSystem = new TypeScriptCachedFileSystem_1.TypeScriptCachedFileSystem();
48
+ this._configuration = configuration;
49
+ this._typescriptLogger = configuration.scopedLogger;
50
+ this._typescriptTerminal = configuration.scopedLogger.terminal;
51
+ }
52
+ get _tsCacheFilePath() {
53
+ if (!this.__tsCacheFilePath) {
54
+ // TypeScript internally handles if the tsconfig options have changed from when the tsbuildinfo file was created.
55
+ // We only need to hash our additional Heft configuration.
56
+ const configHash = crypto.createHash('sha1');
57
+ configHash.update(JSON.stringify(this._configuration.additionalModuleKindsToEmit || {}));
58
+ const serializedConfigHash = configHash
59
+ .digest('base64')
60
+ .slice(0, 8)
61
+ .replace(/\+/g, '-')
62
+ .replace(/\//g, '_');
63
+ // This conversion is theoretically redundant, but it is here to make absolutely sure that the path is formatted
64
+ // using only '/' as the directory separator so that incremental builds don't break on Windows.
65
+ // TypeScript will normalize to '/' when serializing, but not on the direct input, and uses exact string equality.
66
+ const normalizedCacheFolderPath = node_core_library_1.Path.convertToSlashes(this._configuration.buildMetadataFolderPath);
67
+ this.__tsCacheFilePath = `${normalizedCacheFolderPath}/ts_${serializedConfigHash}.json`;
68
+ }
69
+ return this.__tsCacheFilePath;
70
+ }
71
+ async invokeAsync() {
72
+ // Determine the compiler version
73
+ const compilerPackageJsonFilename = path.join(this._configuration.typeScriptToolPath, 'package.json');
74
+ const packageJson = await node_core_library_1.JsonFile.loadAsync(compilerPackageJsonFilename);
75
+ this._typescriptVersion = packageJson.version;
76
+ const parsedVersion = semver.parse(this._typescriptVersion);
77
+ if (!parsedVersion) {
78
+ throw new Error(`Unable to parse version "${this._typescriptVersion}" for TypeScript compiler package in: ` +
79
+ compilerPackageJsonFilename);
80
+ }
81
+ this._typescriptParsedVersion = parsedVersion;
82
+ // Detect what features this compiler supports. Note that manually comparing major/minor numbers
83
+ // loosens the matching to accept prereleases such as "3.6.0-dev.20190530"
84
+ this._capabilities = {
85
+ incrementalProgram: false,
86
+ solutionBuilder: this._typescriptParsedVersion.major >= 3
87
+ };
88
+ if (this._typescriptParsedVersion.major > 3 ||
89
+ (this._typescriptParsedVersion.major === 3 && this._typescriptParsedVersion.minor >= 6)) {
90
+ this._capabilities.incrementalProgram = true;
91
+ }
92
+ this._useSolutionBuilder = !!this._configuration.buildProjectReferences;
93
+ if (this._useSolutionBuilder && !this._capabilities.solutionBuilder) {
94
+ throw new Error(`Building project references requires TypeScript@>=3.0, but the current version is ${this._typescriptVersion}`);
95
+ }
96
+ // Report a warning if the TypeScript version is too old/new. The current oldest supported version is
97
+ // TypeScript 2.9. Prior to that the "ts.getConfigFileParsingDiagnostics()" API is missing; more fixups
98
+ // would be required to deal with that. We won't do that work unless someone requests it.
99
+ if (this._typescriptParsedVersion.major < OLDEST_SUPPORTED_TS_MAJOR_VERSION ||
100
+ (this._typescriptParsedVersion.major === OLDEST_SUPPORTED_TS_MAJOR_VERSION &&
101
+ this._typescriptParsedVersion.minor < OLDEST_SUPPORTED_TS_MINOR_VERSION)) {
102
+ // We don't use writeWarningLine() here because, if the person wants to take their chances with
103
+ // a seemingly unsupported compiler, their build should be allowed to succeed.
104
+ this._typescriptTerminal.writeLine(`The TypeScript compiler version ${this._typescriptVersion} is very old` +
105
+ ` and has not been tested with Heft; it may not work correctly.`);
106
+ }
107
+ else if (this._typescriptParsedVersion.major > NEWEST_SUPPORTED_TS_MAJOR_VERSION ||
108
+ (this._typescriptParsedVersion.major === NEWEST_SUPPORTED_TS_MAJOR_VERSION &&
109
+ this._typescriptParsedVersion.minor > NEWEST_SUPPORTED_TS_MINOR_VERSION)) {
110
+ this._typescriptTerminal.writeLine(`The TypeScript compiler version ${this._typescriptVersion} is newer` +
111
+ ' than the latest version that was tested with Heft ' +
112
+ `(${NEWEST_SUPPORTED_TS_MAJOR_VERSION}.${NEWEST_SUPPORTED_TS_MINOR_VERSION}); it may not work correctly.`);
113
+ }
114
+ const ts = require(this._configuration.typeScriptToolPath);
115
+ ts.performance.enable();
116
+ const measureTsPerformance = (measurementName, fn) => {
117
+ const beforeName = `before${measurementName}`;
118
+ ts.performance.mark(beforeName);
119
+ const result = fn();
120
+ const afterName = `after${measurementName}`;
121
+ ts.performance.mark(afterName);
122
+ ts.performance.measure(measurementName, beforeName, afterName);
123
+ return Object.assign(Object.assign({}, result), { duration: ts.performance.getDuration(measurementName), count: ts.performance.getCount(beforeName) });
124
+ };
125
+ const measureTsPerformanceAsync = async (measurementName, fn) => {
126
+ const beforeName = `before${measurementName}`;
127
+ ts.performance.mark(beforeName);
128
+ const resultPromise = fn();
129
+ const result = await resultPromise;
130
+ const afterName = `after${measurementName}`;
131
+ ts.performance.mark(afterName);
132
+ ts.performance.measure(measurementName, beforeName, afterName);
133
+ return Object.assign(Object.assign({}, result), { duration: ts.performance.getDuration(measurementName) });
134
+ };
135
+ this._typescriptTerminal.writeLine(`Using TypeScript version ${ts.version}`);
136
+ // if (this._configuration.watchMode) {
137
+ // await this._runWatch(ts, measureTsPerformance);
138
+ // } else if (this._useSolutionBuilder) {
139
+ if (this._useSolutionBuilder) {
140
+ this._runSolutionBuild(ts, measureTsPerformance);
141
+ }
142
+ else {
143
+ await this._runBuildAsync(ts, measureTsPerformance, measureTsPerformanceAsync);
144
+ }
145
+ }
146
+ // public async _runWatch(ts: ExtendedTypeScript, measureTsPerformance: PerformanceMeasurer): Promise<void> {
147
+ // //#region CONFIGURE
148
+ // const { duration: configureDurationMs, tsconfig } = measureTsPerformance('Configure', () => {
149
+ // const _tsconfig: TTypescript.ParsedCommandLine = this._loadTsconfig(ts);
150
+ // this._validateTsconfig(ts, _tsconfig);
151
+ // EmitFilesPatch.install(ts, _tsconfig, this._moduleKindsToEmit);
152
+ // return {
153
+ // tsconfig: _tsconfig
154
+ // };
155
+ // });
156
+ // this._typescriptTerminal.writeVerboseLine(`Configure: ${configureDurationMs}ms`);
157
+ // //#endregion
158
+ // if (this._useSolutionBuilder) {
159
+ // const solutionHost: TWatchSolutionHost = this._buildWatchSolutionBuilderHost(ts);
160
+ // const watchBuilder: TTypescript.SolutionBuilder<TTypescript.EmitAndSemanticDiagnosticsBuilderProgram> =
161
+ // ts.createSolutionBuilderWithWatch(solutionHost, [this._configuration.tsconfigPath], {});
162
+ // watchBuilder.build();
163
+ // } else {
164
+ // const compilerHost: TWatchCompilerHost = this._buildWatchCompilerHost(ts, tsconfig);
165
+ // ts.createWatchProgram(compilerHost);
166
+ // }
167
+ // return new Promise(() => {
168
+ // /* never terminate */
169
+ // });
170
+ // }
171
+ async _runBuildAsync(ts, measureTsPerformance, measureTsPerformanceAsync) {
172
+ //#region CONFIGURE
173
+ const { duration: configureDurationMs, tsconfig, compilerHost } = measureTsPerformance('Configure', () => {
174
+ this._overrideTypeScriptReadJson(ts);
175
+ const _tsconfig = this._loadTsconfig(ts);
176
+ this._validateTsconfig(ts, _tsconfig);
177
+ const _compilerHost = this._buildIncrementalCompilerHost(ts, _tsconfig);
178
+ return {
179
+ tsconfig: _tsconfig,
180
+ compilerHost: _compilerHost
181
+ };
182
+ });
183
+ this._typescriptTerminal.writeVerboseLine(`Configure: ${configureDurationMs}ms`);
184
+ //#endregion
185
+ //#region PROGRAM
186
+ // There will be only one program here; emit will get a bit abused if we produce multiple outputs
187
+ let builderProgram = undefined;
188
+ let tsProgram;
189
+ if (tsconfig.options.incremental) {
190
+ builderProgram = ts.createIncrementalProgram({
191
+ rootNames: tsconfig.fileNames,
192
+ options: tsconfig.options,
193
+ projectReferences: tsconfig.projectReferences,
194
+ host: compilerHost,
195
+ configFileParsingDiagnostics: ts.getConfigFileParsingDiagnostics(tsconfig)
196
+ });
197
+ tsProgram = builderProgram.getProgram();
198
+ }
199
+ else {
200
+ tsProgram = ts.createProgram({
201
+ rootNames: tsconfig.fileNames,
202
+ options: tsconfig.options,
203
+ projectReferences: tsconfig.projectReferences,
204
+ host: compilerHost,
205
+ configFileParsingDiagnostics: ts.getConfigFileParsingDiagnostics(tsconfig)
206
+ });
207
+ }
208
+ // Prefer the builder program, since it is what gives us incremental builds
209
+ const genericProgram = builderProgram || tsProgram;
210
+ this._logReadPerformance(ts);
211
+ //#endregion
212
+ //#region ANALYSIS
213
+ const { duration: diagnosticsDurationMs, diagnostics: preDiagnostics } = measureTsPerformance('Analyze', () => {
214
+ const rawDiagnostics = [
215
+ ...genericProgram.getConfigFileParsingDiagnostics(),
216
+ ...genericProgram.getOptionsDiagnostics(),
217
+ ...genericProgram.getSyntacticDiagnostics(),
218
+ ...genericProgram.getGlobalDiagnostics(),
219
+ ...genericProgram.getSemanticDiagnostics()
220
+ ];
221
+ return { diagnostics: rawDiagnostics };
222
+ });
223
+ this._typescriptTerminal.writeVerboseLine(`Analyze: ${diagnosticsDurationMs}ms`);
224
+ //#endregion
225
+ //#region EMIT
226
+ const emitResult = this._emit(ts, tsconfig, genericProgram);
227
+ //#endregion
228
+ this._logEmitPerformance(ts);
229
+ //#region FINAL_ANALYSIS
230
+ // Need to ensure that we include emit diagnostics, since they might not be part of the other sets
231
+ const rawDiagnostics = [...preDiagnostics, ...emitResult.diagnostics];
232
+ //#endregion
233
+ //#region WRITE
234
+ // Using async file system I/O for theoretically better peak performance
235
+ // Also allows to run concurrently with linting
236
+ const writePromise = measureTsPerformanceAsync('Write', () => node_core_library_1.Async.forEachAsync(emitResult.filesToWrite, async ({ filePath, data }) => this._cachedFileSystem.writeFile(filePath, data, { ensureFolderExists: true }), { concurrency: this._configuration.maxWriteParallelism }));
237
+ //#endregion
238
+ const { duration: writeDuration } = await writePromise;
239
+ this._typescriptTerminal.writeVerboseLine(`I/O Write: ${writeDuration}ms (${emitResult.filesToWrite.length} files)`);
240
+ this._logDiagnostics(ts, rawDiagnostics);
241
+ this._configuration.emitChangedFilesCallback(tsProgram, emitResult.changedSourceFiles);
242
+ }
243
+ _runSolutionBuild(ts, measureTsPerformance) {
244
+ this._typescriptTerminal.writeVerboseLine(`Using solution mode`);
245
+ //#region CONFIGURE
246
+ const { duration: configureDurationMs, rawDiagnostics, solutionBuilderHost } = measureTsPerformance('Configure', () => {
247
+ this._overrideTypeScriptReadJson(ts);
248
+ const _tsconfig = this._loadTsconfig(ts);
249
+ this._validateTsconfig(ts, _tsconfig);
250
+ const _rawDiagnostics = [];
251
+ const reportDiagnostic = (diagnostic) => {
252
+ _rawDiagnostics.push(diagnostic);
253
+ };
254
+ // TypeScript doesn't have a
255
+ EmitFilesPatch_1.EmitFilesPatch.install(ts, _tsconfig, this._moduleKindsToEmit);
256
+ const _solutionBuilderHost = this._buildSolutionBuilderHost(ts, reportDiagnostic);
257
+ _solutionBuilderHost.afterProgramEmitAndDiagnostics = (program) => {
258
+ const tsProgram = program.getProgram();
259
+ if (tsProgram) {
260
+ this._configuration.emitChangedFilesCallback(tsProgram);
261
+ }
262
+ };
263
+ return {
264
+ rawDiagnostics: _rawDiagnostics,
265
+ solutionBuilderHost: _solutionBuilderHost
266
+ };
267
+ });
268
+ this._typescriptTerminal.writeVerboseLine(`Configure: ${configureDurationMs}ms`);
269
+ //#endregion
270
+ const solutionBuilder = ts.createSolutionBuilder(solutionBuilderHost, [this._configuration.tsconfigPath], {});
271
+ //#region EMIT
272
+ // Ignoring the exit status because we only care about presence of diagnostics
273
+ solutionBuilder.build();
274
+ //#endregion
275
+ this._logReadPerformance(ts);
276
+ this._logEmitPerformance(ts);
277
+ // Use the native metric since we aren't overwriting the writer
278
+ this._typescriptTerminal.writeVerboseLine(`I/O Write: ${ts.performance.getDuration('I/O Write')}ms (${ts.performance.getCount('beforeIOWrite')} files)`);
279
+ this._logDiagnostics(ts, rawDiagnostics);
280
+ EmitFilesPatch_1.EmitFilesPatch.uninstall(ts);
281
+ }
282
+ _logDiagnostics(ts, rawDiagnostics) {
283
+ const diagnostics = ts.sortAndDeduplicateDiagnostics(rawDiagnostics);
284
+ let typeScriptErrorCount = 0;
285
+ if (diagnostics.length > 0) {
286
+ this._typescriptTerminal.writeLine(`Encountered ${diagnostics.length} TypeScript issue${diagnostics.length > 1 ? 's' : ''}:`);
287
+ for (const diagnostic of diagnostics) {
288
+ const diagnosticCategory = this._getAdjustedDiagnosticCategory(diagnostic, ts);
289
+ if (diagnosticCategory === ts.DiagnosticCategory.Error) {
290
+ typeScriptErrorCount++;
291
+ }
292
+ this._printDiagnosticMessage(ts, diagnostic, diagnosticCategory);
293
+ }
294
+ }
295
+ if (typeScriptErrorCount > 0) {
296
+ throw new Error(`Encountered TypeScript error${typeScriptErrorCount > 1 ? 's' : ''}`);
297
+ }
298
+ }
299
+ _logEmitPerformance(ts) {
300
+ this._typescriptTerminal.writeVerboseLine(`Bind: ${ts.performance.getDuration('Bind')}ms`);
301
+ this._typescriptTerminal.writeVerboseLine(`Check: ${ts.performance.getDuration('Check')}ms`);
302
+ this._typescriptTerminal.writeVerboseLine(`Transform: ${ts.performance.getDuration('transformTime')}ms ` +
303
+ `(${ts.performance.getCount('beforeTransform')} files)`);
304
+ this._typescriptTerminal.writeVerboseLine(`Print: ${ts.performance.getDuration('printTime')}ms ` +
305
+ `(${ts.performance.getCount('beforePrint')} files) (Includes Transform)`);
306
+ this._typescriptTerminal.writeVerboseLine(`Emit: ${ts.performance.getDuration('Emit')}ms (Includes Print)`);
307
+ }
308
+ _logReadPerformance(ts) {
309
+ this._typescriptTerminal.writeVerboseLine(`I/O Read: ${ts.performance.getDuration('I/O Read')}ms (${ts.performance.getCount('beforeIORead')} files)`);
310
+ this._typescriptTerminal.writeVerboseLine(`Parse: ${ts.performance.getDuration('Parse')}ms (${ts.performance.getCount('beforeParse')} files)`);
311
+ this._typescriptTerminal.writeVerboseLine(`Program (includes Read + Parse): ${ts.performance.getDuration('Program')}ms`);
312
+ }
313
+ _printDiagnosticMessage(ts, diagnostic, diagnosticCategory = this._getAdjustedDiagnosticCategory(diagnostic, ts)) {
314
+ // Code taken from reference example
315
+ let diagnosticMessage;
316
+ let errorObject;
317
+ if (diagnostic.file) {
318
+ const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
319
+ const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
320
+ const formattedMessage = `(TS${diagnostic.code}) ${message}`;
321
+ errorObject = new node_core_library_1.FileError(formattedMessage, {
322
+ absolutePath: diagnostic.file.fileName,
323
+ projectFolder: this._configuration.buildFolderPath,
324
+ line: line + 1,
325
+ column: character + 1
326
+ });
327
+ diagnosticMessage = errorObject.toString();
328
+ }
329
+ else {
330
+ diagnosticMessage = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
331
+ errorObject = new Error(diagnosticMessage);
332
+ }
333
+ switch (diagnosticCategory) {
334
+ case ts.DiagnosticCategory.Error: {
335
+ this._typescriptLogger.emitError(errorObject);
336
+ break;
337
+ }
338
+ case ts.DiagnosticCategory.Warning: {
339
+ this._typescriptLogger.emitWarning(errorObject);
340
+ break;
341
+ }
342
+ default: {
343
+ this._typescriptTerminal.writeLine(...diagnosticMessage);
344
+ break;
345
+ }
346
+ }
347
+ }
348
+ _getAdjustedDiagnosticCategory(diagnostic, ts) {
349
+ // Workaround for https://github.com/microsoft/TypeScript/issues/40058
350
+ // The compiler reports a hard error for issues such as this:
351
+ //
352
+ // error TS6133: 'x' is declared but its value is never read.
353
+ //
354
+ // These should properly be treated as warnings, because they are purely cosmetic issues.
355
+ // TODO: Maybe heft should provide a config file for managing DiagnosticCategory mappings.
356
+ if (diagnostic.reportsUnnecessary && diagnostic.category === ts.DiagnosticCategory.Error) {
357
+ return ts.DiagnosticCategory.Warning;
358
+ }
359
+ // These pedantic checks also should not be treated as hard errors
360
+ switch (diagnostic.code) {
361
+ case ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor
362
+ .code:
363
+ case ts.Diagnostics
364
+ .Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1.code:
365
+ return ts.DiagnosticCategory.Warning;
366
+ }
367
+ return diagnostic.category;
368
+ }
369
+ _emit(ts, tsconfig, genericProgram) {
370
+ const filesToWrite = [];
371
+ const changedFiles = new Set();
372
+ EmitFilesPatch_1.EmitFilesPatch.install(ts, tsconfig, this._moduleKindsToEmit, changedFiles);
373
+ const writeFileCallback = (filePath, data) => {
374
+ filesToWrite.push({ filePath, data });
375
+ };
376
+ const result = genericProgram.emit(undefined, // Target source file
377
+ writeFileCallback);
378
+ EmitFilesPatch_1.EmitFilesPatch.uninstall(ts);
379
+ return Object.assign(Object.assign({}, result), { changedSourceFiles: changedFiles, filesToWrite });
380
+ }
381
+ _validateTsconfig(ts, tsconfig) {
382
+ if ((tsconfig.options.module && !tsconfig.options.outDir) ||
383
+ (!tsconfig.options.module && tsconfig.options.outDir)) {
384
+ throw new Error('If either the module or the outDir option is provided in the tsconfig compilerOptions, both must be provided');
385
+ }
386
+ this._moduleKindsToEmit = [];
387
+ const specifiedKinds = new Map();
388
+ const specifiedOutDirs = new Map();
389
+ if (!tsconfig.options.module) {
390
+ throw new Error('If the module tsconfig compilerOption is not provided, the builder must be provided with the ' +
391
+ 'additionalModuleKindsToEmit configuration option.');
392
+ }
393
+ if (this._configuration.emitCjsExtensionForCommonJS) {
394
+ this._addModuleKindToEmit(ts.ModuleKind.CommonJS, tsconfig.options.outDir,
395
+ /* isPrimary */ tsconfig.options.module === ts.ModuleKind.CommonJS, '.cjs');
396
+ const cjsReason = {
397
+ outDir: tsconfig.options.outDir,
398
+ kind: 'CommonJS',
399
+ extension: '.cjs',
400
+ reason: 'emitCjsExtensionForCommonJS'
401
+ };
402
+ specifiedKinds.set(ts.ModuleKind.CommonJS, cjsReason);
403
+ specifiedOutDirs.set(`${tsconfig.options.outDir}:.cjs`, cjsReason);
404
+ }
405
+ if (this._configuration.emitMjsExtensionForESModule) {
406
+ this._addModuleKindToEmit(ts.ModuleKind.ESNext, tsconfig.options.outDir,
407
+ /* isPrimary */ tsconfig.options.module === ts.ModuleKind.ESNext, '.mjs');
408
+ const mjsReason = {
409
+ outDir: tsconfig.options.outDir,
410
+ kind: 'ESNext',
411
+ extension: '.mjs',
412
+ reason: 'emitMjsExtensionForESModule'
413
+ };
414
+ specifiedKinds.set(ts.ModuleKind.ESNext, mjsReason);
415
+ specifiedOutDirs.set(`${tsconfig.options.outDir}:.mjs`, mjsReason);
416
+ }
417
+ if (!specifiedKinds.has(tsconfig.options.module)) {
418
+ this._addModuleKindToEmit(tsconfig.options.module, tsconfig.options.outDir,
419
+ /* isPrimary */ true,
420
+ /* jsExtensionOverride */ undefined);
421
+ const tsConfigReason = {
422
+ outDir: tsconfig.options.outDir,
423
+ kind: ts.ModuleKind[tsconfig.options.module],
424
+ extension: '.js',
425
+ reason: 'tsconfig.json'
426
+ };
427
+ specifiedKinds.set(tsconfig.options.module, tsConfigReason);
428
+ specifiedOutDirs.set(`${tsconfig.options.outDir}:.js`, tsConfigReason);
429
+ }
430
+ if (this._configuration.additionalModuleKindsToEmit) {
431
+ for (const additionalModuleKindToEmit of this._configuration.additionalModuleKindsToEmit) {
432
+ const moduleKind = this._parseModuleKind(ts, additionalModuleKindToEmit.moduleKind);
433
+ const outDirKey = `${additionalModuleKindToEmit.outFolderName}:.js`;
434
+ const moduleKindReason = {
435
+ kind: ts.ModuleKind[moduleKind],
436
+ outDir: additionalModuleKindToEmit.outFolderName,
437
+ extension: '.js',
438
+ reason: `additionalModuleKindsToEmit`
439
+ };
440
+ const existingKind = specifiedKinds.get(moduleKind);
441
+ const existingDir = specifiedOutDirs.get(outDirKey);
442
+ if (existingKind) {
443
+ throw new Error(`Module kind "${additionalModuleKindToEmit.moduleKind}" is already emitted at ${existingKind.outDir} with extension '${existingKind.extension}' by option ${existingKind.reason}.`);
444
+ }
445
+ else if (existingDir) {
446
+ throw new Error(`Output folder "${additionalModuleKindToEmit.outFolderName}" already contains module kind ${existingDir.kind} with extension '${existingDir.extension}', specified by option ${existingDir.reason}.`);
447
+ }
448
+ else {
449
+ const outFolderKey = this._addModuleKindToEmit(moduleKind, additionalModuleKindToEmit.outFolderName,
450
+ /* isPrimary */ false, undefined);
451
+ if (outFolderKey) {
452
+ specifiedKinds.set(moduleKind, moduleKindReason);
453
+ specifiedOutDirs.set(outFolderKey, moduleKindReason);
454
+ }
455
+ }
456
+ }
457
+ }
458
+ }
459
+ _addModuleKindToEmit(moduleKind, outFolderPath, isPrimary, jsExtensionOverride) {
460
+ let outFolderName;
461
+ if (path.isAbsolute(outFolderPath)) {
462
+ outFolderName = path.relative(this._configuration.buildFolderPath, outFolderPath);
463
+ }
464
+ else {
465
+ outFolderName = outFolderPath;
466
+ outFolderPath = path.resolve(this._configuration.buildFolderPath, outFolderPath);
467
+ }
468
+ outFolderPath = node_core_library_1.Path.convertToSlashes(outFolderPath);
469
+ outFolderPath = outFolderPath.replace(/\/*$/, '/'); // Ensure the outFolderPath ends with a slash
470
+ for (const existingModuleKindToEmit of this._moduleKindsToEmit) {
471
+ let errorText;
472
+ if (existingModuleKindToEmit.outFolderPath === outFolderPath) {
473
+ if (existingModuleKindToEmit.jsExtensionOverride === jsExtensionOverride) {
474
+ errorText =
475
+ 'Unable to output two different module kinds with the same ' +
476
+ `module extension (${jsExtensionOverride || '.js'}) to the same ` +
477
+ `folder ("${outFolderPath}").`;
478
+ }
479
+ }
480
+ else {
481
+ let parentFolder;
482
+ let childFolder;
483
+ if (outFolderPath.startsWith(existingModuleKindToEmit.outFolderPath)) {
484
+ parentFolder = outFolderPath;
485
+ childFolder = existingModuleKindToEmit.outFolderPath;
486
+ }
487
+ else if (existingModuleKindToEmit.outFolderPath.startsWith(outFolderPath)) {
488
+ parentFolder = existingModuleKindToEmit.outFolderPath;
489
+ childFolder = outFolderPath;
490
+ }
491
+ if (parentFolder) {
492
+ errorText =
493
+ 'Unable to output two different module kinds to nested folders ' +
494
+ `("${parentFolder}" and "${childFolder}").`;
495
+ }
496
+ }
497
+ if (errorText) {
498
+ this._typescriptLogger.emitError(new Error(errorText));
499
+ return undefined;
500
+ }
501
+ }
502
+ this._moduleKindsToEmit.push({
503
+ outFolderPath,
504
+ moduleKind,
505
+ jsExtensionOverride,
506
+ isPrimary
507
+ });
508
+ return `${outFolderName}:${jsExtensionOverride || '.js'}`;
509
+ }
510
+ _loadTsconfig(ts) {
511
+ const parsedConfigFile = ts.readConfigFile(this._configuration.tsconfigPath, this._cachedFileSystem.readFile);
512
+ const currentFolder = path.dirname(this._configuration.tsconfigPath);
513
+ const tsconfig = ts.parseJsonConfigFileContent(parsedConfigFile.config, {
514
+ fileExists: this._cachedFileSystem.exists,
515
+ readFile: this._cachedFileSystem.readFile,
516
+ readDirectory: (folderPath, extensions, excludes, includes, depth) => ts.matchFiles(folderPath, extensions, excludes, includes,
517
+ /* useCaseSensitiveFileNames */ true, currentFolder, depth, this._cachedFileSystem.readFolderFilesAndDirectories.bind(this._cachedFileSystem), this._cachedFileSystem.getRealPath.bind(this._cachedFileSystem), this._cachedFileSystem.directoryExists.bind(this._cachedFileSystem)),
518
+ useCaseSensitiveFileNames: true
519
+ }, currentFolder,
520
+ /*existingOptions:*/ undefined, this._configuration.tsconfigPath);
521
+ if (tsconfig.options.incremental) {
522
+ tsconfig.options.tsBuildInfoFile = this._tsCacheFilePath;
523
+ }
524
+ return tsconfig;
525
+ }
526
+ _buildSolutionBuilderHost(ts, reportDiagnostic) {
527
+ const reportSolutionBuilderStatus = reportDiagnostic;
528
+ const reportEmitErrorSummary = (errorCount) => {
529
+ // Do nothing
530
+ };
531
+ const compilerHost = ts.createSolutionBuilderHost(this._getCachingTypeScriptSystem(ts), ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus, reportEmitErrorSummary);
532
+ return compilerHost;
533
+ }
534
+ _buildIncrementalCompilerHost(ts, tsconfig) {
535
+ if (tsconfig.options.incremental) {
536
+ return ts.createIncrementalCompilerHost(tsconfig.options, this._getCachingTypeScriptSystem(ts));
537
+ }
538
+ else {
539
+ return ts.createCompilerHost(tsconfig.options);
540
+ }
541
+ }
542
+ _getCachingTypeScriptSystem(ts) {
543
+ const sys = Object.assign(Object.assign({}, ts.sys), { deleteFile: this._cachedFileSystem.deleteFile.bind(this._cachedFileSystem),
544
+ /** Check if the path exists and is a directory */
545
+ directoryExists: (directoryPath) => {
546
+ try {
547
+ const stats = this._cachedFileSystem.getStatistics(directoryPath);
548
+ return stats.isDirectory() || stats.isSymbolicLink();
549
+ }
550
+ catch (error) {
551
+ if (node_core_library_1.FileSystem.isNotExistError(error)) {
552
+ return false;
553
+ }
554
+ else {
555
+ throw error;
556
+ }
557
+ }
558
+ },
559
+ /** Check if the path exists and is a file */
560
+ fileExists: (filePath) => {
561
+ try {
562
+ const stats = this._cachedFileSystem.getStatistics(filePath);
563
+ return stats.isFile();
564
+ }
565
+ catch (error) {
566
+ if (node_core_library_1.FileSystem.isNotExistError(error)) {
567
+ return false;
568
+ }
569
+ else {
570
+ throw error;
571
+ }
572
+ }
573
+ },
574
+ /* Use the Heft config's build folder because it has corrected casing */
575
+ getCurrentDirectory: () => this._configuration.buildFolderPath, getDirectories: (folderPath) => {
576
+ return this._cachedFileSystem.readFolderFilesAndDirectories(folderPath).directories;
577
+ }, realpath: this._cachedFileSystem.getRealPath.bind(this._cachedFileSystem) });
578
+ return sys;
579
+ }
580
+ // private _buildWatchCompilerHost(
581
+ // ts: ExtendedTypeScript,
582
+ // tsconfig: TTypescript.ParsedCommandLine
583
+ // ): TWatchCompilerHost {
584
+ // const reportDiagnostic: TTypescript.DiagnosticReporter = (diagnostic: TTypescript.Diagnostic): void => {
585
+ // this._printDiagnosticMessage(ts, diagnostic);
586
+ // };
587
+ // const reportWatchStatus: TTypescript.DiagnosticReporter = (diagnostic: TTypescript.Diagnostic) => {
588
+ // this._printDiagnosticMessage(ts, diagnostic);
589
+ // // In watch mode, notify EmitCompletedCallbackManager every time we finish recompiling.
590
+ // if (
591
+ // diagnostic.code === ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code ||
592
+ // diagnostic.code === ts.Diagnostics.Found_1_error_Watching_for_file_changes.code
593
+ // ) {
594
+ // this._emitCompletedCallbackManager.callback();
595
+ // }
596
+ // };
597
+ // return ts.createWatchCompilerHost(
598
+ // tsconfig.fileNames,
599
+ // tsconfig.options,
600
+ // this._getCachingTypeScriptSystem(ts),
601
+ // ts.createEmitAndSemanticDiagnosticsBuilderProgram,
602
+ // reportDiagnostic,
603
+ // reportWatchStatus,
604
+ // tsconfig.projectReferences
605
+ // );
606
+ // }
607
+ // private _buildWatchSolutionBuilderHost(ts: ExtendedTypeScript): TWatchSolutionHost {
608
+ // const reportDiagnostic: TTypescript.DiagnosticReporter = (diagnostic: TTypescript.Diagnostic): void => {
609
+ // this._printDiagnosticMessage(ts, diagnostic);
610
+ // };
611
+ // const reportSolutionBuilderStatus: TTypescript.DiagnosticReporter = reportDiagnostic;
612
+ // const reportWatchStatus: TTypescript.DiagnosticReporter = (diagnostic: TTypescript.Diagnostic) => {
613
+ // this._printDiagnosticMessage(ts, diagnostic);
614
+ // // In watch mode, notify EmitCompletedCallbackManager every time we finish recompiling.
615
+ // if (
616
+ // diagnostic.code === ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code ||
617
+ // diagnostic.code === ts.Diagnostics.Found_1_error_Watching_for_file_changes.code
618
+ // ) {
619
+ // this._emitCompletedCallbackManager.callback();
620
+ // }
621
+ // };
622
+ // return ts.createSolutionBuilderWithWatchHost(
623
+ // this._getCachingTypeScriptSystem(ts),
624
+ // ts.createEmitAndSemanticDiagnosticsBuilderProgram,
625
+ // reportDiagnostic,
626
+ // reportSolutionBuilderStatus,
627
+ // reportWatchStatus
628
+ // );
629
+ // }
630
+ _overrideTypeScriptReadJson(ts) {
631
+ const cachedReadJson = (filePath) => {
632
+ let jsonData = this._tsReadJsonCache.get(filePath);
633
+ if (jsonData) {
634
+ return jsonData;
635
+ }
636
+ else {
637
+ try {
638
+ const fileContents = this._cachedFileSystem.readFile(filePath);
639
+ if (!fileContents) {
640
+ jsonData = EMPTY_JSON;
641
+ }
642
+ else {
643
+ const parsedFile = ts.parseConfigFileTextToJson(filePath, fileContents);
644
+ if (parsedFile.error) {
645
+ jsonData = EMPTY_JSON;
646
+ }
647
+ else {
648
+ jsonData = parsedFile.config;
649
+ }
650
+ }
651
+ }
652
+ catch (error) {
653
+ jsonData = EMPTY_JSON;
654
+ }
655
+ this._tsReadJsonCache.set(filePath, jsonData);
656
+ return jsonData;
657
+ }
658
+ };
659
+ ts.readJson = cachedReadJson;
660
+ }
661
+ _parseModuleKind(ts, moduleKindName) {
662
+ switch (moduleKindName.toLowerCase()) {
663
+ case 'commonjs':
664
+ return ts.ModuleKind.CommonJS;
665
+ case 'amd':
666
+ return ts.ModuleKind.AMD;
667
+ case 'umd':
668
+ return ts.ModuleKind.UMD;
669
+ case 'system':
670
+ return ts.ModuleKind.System;
671
+ case 'es2015':
672
+ return ts.ModuleKind.ES2015;
673
+ case 'esnext':
674
+ return ts.ModuleKind.ESNext;
675
+ default:
676
+ throw new Error(`"${moduleKindName}" is not a valid module kind name.`);
677
+ }
678
+ }
679
+ }
680
+ exports.TypeScriptBuilder = TypeScriptBuilder;
681
+ //# sourceMappingURL=TypeScriptBuilder.js.map