-
Notifications
You must be signed in to change notification settings - Fork 622
/
Copy pathExtractor.ts
538 lines (478 loc) · 19.4 KB
/
Extractor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import * as path from 'path';
import * as semver from 'semver';
import * as ts from 'typescript';
import * as resolve from 'resolve';
import {
FileSystem,
type NewlineKind,
PackageJsonLookup,
type IPackageJson,
type INodePackageJson,
Path
} from '@rushstack/node-core-library';
import { ExtractorConfig, type IExtractorConfigApiReport } from './ExtractorConfig';
import { Collector } from '../collector/Collector';
import { DtsRollupGenerator, DtsRollupKind } from '../generators/DtsRollupGenerator';
import { ApiModelGenerator } from '../generators/ApiModelGenerator';
import type { ApiPackage } from '@microsoft/api-extractor-model';
import { ApiReportGenerator } from '../generators/ApiReportGenerator';
import { PackageMetadataManager } from '../analyzer/PackageMetadataManager';
import { ValidationEnhancer } from '../enhancers/ValidationEnhancer';
import { DocCommentEnhancer } from '../enhancers/DocCommentEnhancer';
import { CompilerState } from './CompilerState';
import type { ExtractorMessage } from './ExtractorMessage';
import { MessageRouter } from '../collector/MessageRouter';
import { ConsoleMessageId } from './ConsoleMessageId';
import { TSDocConfigFile } from '@microsoft/tsdoc-config';
import { SourceMapper } from '../collector/SourceMapper';
/**
* Runtime options for Extractor.
*
* @public
*/
export interface IExtractorInvokeOptions {
/**
* An optional TypeScript compiler state. This allows an optimization where multiple invocations of API Extractor
* can reuse the same TypeScript compiler analysis.
*/
compilerState?: CompilerState;
/**
* Indicates that API Extractor is running as part of a local build, e.g. on developer's
* machine.
*
* @remarks
* This disables certain validation that would normally be performed for a ship/production build. For example,
* the *.api.md report file is automatically updated in a local build.
*
* The default value is false.
*/
localBuild?: boolean;
/**
* If true, API Extractor will include {@link ExtractorLogLevel.Verbose} messages in its output.
*/
showVerboseMessages?: boolean;
/**
* If true, API Extractor will print diagnostic information used for troubleshooting problems.
* These messages will be included as {@link ExtractorLogLevel.Verbose} output.
*
* @remarks
* Setting `showDiagnostics=true` forces `showVerboseMessages=true`.
*/
showDiagnostics?: boolean;
/**
* Specifies an alternate folder path to be used when loading the TypeScript system typings.
*
* @remarks
* API Extractor uses its own TypeScript compiler engine to analyze your project. If your project
* is built with a significantly different TypeScript version, sometimes API Extractor may report compilation
* errors due to differences in the system typings (e.g. lib.dom.d.ts). You can use the "--typescriptCompilerFolder"
* option to specify the folder path where you installed the TypeScript package, and API Extractor's compiler will
* use those system typings instead.
*/
typescriptCompilerFolder?: string;
/**
* An optional callback function that will be called for each `ExtractorMessage` before it is displayed by
* API Extractor. The callback can customize the message, handle it, or discard it.
*
* @remarks
* If a `messageCallback` is not provided, then by default API Extractor will print the messages to
* the STDERR/STDOUT console.
*/
messageCallback?: (message: ExtractorMessage) => void;
}
/**
* This object represents the outcome of an invocation of API Extractor.
*
* @public
*/
export class ExtractorResult {
/**
* The TypeScript compiler state that was used.
*/
public readonly compilerState: CompilerState;
/**
* The API Extractor configuration that was used.
*/
public readonly extractorConfig: ExtractorConfig;
/**
* Whether the invocation of API Extractor was successful. For example, if `succeeded` is false, then the build task
* would normally return a nonzero process exit code, indicating that the operation failed.
*
* @remarks
*
* Normally the operation "succeeds" if `errorCount` and `warningCount` are both zero. However if
* {@link IExtractorInvokeOptions.localBuild} is `true`, then the operation "succeeds" if `errorCount` is zero
* (i.e. warnings are ignored).
*/
public readonly succeeded: boolean;
/**
* Returns true if the API report was found to have changed.
*/
public readonly apiReportChanged: boolean;
/**
* Reports the number of errors encountered during analysis.
*
* @remarks
* This does not count exceptions, where unexpected issues prematurely abort the operation.
*/
public readonly errorCount: number;
/**
* Reports the number of warnings encountered during analysis.
*
* @remarks
* This does not count warnings that are emitted in the API report file.
*/
public readonly warningCount: number;
/** @internal */
public constructor(properties: ExtractorResult) {
this.compilerState = properties.compilerState;
this.extractorConfig = properties.extractorConfig;
this.succeeded = properties.succeeded;
this.apiReportChanged = properties.apiReportChanged;
this.errorCount = properties.errorCount;
this.warningCount = properties.warningCount;
}
}
/**
* The starting point for invoking the API Extractor tool.
* @public
*/
export class Extractor {
/**
* Returns the version number of the API Extractor NPM package.
*/
public static get version(): string {
return Extractor._getPackageJson().version;
}
/**
* Returns the package name of the API Extractor NPM package.
*/
public static get packageName(): string {
return Extractor._getPackageJson().name;
}
private static _getPackageJson(): IPackageJson {
return PackageJsonLookup.loadOwnPackageJson(__dirname);
}
/**
* Load the api-extractor.json config file from the specified path, and then invoke API Extractor.
*/
public static loadConfigAndInvoke(
configFilePath: string,
options?: IExtractorInvokeOptions
): ExtractorResult {
const extractorConfig: ExtractorConfig = ExtractorConfig.loadFileAndPrepare(configFilePath);
return Extractor.invoke(extractorConfig, options);
}
/**
* Invoke API Extractor using an already prepared `ExtractorConfig` object.
*/
public static invoke(extractorConfig: ExtractorConfig, options?: IExtractorInvokeOptions): ExtractorResult {
if (!options) {
options = {};
}
const localBuild: boolean = options.localBuild || false;
let compilerState: CompilerState | undefined;
if (options.compilerState) {
compilerState = options.compilerState;
} else {
compilerState = CompilerState.create(extractorConfig, options);
}
const sourceMapper: SourceMapper = new SourceMapper();
const messageRouter: MessageRouter = new MessageRouter({
workingPackageFolder: extractorConfig.packageFolder,
messageCallback: options.messageCallback,
messagesConfig: extractorConfig.messages || {},
showVerboseMessages: !!options.showVerboseMessages,
showDiagnostics: !!options.showDiagnostics,
tsdocConfiguration: extractorConfig.tsdocConfiguration,
sourceMapper
});
if (extractorConfig.tsdocConfigFile.filePath && !extractorConfig.tsdocConfigFile.fileNotFound) {
if (!Path.isEqual(extractorConfig.tsdocConfigFile.filePath, ExtractorConfig._tsdocBaseFilePath)) {
messageRouter.logVerbose(
ConsoleMessageId.UsingCustomTSDocConfig,
'Using custom TSDoc config from ' + extractorConfig.tsdocConfigFile.filePath
);
}
}
this._checkCompilerCompatibility(extractorConfig, messageRouter);
if (messageRouter.showDiagnostics) {
messageRouter.logDiagnostic('');
messageRouter.logDiagnosticHeader('Final prepared ExtractorConfig');
messageRouter.logDiagnostic(extractorConfig.getDiagnosticDump());
messageRouter.logDiagnosticFooter();
messageRouter.logDiagnosticHeader('Compiler options');
const serializedCompilerOptions: object = MessageRouter.buildJsonDumpObject(
(compilerState.program as ts.Program).getCompilerOptions()
);
messageRouter.logDiagnostic(JSON.stringify(serializedCompilerOptions, undefined, 2));
messageRouter.logDiagnosticFooter();
messageRouter.logDiagnosticHeader('TSDoc configuration');
// Convert the TSDocConfiguration into a tsdoc.json representation
const combinedConfigFile: TSDocConfigFile = TSDocConfigFile.loadFromParser(
extractorConfig.tsdocConfiguration
);
const serializedTSDocConfig: object = MessageRouter.buildJsonDumpObject(
combinedConfigFile.saveToObject()
);
messageRouter.logDiagnostic(JSON.stringify(serializedTSDocConfig, undefined, 2));
messageRouter.logDiagnosticFooter();
}
const collector: Collector = new Collector({
program: compilerState.program as ts.Program,
messageRouter,
extractorConfig,
sourceMapper
});
collector.analyze();
DocCommentEnhancer.analyze(collector);
ValidationEnhancer.analyze(collector);
const modelBuilder: ApiModelGenerator = new ApiModelGenerator(collector, extractorConfig);
const apiPackage: ApiPackage = modelBuilder.buildApiPackage();
if (messageRouter.showDiagnostics) {
messageRouter.logDiagnostic(''); // skip a line after any diagnostic messages
}
if (modelBuilder.docModelEnabled) {
messageRouter.logVerbose(
ConsoleMessageId.WritingDocModelFile,
'Writing: ' + extractorConfig.apiJsonFilePath
);
apiPackage.saveToJsonFile(extractorConfig.apiJsonFilePath, {
toolPackage: Extractor.packageName,
toolVersion: Extractor.version,
newlineConversion: extractorConfig.newlineKind,
ensureFolderExists: true,
testMode: extractorConfig.testMode
});
}
function writeApiReport(reportConfig: IExtractorConfigApiReport): boolean {
return Extractor._writeApiReport(
collector,
extractorConfig,
messageRouter,
extractorConfig.reportTempFolder,
extractorConfig.reportFolder,
reportConfig,
localBuild
);
}
let anyReportChanged: boolean = false;
if (extractorConfig.apiReportEnabled) {
for (const reportConfig of extractorConfig.reportConfigs) {
anyReportChanged = writeApiReport(reportConfig) || anyReportChanged;
}
}
if (extractorConfig.rollupEnabled) {
Extractor._generateRollupDtsFile(
collector,
extractorConfig.publicTrimmedFilePath,
DtsRollupKind.PublicRelease,
extractorConfig.newlineKind
);
Extractor._generateRollupDtsFile(
collector,
extractorConfig.alphaTrimmedFilePath,
DtsRollupKind.AlphaRelease,
extractorConfig.newlineKind
);
Extractor._generateRollupDtsFile(
collector,
extractorConfig.betaTrimmedFilePath,
DtsRollupKind.BetaRelease,
extractorConfig.newlineKind
);
Extractor._generateRollupDtsFile(
collector,
extractorConfig.untrimmedFilePath,
DtsRollupKind.InternalRelease,
extractorConfig.newlineKind
);
}
if (extractorConfig.tsdocMetadataEnabled) {
// Write the tsdoc-metadata.json file for this project
PackageMetadataManager.writeTsdocMetadataFile(
extractorConfig.tsdocMetadataFilePath,
extractorConfig.newlineKind
);
}
// Show all the messages that we collected during analysis
messageRouter.handleRemainingNonConsoleMessages();
// Determine success
let succeeded: boolean;
if (localBuild) {
// For a local build, fail if there were errors (but ignore warnings)
succeeded = messageRouter.errorCount === 0;
} else {
// For a production build, fail if there were any errors or warnings
succeeded = messageRouter.errorCount + messageRouter.warningCount === 0;
}
return new ExtractorResult({
compilerState,
extractorConfig,
succeeded,
apiReportChanged: anyReportChanged,
errorCount: messageRouter.errorCount,
warningCount: messageRouter.warningCount
});
}
/**
* Generates the API report at the specified release level, writes it to the specified file path, and compares
* the output to the existing report (if one exists).
*
* @param reportTempDirectoryPath - The path to the directory under which the temp report file will be written prior
* to comparison with an existing report.
* @param reportDirectoryPath - The path to the directory under which the existing report file is located, and to
* which the new report will be written post-comparison.
* @param reportConfig - API report configuration, including its file name and {@link ApiReportVariant}.
*
* @returns Whether or not the newly generated report differs from the existing report (if one exists).
*/
private static _writeApiReport(
collector: Collector,
extractorConfig: ExtractorConfig,
messageRouter: MessageRouter,
reportTempDirectoryPath: string,
reportDirectoryPath: string,
reportConfig: IExtractorConfigApiReport,
localBuild: boolean
): boolean {
let apiReportChanged: boolean = false;
const actualApiReportPath: string = path.resolve(reportTempDirectoryPath, reportConfig.fileName);
const actualApiReportShortPath: string = extractorConfig._getShortFilePath(actualApiReportPath);
const expectedApiReportPath: string = path.resolve(reportDirectoryPath, reportConfig.fileName);
const expectedApiReportShortPath: string = extractorConfig._getShortFilePath(expectedApiReportPath);
collector.messageRouter.logVerbose(
ConsoleMessageId.WritingApiReport,
`Generating ${reportConfig.variant} API report: ${expectedApiReportPath}`
);
const actualApiReportContent: string = ApiReportGenerator.generateReviewFileContent(
collector,
reportConfig.variant
);
// Write the actual file
FileSystem.writeFile(actualApiReportPath, actualApiReportContent, {
ensureFolderExists: true,
convertLineEndings: extractorConfig.newlineKind
});
// Compare it against the expected file
if (FileSystem.exists(expectedApiReportPath)) {
const expectedApiReportContent: string = FileSystem.readFile(expectedApiReportPath);
if (
!ApiReportGenerator.areEquivalentApiFileContents(actualApiReportContent, expectedApiReportContent)
) {
apiReportChanged = true;
if (!localBuild) {
// For a production build, issue a warning that will break the CI build.
messageRouter.logWarning(
ConsoleMessageId.ApiReportNotCopied,
'You have changed the API signature for this project.' +
` Please copy the file "${actualApiReportShortPath}" to "${expectedApiReportShortPath}",` +
` or perform a local build (which does this automatically).` +
` See the Git repo documentation for more info.`
);
} else {
// For a local build, just copy the file automatically.
messageRouter.logWarning(
ConsoleMessageId.ApiReportCopied,
`You have changed the API signature for this project. Updating ${expectedApiReportShortPath}`
);
FileSystem.writeFile(expectedApiReportPath, actualApiReportContent, {
ensureFolderExists: true,
convertLineEndings: extractorConfig.newlineKind
});
}
} else {
messageRouter.logVerbose(
ConsoleMessageId.ApiReportUnchanged,
`The API report is up to date: ${actualApiReportShortPath}`
);
}
} else {
// The target file does not exist, so we are setting up the API review file for the first time.
//
// NOTE: People sometimes make a mistake where they move a project and forget to update the "reportFolder"
// setting, which causes a new file to silently get written to the wrong place. This can be confusing.
// Thus we treat the initial creation of the file specially.
apiReportChanged = true;
if (!localBuild) {
// For a production build, issue a warning that will break the CI build.
messageRouter.logWarning(
ConsoleMessageId.ApiReportNotCopied,
'The API report file is missing.' +
` Please copy the file "${actualApiReportShortPath}" to "${expectedApiReportShortPath}",` +
` or perform a local build (which does this automatically).` +
` See the Git repo documentation for more info.`
);
} else {
const expectedApiReportFolder: string = path.dirname(expectedApiReportPath);
if (!FileSystem.exists(expectedApiReportFolder)) {
messageRouter.logError(
ConsoleMessageId.ApiReportFolderMissing,
'Unable to create the API report file. Please make sure the target folder exists:\n' +
expectedApiReportFolder
);
} else {
FileSystem.writeFile(expectedApiReportPath, actualApiReportContent, {
convertLineEndings: extractorConfig.newlineKind
});
messageRouter.logWarning(
ConsoleMessageId.ApiReportCreated,
'The API report file was missing, so a new file was created. Please add this file to Git:\n' +
expectedApiReportPath
);
}
}
}
return apiReportChanged;
}
private static _checkCompilerCompatibility(
extractorConfig: ExtractorConfig,
messageRouter: MessageRouter
): void {
messageRouter.logInfo(
ConsoleMessageId.Preamble,
`Analysis will use the bundled TypeScript version ${ts.version}`
);
try {
const typescriptPath: string = resolve.sync('typescript', {
basedir: extractorConfig.projectFolder,
preserveSymlinks: false
});
const packageJsonLookup: PackageJsonLookup = new PackageJsonLookup();
const packageJson: INodePackageJson | undefined =
packageJsonLookup.tryLoadNodePackageJsonFor(typescriptPath);
if (packageJson && packageJson.version && semver.valid(packageJson.version)) {
// Consider a newer MINOR release to be incompatible
const ourMajor: number = semver.major(ts.version);
const ourMinor: number = semver.minor(ts.version);
const theirMajor: number = semver.major(packageJson.version);
const theirMinor: number = semver.minor(packageJson.version);
if (theirMajor > ourMajor || (theirMajor === ourMajor && theirMinor > ourMinor)) {
messageRouter.logInfo(
ConsoleMessageId.CompilerVersionNotice,
`*** The target project appears to use TypeScript ${packageJson.version} which is newer than the` +
` bundled compiler engine; consider upgrading API Extractor.`
);
}
}
} catch (e) {
// The compiler detection heuristic is not expected to work in many configurations
}
}
private static _generateRollupDtsFile(
collector: Collector,
outputPath: string,
dtsKind: DtsRollupKind,
newlineKind: NewlineKind
): void {
if (outputPath !== '') {
collector.messageRouter.logVerbose(
ConsoleMessageId.WritingDtsRollup,
`Writing package typings: ${outputPath}`
);
DtsRollupGenerator.writeTypingsFile(collector, outputPath, dtsKind, newlineKind);
}
}
}