@rushstack/heft-typescript-plugin 1.1.14 → 1.2.1

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