@rushstack/heft-typescript-plugin 0.0.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 (44) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +12 -0
  3. package/dist/heft-typescript-plugin.d.ts +110 -0
  4. package/dist/tsdoc-metadata.json +11 -0
  5. package/heft-plugin.json +10 -0
  6. package/lib/Performance.d.ts +7 -0
  7. package/lib/Performance.d.ts.map +1 -0
  8. package/lib/Performance.js +5 -0
  9. package/lib/Performance.js.map +1 -0
  10. package/lib/TranspilerWorker.d.ts +2 -0
  11. package/lib/TranspilerWorker.d.ts.map +1 -0
  12. package/lib/TranspilerWorker.js +85 -0
  13. package/lib/TranspilerWorker.js.map +1 -0
  14. package/lib/TypeScriptBuilder.d.ts +96 -0
  15. package/lib/TypeScriptBuilder.d.ts.map +1 -0
  16. package/lib/TypeScriptBuilder.js +790 -0
  17. package/lib/TypeScriptBuilder.js.map +1 -0
  18. package/lib/TypeScriptPlugin.d.ts +100 -0
  19. package/lib/TypeScriptPlugin.d.ts.map +1 -0
  20. package/lib/TypeScriptPlugin.js +219 -0
  21. package/lib/TypeScriptPlugin.js.map +1 -0
  22. package/lib/configureProgramForMultiEmit.d.ts +7 -0
  23. package/lib/configureProgramForMultiEmit.d.ts.map +1 -0
  24. package/lib/configureProgramForMultiEmit.js +99 -0
  25. package/lib/configureProgramForMultiEmit.js.map +1 -0
  26. package/lib/fileSystem/TypeScriptCachedFileSystem.d.ts +36 -0
  27. package/lib/fileSystem/TypeScriptCachedFileSystem.d.ts.map +1 -0
  28. package/lib/fileSystem/TypeScriptCachedFileSystem.js +163 -0
  29. package/lib/fileSystem/TypeScriptCachedFileSystem.js.map +1 -0
  30. package/lib/index.d.ts +8 -0
  31. package/lib/index.d.ts.map +1 -0
  32. package/lib/index.js +10 -0
  33. package/lib/index.js.map +1 -0
  34. package/lib/internalTypings/TypeScriptInternals.d.ts +56 -0
  35. package/lib/internalTypings/TypeScriptInternals.d.ts.map +1 -0
  36. package/lib/internalTypings/TypeScriptInternals.js +5 -0
  37. package/lib/internalTypings/TypeScriptInternals.js.map +1 -0
  38. package/lib/schemas/anything.schema.json +28 -0
  39. package/lib/schemas/typescript.schema.json +101 -0
  40. package/lib/types.d.ts +54 -0
  41. package/lib/types.d.ts.map +1 -0
  42. package/lib/types.js +3 -0
  43. package/lib/types.js.map +1 -0
  44. package/package.json +39 -0
@@ -0,0 +1,790 @@
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 worker_threads_1 = require("worker_threads");
32
+ const semver = __importStar(require("semver"));
33
+ const node_core_library_1 = require("@rushstack/node-core-library");
34
+ const configureProgramForMultiEmit_1 = require("./configureProgramForMultiEmit");
35
+ const OLDEST_SUPPORTED_TS_MAJOR_VERSION = 2;
36
+ const OLDEST_SUPPORTED_TS_MINOR_VERSION = 9;
37
+ const NEWEST_SUPPORTED_TS_MAJOR_VERSION = 5;
38
+ const NEWEST_SUPPORTED_TS_MINOR_VERSION = 0;
39
+ class TypeScriptBuilder {
40
+ get _tsCacheFilePath() {
41
+ if (!this.__tsCacheFilePath) {
42
+ // TypeScript internally handles if the tsconfig options have changed from when the tsbuildinfo file was created.
43
+ // We only need to hash our additional Heft configuration.
44
+ const configHash = crypto.createHash('sha1');
45
+ configHash.update(JSON.stringify(this._configuration.additionalModuleKindsToEmit || {}));
46
+ const serializedConfigHash = configHash
47
+ .digest('base64')
48
+ .slice(0, 8)
49
+ .replace(/\+/g, '-')
50
+ .replace(/\//g, '_');
51
+ // This conversion is theoretically redundant, but it is here to make absolutely sure that the path is formatted
52
+ // using only '/' as the directory separator so that incremental builds don't break on Windows.
53
+ // TypeScript will normalize to '/' when serializing, but not on the direct input, and uses exact string equality.
54
+ const normalizedCacheFolderPath = node_core_library_1.Path.convertToSlashes(this._configuration.buildMetadataFolderPath);
55
+ this.__tsCacheFilePath = `${normalizedCacheFolderPath}/ts_${serializedConfigHash}.json`;
56
+ }
57
+ return this.__tsCacheFilePath;
58
+ }
59
+ constructor(configuration) {
60
+ this._suppressedDiagnosticCodes = new Set();
61
+ this._tool = undefined;
62
+ this._nextRequestId = 0;
63
+ this._configuration = configuration;
64
+ this._typescriptLogger = configuration.scopedLogger;
65
+ this._typescriptTerminal = configuration.scopedLogger.terminal;
66
+ }
67
+ async invokeAsync(onChangeDetected) {
68
+ var _a, _b;
69
+ if (!this._tool) {
70
+ // Determine the compiler version
71
+ const compilerPackageJsonFilename = path.join(this._configuration.typeScriptToolPath, 'package.json');
72
+ const packageJson = await node_core_library_1.JsonFile.loadAsync(compilerPackageJsonFilename);
73
+ this._typescriptVersion = packageJson.version;
74
+ const parsedVersion = semver.parse(this._typescriptVersion);
75
+ if (!parsedVersion) {
76
+ throw new Error(`Unable to parse version "${this._typescriptVersion}" for TypeScript compiler package in: ` +
77
+ compilerPackageJsonFilename);
78
+ }
79
+ this._typescriptParsedVersion = parsedVersion;
80
+ // Detect what features this compiler supports. Note that manually comparing major/minor numbers
81
+ // loosens the matching to accept prereleases such as "3.6.0-dev.20190530"
82
+ this._capabilities = {
83
+ incrementalProgram: false,
84
+ solutionBuilder: this._typescriptParsedVersion.major >= 3
85
+ };
86
+ if (this._typescriptParsedVersion.major > 3 ||
87
+ (this._typescriptParsedVersion.major === 3 && this._typescriptParsedVersion.minor >= 6)) {
88
+ this._capabilities.incrementalProgram = true;
89
+ }
90
+ this._useSolutionBuilder = !!this._configuration.buildProjectReferences;
91
+ if (this._useSolutionBuilder && !this._capabilities.solutionBuilder) {
92
+ throw new Error(`Building project references requires TypeScript@>=3.0, but the current version is ${this._typescriptVersion}`);
93
+ }
94
+ // Report a warning if the TypeScript version is too old/new. The current oldest supported version is
95
+ // TypeScript 2.9. Prior to that the "ts.getConfigFileParsingDiagnostics()" API is missing; more fixups
96
+ // would be required to deal with that. We won't do that work unless someone requests it.
97
+ if (this._typescriptParsedVersion.major < OLDEST_SUPPORTED_TS_MAJOR_VERSION ||
98
+ (this._typescriptParsedVersion.major === OLDEST_SUPPORTED_TS_MAJOR_VERSION &&
99
+ this._typescriptParsedVersion.minor < OLDEST_SUPPORTED_TS_MINOR_VERSION)) {
100
+ // We don't use writeWarningLine() here because, if the person wants to take their chances with
101
+ // a seemingly unsupported compiler, their build should be allowed to succeed.
102
+ this._typescriptTerminal.writeLine(`The TypeScript compiler version ${this._typescriptVersion} is very old` +
103
+ ` and has not been tested with Heft; it may not work correctly.`);
104
+ }
105
+ else if (this._typescriptParsedVersion.major > NEWEST_SUPPORTED_TS_MAJOR_VERSION ||
106
+ (this._typescriptParsedVersion.major === NEWEST_SUPPORTED_TS_MAJOR_VERSION &&
107
+ this._typescriptParsedVersion.minor > NEWEST_SUPPORTED_TS_MINOR_VERSION)) {
108
+ this._typescriptTerminal.writeLine(`The TypeScript compiler version ${this._typescriptVersion} is newer` +
109
+ ' than the latest version that was tested with Heft ' +
110
+ `(${NEWEST_SUPPORTED_TS_MAJOR_VERSION}.${NEWEST_SUPPORTED_TS_MINOR_VERSION}); it may not work correctly.`);
111
+ }
112
+ const ts = require(this._configuration.typeScriptToolPath);
113
+ ts.performance.enable();
114
+ const suppressedCodes = [
115
+ (_a = ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor) === null || _a === void 0 ? void 0 : _a.code,
116
+ // This diagnostic code is not present in old versions of TypeScript
117
+ (_b = ts.Diagnostics
118
+ .Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1) === null || _b === void 0 ? void 0 : _b.code
119
+ ];
120
+ for (const code of suppressedCodes) {
121
+ if (code !== undefined) {
122
+ this._suppressedDiagnosticCodes.add(code);
123
+ }
124
+ }
125
+ const measureTsPerformance = (measurementName, fn) => {
126
+ const beforeName = `before${measurementName}`;
127
+ ts.performance.mark(beforeName);
128
+ const result = fn();
129
+ const afterName = `after${measurementName}`;
130
+ ts.performance.mark(afterName);
131
+ ts.performance.measure(measurementName, beforeName, afterName);
132
+ return Object.assign(Object.assign({}, result), { duration: ts.performance.getDuration(measurementName), count: ts.performance.getCount(beforeName) });
133
+ };
134
+ this._typescriptTerminal.writeLine(`Using TypeScript version ${ts.version}`);
135
+ const rawDiagnostics = [];
136
+ const pendingOperations = new Set();
137
+ this._tool = {
138
+ ts,
139
+ measureSync: measureTsPerformance,
140
+ sourceFileCache: new Map(),
141
+ watchProgram: undefined,
142
+ solutionBuilder: undefined,
143
+ rawDiagnostics,
144
+ pendingOperations,
145
+ executing: false,
146
+ reportDiagnostic: (diagnostic) => {
147
+ rawDiagnostics.push(diagnostic);
148
+ },
149
+ clearTimeout(timeout) {
150
+ pendingOperations.delete(timeout);
151
+ },
152
+ setTimeout(fn, ms, ...args) {
153
+ const timeout = () => {
154
+ fn(...args);
155
+ };
156
+ pendingOperations.add(timeout);
157
+ if (!this.executing && onChangeDetected) {
158
+ onChangeDetected();
159
+ }
160
+ return timeout;
161
+ },
162
+ worker: undefined,
163
+ pendingTranspilePromises: new Map(),
164
+ pendingTranspileSignals: new Map()
165
+ };
166
+ }
167
+ const { performance } = this._tool.ts;
168
+ // Reset the performance counters to 0 to avoid contamination from previous runs
169
+ performance.disable();
170
+ performance.enable();
171
+ if (onChangeDetected !== undefined) {
172
+ await this._runWatchAsync(this._tool);
173
+ }
174
+ else if (this._useSolutionBuilder) {
175
+ await this._runSolutionBuildAsync(this._tool);
176
+ }
177
+ else {
178
+ await this._runBuildAsync(this._tool);
179
+ }
180
+ }
181
+ async _runWatchAsync(tool) {
182
+ const { ts, measureSync: measureTsPerformance, pendingOperations, rawDiagnostics, pendingTranspilePromises } = tool;
183
+ if (!tool.solutionBuilder && !tool.watchProgram) {
184
+ //#region CONFIGURE
185
+ const { duration: configureDurationMs, tsconfig } = measureTsPerformance('Configure', () => {
186
+ const _tsconfig = this._loadTsconfig(ts);
187
+ this._validateTsconfig(ts, _tsconfig);
188
+ return {
189
+ tsconfig: _tsconfig
190
+ };
191
+ });
192
+ this._typescriptTerminal.writeVerboseLine(`Configure: ${configureDurationMs}ms`);
193
+ //#endregion
194
+ if (this._useSolutionBuilder) {
195
+ const solutionHost = this._buildWatchSolutionBuilderHost(tool);
196
+ const builder = ts.createSolutionBuilderWithWatch(solutionHost, [this._configuration.tsconfigPath], {});
197
+ tool.solutionBuilder = builder;
198
+ builder.build();
199
+ }
200
+ else {
201
+ const compilerHost = this._buildWatchCompilerHost(tool, tsconfig);
202
+ tool.watchProgram = ts.createWatchProgram(compilerHost);
203
+ }
204
+ }
205
+ if (pendingOperations.size > 0) {
206
+ rawDiagnostics.length = 0;
207
+ tool.executing = true;
208
+ for (const operation of pendingOperations) {
209
+ pendingOperations.delete(operation);
210
+ operation();
211
+ }
212
+ if (pendingTranspilePromises.size) {
213
+ const emitResults = await Promise.all(pendingTranspilePromises.values());
214
+ for (const { diagnostics } of emitResults) {
215
+ for (const diagnostic of diagnostics) {
216
+ rawDiagnostics.push(diagnostic);
217
+ }
218
+ }
219
+ }
220
+ // eslint-disable-next-line require-atomic-updates
221
+ tool.executing = false;
222
+ }
223
+ this._logDiagnostics(ts, rawDiagnostics);
224
+ }
225
+ async _runBuildAsync(tool) {
226
+ const { ts, measureSync: measureTsPerformance, pendingTranspilePromises } = tool;
227
+ //#region CONFIGURE
228
+ const { duration: configureDurationMs, tsconfig, compilerHost } = measureTsPerformance('Configure', () => {
229
+ const _tsconfig = this._loadTsconfig(ts);
230
+ this._validateTsconfig(ts, _tsconfig);
231
+ const _compilerHost = this._buildIncrementalCompilerHost(tool, _tsconfig);
232
+ return {
233
+ tsconfig: _tsconfig,
234
+ compilerHost: _compilerHost
235
+ };
236
+ });
237
+ this._typescriptTerminal.writeVerboseLine(`Configure: ${configureDurationMs}ms`);
238
+ //#endregion
239
+ //#region PROGRAM
240
+ // There will be only one program here; emit will get a bit abused if we produce multiple outputs
241
+ let builderProgram = undefined;
242
+ let innerProgram;
243
+ const isolatedModules = !!this._configuration.useTranspilerWorker && !!tsconfig.options.isolatedModules;
244
+ const mode = isolatedModules ? 'declaration' : 'both';
245
+ let filesToTranspile;
246
+ if (tsconfig.options.incremental) {
247
+ // Use ts.createEmitAndSemanticDiagnositcsBuilderProgram directly because the customizations performed by
248
+ // _getCreateBuilderProgram duplicate those performed in this function for non-incremental build.
249
+ const oldProgram = ts.readBuilderProgram(tsconfig.options, compilerHost);
250
+ builderProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram(tsconfig.fileNames, tsconfig.options, compilerHost, oldProgram, ts.getConfigFileParsingDiagnostics(tsconfig), tsconfig.projectReferences);
251
+ filesToTranspile = getFilesToTranspileFromBuilderProgram(builderProgram);
252
+ innerProgram = builderProgram.getProgram();
253
+ }
254
+ else {
255
+ innerProgram = ts.createProgram({
256
+ rootNames: tsconfig.fileNames,
257
+ options: tsconfig.options,
258
+ projectReferences: tsconfig.projectReferences,
259
+ host: compilerHost,
260
+ oldProgram: undefined,
261
+ configFileParsingDiagnostics: ts.getConfigFileParsingDiagnostics(tsconfig)
262
+ });
263
+ filesToTranspile = getFilesToTranspileFromProgram(innerProgram);
264
+ }
265
+ // Prefer the builder program, since it is what gives us incremental builds
266
+ const genericProgram = builderProgram || innerProgram;
267
+ this._logReadPerformance(ts);
268
+ //#endregion
269
+ if (isolatedModules) {
270
+ // Kick the transpilation worker.
271
+ this._queueTranspileInWorker(tool, genericProgram.getCompilerOptions(), filesToTranspile);
272
+ }
273
+ //#region ANALYSIS
274
+ const { duration: diagnosticsDurationMs, diagnostics: preDiagnostics } = measureTsPerformance('Analyze', () => {
275
+ const rawDiagnostics = [
276
+ ...genericProgram.getConfigFileParsingDiagnostics(),
277
+ ...genericProgram.getOptionsDiagnostics(),
278
+ ...genericProgram.getSyntacticDiagnostics(),
279
+ ...genericProgram.getGlobalDiagnostics(),
280
+ ...genericProgram.getSemanticDiagnostics()
281
+ ];
282
+ return { diagnostics: rawDiagnostics };
283
+ });
284
+ this._typescriptTerminal.writeVerboseLine(`Analyze: ${diagnosticsDurationMs}ms`);
285
+ //#endregion
286
+ //#region EMIT
287
+ const { changedFiles } = (0, configureProgramForMultiEmit_1.configureProgramForMultiEmit)(innerProgram, ts, this._moduleKindsToEmit, mode);
288
+ const emitResult = genericProgram.emit(undefined,
289
+ // The writeFile callback must be provided for the multi-emit redirector
290
+ ts.sys.writeFile, undefined, undefined, undefined);
291
+ this._cleanupWorker();
292
+ //#endregion
293
+ this._logEmitPerformance(ts);
294
+ //#region FINAL_ANALYSIS
295
+ // Need to ensure that we include emit diagnostics, since they might not be part of the other sets
296
+ const rawDiagnostics = [...preDiagnostics, ...emitResult.diagnostics];
297
+ //#endregion
298
+ this._configuration.emitChangedFilesCallback(innerProgram, changedFiles);
299
+ if (pendingTranspilePromises.size) {
300
+ const emitResults = await Promise.all(pendingTranspilePromises.values());
301
+ for (const { diagnostics } of emitResults) {
302
+ for (const diagnostic of diagnostics) {
303
+ rawDiagnostics.push(diagnostic);
304
+ }
305
+ }
306
+ }
307
+ this._logDiagnostics(ts, rawDiagnostics);
308
+ // Reset performance counters in case any are used in the callback
309
+ ts.performance.disable();
310
+ ts.performance.enable();
311
+ }
312
+ async _runSolutionBuildAsync(tool) {
313
+ this._typescriptTerminal.writeVerboseLine(`Using solution mode`);
314
+ const { ts, measureSync, rawDiagnostics, pendingTranspilePromises } = tool;
315
+ rawDiagnostics.length = 0;
316
+ if (!tool.solutionBuilder) {
317
+ //#region CONFIGURE
318
+ const { duration: configureDurationMs, solutionBuilderHost } = measureSync('Configure', () => {
319
+ const _tsconfig = this._loadTsconfig(ts);
320
+ this._validateTsconfig(ts, _tsconfig);
321
+ const _solutionBuilderHost = this._buildSolutionBuilderHost(tool);
322
+ return {
323
+ solutionBuilderHost: _solutionBuilderHost
324
+ };
325
+ });
326
+ this._typescriptTerminal.writeVerboseLine(`Configure: ${configureDurationMs}ms`);
327
+ //#endregion
328
+ tool.solutionBuilder = ts.createSolutionBuilder(solutionBuilderHost, [this._configuration.tsconfigPath], {});
329
+ }
330
+ else {
331
+ // Force reload everything from disk
332
+ for (const project of tool.solutionBuilder.getBuildOrder()) {
333
+ tool.solutionBuilder.invalidateProject(project, 1);
334
+ }
335
+ }
336
+ //#region EMIT
337
+ // Ignoring the exit status because we only care about presence of diagnostics
338
+ tool.solutionBuilder.build();
339
+ this._cleanupWorker();
340
+ //#endregion
341
+ if (pendingTranspilePromises.size) {
342
+ const emitResults = await Promise.all(pendingTranspilePromises.values());
343
+ for (const { diagnostics } of emitResults) {
344
+ for (const diagnostic of diagnostics) {
345
+ rawDiagnostics.push(diagnostic);
346
+ }
347
+ }
348
+ }
349
+ this._logDiagnostics(ts, rawDiagnostics);
350
+ }
351
+ _logDiagnostics(ts, rawDiagnostics) {
352
+ const diagnostics = ts.sortAndDeduplicateDiagnostics(rawDiagnostics);
353
+ if (diagnostics.length > 0) {
354
+ this._typescriptTerminal.writeLine(`Encountered ${diagnostics.length} TypeScript issue${diagnostics.length > 1 ? 's' : ''}:`);
355
+ for (const diagnostic of diagnostics) {
356
+ const diagnosticCategory = this._getAdjustedDiagnosticCategory(diagnostic, ts);
357
+ this._printDiagnosticMessage(ts, diagnostic, diagnosticCategory);
358
+ }
359
+ }
360
+ }
361
+ _logEmitPerformance(ts) {
362
+ this._typescriptTerminal.writeVerboseLine(`Bind: ${ts.performance.getDuration('Bind')}ms`);
363
+ this._typescriptTerminal.writeVerboseLine(`Check: ${ts.performance.getDuration('Check')}ms`);
364
+ this._typescriptTerminal.writeVerboseLine(`Transform: ${ts.performance.getDuration('transformTime')}ms ` +
365
+ `(${ts.performance.getCount('beforeTransform')} files)`);
366
+ this._typescriptTerminal.writeVerboseLine(`Print: ${ts.performance.getDuration('printTime')}ms ` +
367
+ `(${ts.performance.getCount('beforePrint')} files) (Includes Transform)`);
368
+ this._typescriptTerminal.writeVerboseLine(`Emit: ${ts.performance.getDuration('Emit')}ms (Includes Print)`);
369
+ this._typescriptTerminal.writeVerboseLine(`I/O Write: ${ts.performance.getDuration('I/O Write')}ms (${ts.performance.getCount('beforeIOWrite')} files)`);
370
+ }
371
+ _logReadPerformance(ts) {
372
+ this._typescriptTerminal.writeVerboseLine(`I/O Read: ${ts.performance.getDuration('I/O Read')}ms (${ts.performance.getCount('beforeIORead')} files)`);
373
+ this._typescriptTerminal.writeVerboseLine(`Parse: ${ts.performance.getDuration('Parse')}ms (${ts.performance.getCount('beforeParse')} files)`);
374
+ this._typescriptTerminal.writeVerboseLine(`Program (includes Read + Parse): ${ts.performance.getDuration('Program')}ms`);
375
+ }
376
+ _printDiagnosticMessage(ts, diagnostic, diagnosticCategory = this._getAdjustedDiagnosticCategory(diagnostic, ts)) {
377
+ // Code taken from reference example
378
+ let diagnosticMessage;
379
+ let errorObject;
380
+ if (diagnostic.file) {
381
+ const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
382
+ const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
383
+ const formattedMessage = `(TS${diagnostic.code}) ${message}`;
384
+ errorObject = new node_core_library_1.FileError(formattedMessage, {
385
+ absolutePath: diagnostic.file.fileName,
386
+ projectFolder: this._configuration.buildFolderPath,
387
+ line: line + 1,
388
+ column: character + 1
389
+ });
390
+ diagnosticMessage = errorObject.toString();
391
+ }
392
+ else {
393
+ diagnosticMessage = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
394
+ errorObject = new Error(diagnosticMessage);
395
+ }
396
+ switch (diagnosticCategory) {
397
+ case ts.DiagnosticCategory.Error: {
398
+ this._typescriptLogger.emitError(errorObject);
399
+ break;
400
+ }
401
+ case ts.DiagnosticCategory.Warning: {
402
+ this._typescriptLogger.emitWarning(errorObject);
403
+ break;
404
+ }
405
+ default: {
406
+ this._typescriptTerminal.writeLine(...diagnosticMessage);
407
+ break;
408
+ }
409
+ }
410
+ }
411
+ _getAdjustedDiagnosticCategory(diagnostic, ts) {
412
+ // Workaround for https://github.com/microsoft/TypeScript/issues/40058
413
+ // The compiler reports a hard error for issues such as this:
414
+ //
415
+ // error TS6133: 'x' is declared but its value is never read.
416
+ //
417
+ // These should properly be treated as warnings, because they are purely cosmetic issues.
418
+ // TODO: Maybe heft should provide a config file for managing DiagnosticCategory mappings.
419
+ if (diagnostic.reportsUnnecessary && diagnostic.category === ts.DiagnosticCategory.Error) {
420
+ return ts.DiagnosticCategory.Warning;
421
+ }
422
+ // These pedantic checks also should not be treated as hard errors
423
+ if (this._suppressedDiagnosticCodes.has(diagnostic.code)) {
424
+ return ts.DiagnosticCategory.Warning;
425
+ }
426
+ return diagnostic.category;
427
+ }
428
+ _validateTsconfig(ts, tsconfig) {
429
+ if ((tsconfig.options.module && !tsconfig.options.outDir) ||
430
+ (!tsconfig.options.module && tsconfig.options.outDir)) {
431
+ throw new Error('If either the module or the outDir option is provided in the tsconfig compilerOptions, both must be provided');
432
+ }
433
+ this._moduleKindsToEmit = [];
434
+ const specifiedKinds = new Map();
435
+ const specifiedOutDirs = new Map();
436
+ if (!tsconfig.options.module) {
437
+ throw new Error('If the module tsconfig compilerOption is not provided, the builder must be provided with the ' +
438
+ 'additionalModuleKindsToEmit configuration option.');
439
+ }
440
+ if (this._configuration.emitCjsExtensionForCommonJS) {
441
+ this._addModuleKindToEmit(ts.ModuleKind.CommonJS, tsconfig.options.outDir,
442
+ /* isPrimary */ tsconfig.options.module === ts.ModuleKind.CommonJS, '.cjs');
443
+ const cjsReason = {
444
+ outDir: tsconfig.options.outDir,
445
+ kind: 'CommonJS',
446
+ extension: '.cjs',
447
+ reason: 'emitCjsExtensionForCommonJS'
448
+ };
449
+ specifiedKinds.set(ts.ModuleKind.CommonJS, cjsReason);
450
+ specifiedOutDirs.set(`${tsconfig.options.outDir}:.cjs`, cjsReason);
451
+ }
452
+ if (this._configuration.emitMjsExtensionForESModule) {
453
+ this._addModuleKindToEmit(ts.ModuleKind.ESNext, tsconfig.options.outDir,
454
+ /* isPrimary */ tsconfig.options.module === ts.ModuleKind.ESNext, '.mjs');
455
+ const mjsReason = {
456
+ outDir: tsconfig.options.outDir,
457
+ kind: 'ESNext',
458
+ extension: '.mjs',
459
+ reason: 'emitMjsExtensionForESModule'
460
+ };
461
+ specifiedKinds.set(ts.ModuleKind.ESNext, mjsReason);
462
+ specifiedOutDirs.set(`${tsconfig.options.outDir}:.mjs`, mjsReason);
463
+ }
464
+ if (!specifiedKinds.has(tsconfig.options.module)) {
465
+ this._addModuleKindToEmit(tsconfig.options.module, tsconfig.options.outDir,
466
+ /* isPrimary */ true,
467
+ /* jsExtensionOverride */ undefined);
468
+ const tsConfigReason = {
469
+ outDir: tsconfig.options.outDir,
470
+ kind: ts.ModuleKind[tsconfig.options.module],
471
+ extension: '.js',
472
+ reason: 'tsconfig.json'
473
+ };
474
+ specifiedKinds.set(tsconfig.options.module, tsConfigReason);
475
+ specifiedOutDirs.set(`${tsconfig.options.outDir}:.js`, tsConfigReason);
476
+ }
477
+ if (this._configuration.additionalModuleKindsToEmit) {
478
+ for (const additionalModuleKindToEmit of this._configuration.additionalModuleKindsToEmit) {
479
+ const moduleKind = this._parseModuleKind(ts, additionalModuleKindToEmit.moduleKind);
480
+ const outDirKey = `${additionalModuleKindToEmit.outFolderName}:.js`;
481
+ const moduleKindReason = {
482
+ kind: ts.ModuleKind[moduleKind],
483
+ outDir: additionalModuleKindToEmit.outFolderName,
484
+ extension: '.js',
485
+ reason: `additionalModuleKindsToEmit`
486
+ };
487
+ const existingKind = specifiedKinds.get(moduleKind);
488
+ const existingDir = specifiedOutDirs.get(outDirKey);
489
+ if (existingKind) {
490
+ throw new Error(`Module kind "${additionalModuleKindToEmit.moduleKind}" is already emitted at ${existingKind.outDir} with extension '${existingKind.extension}' by option ${existingKind.reason}.`);
491
+ }
492
+ else if (existingDir) {
493
+ throw new Error(`Output folder "${additionalModuleKindToEmit.outFolderName}" already contains module kind ${existingDir.kind} with extension '${existingDir.extension}', specified by option ${existingDir.reason}.`);
494
+ }
495
+ else {
496
+ const outFolderKey = this._addModuleKindToEmit(moduleKind, additionalModuleKindToEmit.outFolderName,
497
+ /* isPrimary */ false, undefined);
498
+ if (outFolderKey) {
499
+ specifiedKinds.set(moduleKind, moduleKindReason);
500
+ specifiedOutDirs.set(outFolderKey, moduleKindReason);
501
+ }
502
+ }
503
+ }
504
+ }
505
+ }
506
+ _addModuleKindToEmit(moduleKind, outFolderPath, isPrimary, jsExtensionOverride) {
507
+ let outFolderName;
508
+ if (path.isAbsolute(outFolderPath)) {
509
+ outFolderName = path.relative(this._configuration.buildFolderPath, outFolderPath);
510
+ }
511
+ else {
512
+ outFolderName = outFolderPath;
513
+ outFolderPath = path.resolve(this._configuration.buildFolderPath, outFolderPath);
514
+ }
515
+ outFolderPath = node_core_library_1.Path.convertToSlashes(outFolderPath);
516
+ outFolderPath = outFolderPath.replace(/\/*$/, '/'); // Ensure the outFolderPath ends with a slash
517
+ for (const existingModuleKindToEmit of this._moduleKindsToEmit) {
518
+ let errorText;
519
+ if (existingModuleKindToEmit.outFolderPath === outFolderPath) {
520
+ if (existingModuleKindToEmit.jsExtensionOverride === jsExtensionOverride) {
521
+ errorText =
522
+ 'Unable to output two different module kinds with the same ' +
523
+ `module extension (${jsExtensionOverride || '.js'}) to the same ` +
524
+ `folder ("${outFolderPath}").`;
525
+ }
526
+ }
527
+ else {
528
+ let parentFolder;
529
+ let childFolder;
530
+ if (outFolderPath.startsWith(existingModuleKindToEmit.outFolderPath)) {
531
+ parentFolder = outFolderPath;
532
+ childFolder = existingModuleKindToEmit.outFolderPath;
533
+ }
534
+ else if (existingModuleKindToEmit.outFolderPath.startsWith(outFolderPath)) {
535
+ parentFolder = existingModuleKindToEmit.outFolderPath;
536
+ childFolder = outFolderPath;
537
+ }
538
+ if (parentFolder) {
539
+ errorText =
540
+ 'Unable to output two different module kinds to nested folders ' +
541
+ `("${parentFolder}" and "${childFolder}").`;
542
+ }
543
+ }
544
+ if (errorText) {
545
+ this._typescriptLogger.emitError(new Error(errorText));
546
+ return undefined;
547
+ }
548
+ }
549
+ this._moduleKindsToEmit.push({
550
+ outFolderPath,
551
+ moduleKind,
552
+ jsExtensionOverride,
553
+ isPrimary
554
+ });
555
+ return `${outFolderName}:${jsExtensionOverride || '.js'}`;
556
+ }
557
+ _loadTsconfig(ts) {
558
+ const parsedConfigFile = ts.readConfigFile(this._configuration.tsconfigPath, ts.sys.readFile);
559
+ const currentFolder = path.dirname(this._configuration.tsconfigPath);
560
+ const tsconfig = ts.parseJsonConfigFileContent(parsedConfigFile.config, {
561
+ fileExists: ts.sys.fileExists,
562
+ readFile: ts.sys.readFile,
563
+ readDirectory: ts.sys.readDirectory,
564
+ useCaseSensitiveFileNames: true
565
+ }, currentFolder,
566
+ /*existingOptions:*/ undefined, this._configuration.tsconfigPath);
567
+ if (tsconfig.options.incremental) {
568
+ tsconfig.options.tsBuildInfoFile = this._tsCacheFilePath;
569
+ }
570
+ return tsconfig;
571
+ }
572
+ _getCreateBuilderProgram(ts) {
573
+ const { _configuration: { emitChangedFilesCallback } } = this;
574
+ const createMultiEmitBuilderProgram = (fileNames, compilerOptions, host, oldProgram, configFileParsingDiagnostics, projectReferences) => {
575
+ // Reset performance counters
576
+ ts.performance.disable();
577
+ ts.performance.enable();
578
+ this._typescriptTerminal.writeVerboseLine(`Reading program "${compilerOptions.configFilePath}"`);
579
+ const newProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram(fileNames, compilerOptions, host, oldProgram, configFileParsingDiagnostics, projectReferences);
580
+ this._logReadPerformance(ts);
581
+ const isolatedModules = !!this._configuration.useTranspilerWorker && !!compilerOptions.isolatedModules;
582
+ const mode = isolatedModules ? 'declaration' : 'both';
583
+ if (isolatedModules) {
584
+ // Kick the transpilation worker.
585
+ const filesToTranspile = getFilesToTranspileFromBuilderProgram(newProgram);
586
+ this._queueTranspileInWorker(this._tool, compilerOptions, filesToTranspile);
587
+ }
588
+ const { emit: originalEmit } = newProgram;
589
+ const emit = (outerTargetSourceFile, outerWriteFile, outerCancellationToken, outerEmitOnlyDtsFiles, outerCustomTransformers) => {
590
+ const innerProgram = newProgram.getProgram();
591
+ const innerCompilerOptions = innerProgram.getCompilerOptions();
592
+ const { changedFiles } = (0, configureProgramForMultiEmit_1.configureProgramForMultiEmit)(innerProgram, ts, this._moduleKindsToEmit, mode);
593
+ const result = originalEmit.call(newProgram, outerTargetSourceFile, outerWriteFile, outerCancellationToken, outerEmitOnlyDtsFiles, outerCustomTransformers);
594
+ result.changedSourceFiles = changedFiles;
595
+ this._typescriptTerminal.writeVerboseLine(`Emitting program "${innerCompilerOptions.configFilePath}"`);
596
+ this._logEmitPerformance(ts);
597
+ // Reset performance counters
598
+ ts.performance.disable();
599
+ ts.performance.enable();
600
+ emitChangedFilesCallback(innerProgram, changedFiles);
601
+ return result;
602
+ };
603
+ newProgram.emit = emit;
604
+ return newProgram;
605
+ };
606
+ return createMultiEmitBuilderProgram;
607
+ }
608
+ _buildSolutionBuilderHost(tool) {
609
+ const reportSolutionBuilderStatus = tool.reportDiagnostic;
610
+ const reportEmitErrorSummary = (errorCount) => {
611
+ // Do nothing
612
+ };
613
+ const { ts } = tool;
614
+ const solutionBuilderHost = ts.createSolutionBuilderHost(ts.sys, this._getCreateBuilderProgram(ts), tool.reportDiagnostic, reportSolutionBuilderStatus, reportEmitErrorSummary);
615
+ solutionBuilderHost.afterProgramEmitAndDiagnostics = (program) => {
616
+ // Use the native metric since we aren't overwriting the writer
617
+ this._typescriptTerminal.writeVerboseLine(`I/O Write: ${ts.performance.getDuration('I/O Write')}ms (${ts.performance.getCount('beforeIOWrite')} files)`);
618
+ };
619
+ return solutionBuilderHost;
620
+ }
621
+ _buildIncrementalCompilerHost(tool, tsconfig) {
622
+ const { ts } = tool;
623
+ let compilerHost;
624
+ if (tsconfig.options.incremental) {
625
+ compilerHost = ts.createIncrementalCompilerHost(tsconfig.options, ts.sys);
626
+ }
627
+ else {
628
+ compilerHost = ts.createCompilerHost(tsconfig.options);
629
+ }
630
+ this._changeCompilerHostToUseCache(compilerHost, tool);
631
+ return compilerHost;
632
+ }
633
+ _buildWatchCompilerHost(tool, tsconfig) {
634
+ const { ts } = tool;
635
+ const reportWatchStatus = (diagnostic) => {
636
+ this._printDiagnosticMessage(ts, diagnostic);
637
+ };
638
+ const compilerHost = ts.createWatchCompilerHost(tsconfig.fileNames, tsconfig.options, ts.sys, this._getCreateBuilderProgram(ts), tool.reportDiagnostic, reportWatchStatus, tsconfig.projectReferences, tsconfig.watchOptions);
639
+ compilerHost.clearTimeout = tool.clearTimeout;
640
+ compilerHost.setTimeout = tool.setTimeout;
641
+ return compilerHost;
642
+ }
643
+ _changeCompilerHostToUseCache(compilerHost, tool) {
644
+ const { sourceFileCache } = tool;
645
+ const { getSourceFile: innerGetSourceFile } = compilerHost;
646
+ if (innerGetSourceFile.cache === sourceFileCache) {
647
+ return;
648
+ }
649
+ // Enable source file persistence
650
+ const getSourceFile = (fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) => {
651
+ if (!shouldCreateNewSourceFile) {
652
+ const cachedSourceFile = sourceFileCache.get(fileName);
653
+ if (cachedSourceFile) {
654
+ return cachedSourceFile;
655
+ }
656
+ }
657
+ const result = innerGetSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile);
658
+ if (result) {
659
+ sourceFileCache.set(fileName, result);
660
+ }
661
+ else {
662
+ sourceFileCache.delete(fileName);
663
+ }
664
+ return result;
665
+ };
666
+ getSourceFile.cache = sourceFileCache;
667
+ compilerHost.getSourceFile = getSourceFile;
668
+ }
669
+ _buildWatchSolutionBuilderHost(tool) {
670
+ const { reportDiagnostic, ts } = tool;
671
+ const host = ts.createSolutionBuilderWithWatchHost(ts.sys, this._getCreateBuilderProgram(ts), reportDiagnostic, reportDiagnostic, reportDiagnostic);
672
+ host.clearTimeout = tool.clearTimeout;
673
+ host.setTimeout = tool.setTimeout;
674
+ return host;
675
+ }
676
+ _parseModuleKind(ts, moduleKindName) {
677
+ switch (moduleKindName.toLowerCase()) {
678
+ case 'commonjs':
679
+ return ts.ModuleKind.CommonJS;
680
+ case 'amd':
681
+ return ts.ModuleKind.AMD;
682
+ case 'umd':
683
+ return ts.ModuleKind.UMD;
684
+ case 'system':
685
+ return ts.ModuleKind.System;
686
+ case 'es2015':
687
+ return ts.ModuleKind.ES2015;
688
+ case 'esnext':
689
+ return ts.ModuleKind.ESNext;
690
+ default:
691
+ throw new Error(`"${moduleKindName}" is not a valid module kind name.`);
692
+ }
693
+ }
694
+ _queueTranspileInWorker(tool, compilerOptions, filesToTranspile) {
695
+ const { pendingTranspilePromises, pendingTranspileSignals } = tool;
696
+ let maybeWorker = tool.worker;
697
+ if (!maybeWorker) {
698
+ const workerData = {
699
+ typeScriptToolPath: this._configuration.typeScriptToolPath
700
+ };
701
+ tool.worker = maybeWorker = new worker_threads_1.Worker(require.resolve('./TranspilerWorker.js'), {
702
+ workerData: workerData
703
+ });
704
+ maybeWorker.on('message', (response) => {
705
+ const { requestId: resolvingRequestId, type, result } = response;
706
+ const signal = pendingTranspileSignals.get(resolvingRequestId);
707
+ if (type === 'error') {
708
+ const error = Object.assign(new Error(result.message), result);
709
+ if (signal) {
710
+ signal.reject(error);
711
+ }
712
+ else {
713
+ this._typescriptTerminal.writeErrorLine(`Unexpected worker rejection for request with id ${resolvingRequestId}: ${error}`);
714
+ }
715
+ }
716
+ else if (signal) {
717
+ signal.resolve(result);
718
+ }
719
+ else {
720
+ this._typescriptTerminal.writeErrorLine(`Unexpected worker resolution for request with id ${resolvingRequestId}`);
721
+ }
722
+ pendingTranspileSignals.delete(resolvingRequestId);
723
+ pendingTranspilePromises.delete(resolvingRequestId);
724
+ });
725
+ maybeWorker.once('exit', (exitCode) => {
726
+ if (pendingTranspileSignals.size) {
727
+ const error = new Error(`Worker exited unexpectedly with code ${exitCode}.`);
728
+ for (const { reject: rejectTranspile } of pendingTranspileSignals.values()) {
729
+ rejectTranspile(error);
730
+ }
731
+ pendingTranspileSignals.clear();
732
+ }
733
+ });
734
+ maybeWorker.once('error', (err) => {
735
+ for (const { reject: rejectTranspile } of pendingTranspileSignals.values()) {
736
+ rejectTranspile(err);
737
+ }
738
+ pendingTranspileSignals.clear();
739
+ });
740
+ }
741
+ // make linter happy
742
+ const worker = maybeWorker;
743
+ const requestId = ++this._nextRequestId;
744
+ const transpilePromise = new Promise((resolve, reject) => {
745
+ pendingTranspileSignals.set(requestId, { resolve, reject });
746
+ this._typescriptTerminal.writeLine(`Asynchronously transpiling ${compilerOptions.configFilePath}`);
747
+ const request = {
748
+ compilerOptions,
749
+ filesToTranspile,
750
+ moduleKindsToEmit: this._moduleKindsToEmit,
751
+ requestId
752
+ };
753
+ worker.postMessage(request);
754
+ });
755
+ pendingTranspilePromises.set(requestId, transpilePromise);
756
+ }
757
+ _cleanupWorker() {
758
+ const tool = this._tool;
759
+ if (!tool) {
760
+ return;
761
+ }
762
+ const { worker } = tool;
763
+ if (worker) {
764
+ worker.postMessage(false);
765
+ tool.worker = undefined;
766
+ }
767
+ }
768
+ }
769
+ exports.TypeScriptBuilder = TypeScriptBuilder;
770
+ function getFilesToTranspileFromBuilderProgram(builderProgram) {
771
+ const changedFilesSet = builderProgram.getState().changedFilesSet;
772
+ const filesToTranspile = new Map();
773
+ for (const fileName of changedFilesSet) {
774
+ const sourceFile = builderProgram.getSourceFile(fileName);
775
+ if (sourceFile && !sourceFile.isDeclarationFile) {
776
+ filesToTranspile.set(sourceFile.fileName, sourceFile.text);
777
+ }
778
+ }
779
+ return filesToTranspile;
780
+ }
781
+ function getFilesToTranspileFromProgram(program) {
782
+ const filesToTranspile = new Map();
783
+ for (const sourceFile of program.getSourceFiles()) {
784
+ if (!sourceFile.isDeclarationFile) {
785
+ filesToTranspile.set(sourceFile.fileName, sourceFile.text);
786
+ }
787
+ }
788
+ return filesToTranspile;
789
+ }
790
+ //# sourceMappingURL=TypeScriptBuilder.js.map