Skip to content

Commit f8e2993

Browse files
authored
Merge pull request microsoft#582 from Microsoft/pgonzal/new-dts-config
[api-extractor] Improved model for rollup *.d.ts target folder configuration
2 parents b565338 + 4501b90 commit f8e2993

37 files changed

Lines changed: 293 additions & 129 deletions

‎apps/api-extractor/.vscode/launch.json‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414
"-d",
1515
"run",
1616
"-l"
17-
]
17+
],
18+
"sourceMaps": false
1819
},
1920
{
2021
"type": "node",
@@ -26,7 +27,8 @@
2627
"-d",
2728
"run",
2829
"-l"
29-
]
30+
],
31+
"sourceMaps": false
3032
},
3133
{
3234
"type": "node",
@@ -38,7 +40,8 @@
3840
"-d",
3941
"run",
4042
"-l"
41-
]
43+
],
44+
"sourceMaps": false
4245
},
4346
{
4447
"type": "node",
@@ -62,7 +65,8 @@
6265
"-d",
6366
"run",
6467
"-l"
65-
]
68+
],
69+
"sourceMaps": false
6670
}
6771
]
6872
}

‎apps/api-extractor/README.md‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,24 +11,27 @@
1111

1212
**API Extractor** helps you build better [TypeScript](https://www.typescriptlang.org/) library packages. Suppose for example that your company has published an NPM package called "**awesome-widgets**" that exports many classes and interfaces. As developers start to depend on your library, you may encounter issues such as...
1313

14-
- **Determining versions:** The [SemVer](http://semver.org/) standard uses version numbers to communicate the impact of upgrading to your consumers. But when it's time to publish a new release, how to determine whether it should be a "major", "minor", or "patch" version? For an active project with many source files, it's often not obvious how the API contract has changed.
15-
1614
- **Accidental breaks:** People keep reporting that their code won't compile after a supposedly "minor" update. To address this, you boldly propose that every **awesome-widgets** pull request must be approved by an experienced developer from your team. But that proves unrealistic -- nobody has time to look at every single PR! What you really need is a way to detect PRs that change API contracts, and flag them for review. That would focus attention in the right place... but how to do that?
1715

1816
- **Missing exports:** Suppose the **awesome-widgets** package exports an API function `AwesomeButton.draw()` that requires a parameter of type `DrawStyle`, but you forgot to export this enum. Things seem fine at first, but when a developer tries to call that function, they discover that there's no way to specify the `DrawStyle`. How to avoid these oversights?
1917

20-
- **Accidental exports:** You meant for your`DrawHelper` class to be kept internal, but one day you realize it's being exported by your package. When you try to remove it, you learn that some consumers are now relying on it. How do we avoid this in the future?
18+
- **Accidental exports:** You meant for your `DrawHelper` class to be kept internal, but one day you realize it's a package export. When you try to remove it, consumers complain that they are using it. How do we avoid this in the future?
19+
20+
- **Alpha/Beta graduation:** You want to release previews of new APIs that are not ready for prime time yet. But if you did a major SemVer bump every time you change these definitions, the villagers would be after you with torches and pitchforks! A better approach is to designate certain classes/members as **alpha** quality, then promote them to **beta** and finally to **public** when they're mature. But how to indicate this to your consumers? (And how to detect scoping mistakes? A **public** function should never return a **beta** result.)
2121

22-
- **Alpha/Beta graduation:** You want to release previews of new APIs that are not ready for prime time yet. If you did a major SemVer bump every time you change these definitions, the villagers would be after you with torches and pitchforks. A better approach is to designate certain classes/members as "**alpha**" quality, then promote them to "**beta**" and finally to "**public**" when they're mature. But how to indicate this to your consumers? (And how to detect scoping mistakes? A "public" function should never return a "beta" result.)
22+
- **\*.d.ts rollup:** You webpacked your library into a nice **\*.js** bundle file -- so why are you distributing your typings as a messy tree of **lib/\*.d.ts** files full of private definitions? Let's consolidate them into a tidy **\*.d.ts** rollup file. If you publish internal/beta/public releases, a semantic analyzer can trim the **\*.d.ts** rollup according to each release type. Developers working on a production project don't want to see a bunch of **internal** and **beta** members in their VS Code IntelliSense!
2323

2424
- **Online documentation:** You have faithfully annotated each TypeScript member with nice [JSDoc](http://usejsdoc.org/) descriptions. Now that your library is published, you should probably set up [a nicely formatted](https://docs.microsoft.com/en-us/javascript/api/sp-http) API reference. Which tool should we use to generate that? (What!? There aren't any good ones!?)
2525

2626
**API Extractor** provides an integrated, professional-quality solution for all these problems. It is invoked at build time by your toolchain and leverages the TypeScript compiler engine to:
2727

2828
- Detect a project's exported API surface
2929
- Capture the contracts in a concise report designed to facilitate review
30-
- Warn about common mistakes (e.g. missing exports, inconsistent visibility, etc)
31-
- Generate API documentation in portable format that's easy to integrate with your publishing pipeline
30+
- Warn about common mistakes (e.g. missing exports, inconsistent visibility, etc.)
31+
- Generate \*.d.ts rollups
32+
- Output API documentation in a portable format that's easy to integrate with your publishing pipeline
33+
34+
Best of all, **API Extractor** is free and open source. Join the community and create a pull request!
3235

3336
<!-- ----------------------------------------------------------------------------------- -->
3437
<!-- Text above this line should stay in sync with API-Extractor.md from the GitHub wiki -->

‎apps/api-extractor/src/DebugRun.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,9 @@ const extractor: Extractor = new Extractor(
5050
},
5151
dtsRollup: {
5252
enabled: true,
53-
outputFolder: path.join(__dirname, 'debug')
53+
publishFolderForInternal: path.join(__dirname, 'debug/internal'),
54+
publishFolderForBeta: path.join(__dirname, 'debug/beta'),
55+
publishFolderForPublic: path.join(__dirname, 'debug/public')
5456
}
5557
}
5658
);

‎apps/api-extractor/src/ExtractorContext.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import * as ts from 'typescript';
55
import * as fsx from 'fs-extra';
66
import * as path from 'path';
7-
import { PackageJsonLookup } from '@microsoft/node-core-library';
7+
import { PackageJsonLookup, IPackageJson } from '@microsoft/node-core-library';
88

99
import { AstPackage } from './ast/AstPackage';
1010
import { DocItemLoader } from './DocItemLoader';
@@ -47,6 +47,12 @@ export interface IExtractorContextOptions {
4747
export class ExtractorContext {
4848
public typeChecker: ts.TypeChecker;
4949
public package: AstPackage;
50+
51+
/**
52+
* The parsed package.json file for this package.
53+
*/
54+
public readonly packageJson: IPackageJson;
55+
5056
/**
5157
* One DocItemLoader is needed per analyzer to look up external API members
5258
* as needed.
@@ -59,8 +65,6 @@ export class ExtractorContext {
5965

6066
public readonly validationRules: IExtractorValidationRulesConfig;
6167

62-
private _packageName: string;
63-
6468
// If the entry point is "C:\Folder\project\src\index.ts" and the nearest package.json
6569
// is "C:\Folder\project\package.json", then the packageFolder is "C:\Folder\project"
6670
private _packageFolder: string;
@@ -79,7 +83,7 @@ export class ExtractorContext {
7983
}
8084
this._packageFolder = folder;
8185

82-
this._packageName = this.packageJsonLookup.tryLoadPackageJsonFor(this._packageFolder)!.name;
86+
this.packageJson = this.packageJsonLookup.tryLoadPackageJsonFor(this._packageFolder)!;
8387

8488
this.docItemLoader = new DocItemLoader(this._packageFolder);
8589

@@ -108,7 +112,7 @@ export class ExtractorContext {
108112
* Returns the full name of the package being analyzed.
109113
*/
110114
public get packageName(): string {
111-
return this._packageName;
115+
return this.packageJson.name;
112116
}
113117

114118
/**

‎apps/api-extractor/src/extractor/Extractor.ts‎

Lines changed: 82 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,16 @@ import * as ts from 'typescript';
77
import lodash = require('lodash');
88
import colors = require('colors');
99

10-
import { JsonFile, JsonSchema } from '@microsoft/node-core-library';
10+
import {
11+
JsonFile,
12+
JsonSchema,
13+
Path
14+
} from '@microsoft/node-core-library';
1115
import {
1216
IExtractorConfig,
1317
IExtractorProjectConfig,
14-
IExtractorApiJsonFileConfig
18+
IExtractorApiJsonFileConfig,
19+
IExtractorDtsRollupConfig
1520
} from './IExtractorConfig';
1621
import { ExtractorContext } from '../ExtractorContext';
1722
import { ILogger } from './ILogger';
@@ -340,22 +345,7 @@ export class Extractor {
340345
}
341346
}
342347

343-
if (this.actualConfig.dtsRollup.enabled) {
344-
const dtsRollupGenerator: DtsRollupGenerator = new DtsRollupGenerator(context);
345-
dtsRollupGenerator.analyze();
346-
347-
this._generateTypingsFile(dtsRollupGenerator,
348-
this.actualConfig.dtsRollup.dtsFilePathForPublic!,
349-
DtsRollupKind.PublicRelease);
350-
351-
this._generateTypingsFile(dtsRollupGenerator,
352-
this.actualConfig.dtsRollup.dtsFilePathForPreview!,
353-
DtsRollupKind.PreviewRelease);
354-
355-
this._generateTypingsFile(dtsRollupGenerator,
356-
this.actualConfig.dtsRollup.dtsFilePathForInternal!,
357-
DtsRollupKind.InternalRelease);
358-
}
348+
this._generateRollupDtsFiles(context);
359349

360350
if (this._localBuild) {
361351
// For a local build, fail if there were errors (but ignore warnings)
@@ -366,16 +356,83 @@ export class Extractor {
366356
}
367357
}
368358

369-
private _generateTypingsFile(dtsRollupGenerator: DtsRollupGenerator,
370-
dtsFilePath: string, dtsKind: DtsRollupKind): void {
371-
const dtsFilename: string = path.resolve(this._absoluteRootFolder,
372-
this.actualConfig.dtsRollup!.outputFolder, dtsFilePath);
359+
private _generateRollupDtsFiles(context: ExtractorContext): void {
360+
const dtsRollup: IExtractorDtsRollupConfig = this.actualConfig.dtsRollup!;
361+
if (dtsRollup.enabled) {
362+
let mainDtsRollupPath: string = dtsRollup.mainDtsRollupPath!;
363+
364+
if (!mainDtsRollupPath) {
365+
// If the mainDtsRollupPath is not specified, then infer it from the package.json file
366+
if (!context.packageJson.typings) {
367+
this._monitoredLogger.logError('Either the "mainDtsRollupPath" setting must be specified,'
368+
+ ' or else the package.json file must contain a "typings" field.');
369+
return;
370+
}
371+
372+
// Resolve the "typings" field relative to package.json itself
373+
const resolvedTypings: string = path.resolve(context.packageFolder, context.packageJson.typings);
374+
375+
if (dtsRollup.trimming) {
376+
if (!Path.isUnder(resolvedTypings, dtsRollup.publishFolderForInternal!)) {
377+
this._monitoredLogger.logError('The "mainDtsRollupPath" setting was not specified.'
378+
+ ' In this case, the package.json "typings" field must point to a file under'
379+
+ ' the "publishFolderForInternal": ' + dtsRollup.publishFolderForInternal!);
380+
return;
381+
}
382+
mainDtsRollupPath = path.relative(dtsRollup.publishFolderForInternal!, resolvedTypings);
383+
} else {
384+
if (!Path.isUnder(resolvedTypings, dtsRollup.publishFolder!)) {
385+
this._monitoredLogger.logError('The "mainDtsRollupPath" setting was not specified.'
386+
+ ' In this case, the package.json "typings" field must point to a file under'
387+
+ ' the "publishFolder": ' + dtsRollup.publishFolder!);
388+
return;
389+
}
390+
mainDtsRollupPath = path.relative(dtsRollup.publishFolder!, resolvedTypings);
391+
}
392+
393+
this._monitoredLogger.logVerbose(`The "mainDtsRollupPath" setting was inferred'
394+
+ ' from package.json: ${mainDtsRollupPath}`);
395+
} else {
396+
this._monitoredLogger.logVerbose(`The "mainDtsRollupPath" is: ${mainDtsRollupPath}`);
397+
398+
if (!path.isAbsolute(mainDtsRollupPath)) {
399+
this._monitoredLogger.logError('The "mainDtsRollupPath" setting must be a relative path'
400+
+ ' that can be combined with one of the "publishFolder" settings.');
401+
return;
402+
}
403+
}
404+
405+
const dtsRollupGenerator: DtsRollupGenerator = new DtsRollupGenerator(context);
406+
dtsRollupGenerator.analyze();
407+
408+
if (dtsRollup.trimming) {
409+
this._generateRollupDtsFile(dtsRollupGenerator,
410+
path.resolve(context.packageFolder, dtsRollup.publishFolderForPublic!, mainDtsRollupPath),
411+
DtsRollupKind.PublicRelease);
412+
413+
this._generateRollupDtsFile(dtsRollupGenerator,
414+
path.resolve(context.packageFolder, dtsRollup.publishFolderForBeta!, mainDtsRollupPath),
415+
DtsRollupKind.BetaRelease);
416+
417+
this._generateRollupDtsFile(dtsRollupGenerator,
418+
path.resolve(context.packageFolder, dtsRollup.publishFolderForInternal!, mainDtsRollupPath),
419+
DtsRollupKind.InternalRelease);
420+
} else {
421+
this._generateRollupDtsFile(dtsRollupGenerator,
422+
path.resolve(context.packageFolder, dtsRollup.publishFolder!, mainDtsRollupPath),
423+
DtsRollupKind.InternalRelease); // (no trimming)
424+
}
425+
}
426+
}
427+
428+
private _generateRollupDtsFile(dtsRollupGenerator: DtsRollupGenerator, mainDtsRollupFullPath: string,
429+
dtsKind: DtsRollupKind): void {
373430

374-
this._monitoredLogger.logVerbose(`Writing package typings: ${dtsFilename}`);
431+
this._monitoredLogger.logVerbose(`Writing package typings: ${mainDtsRollupFullPath}`);
375432

376-
fsx.mkdirsSync(path.dirname(dtsFilename));
433+
fsx.mkdirsSync(path.dirname(mainDtsRollupFullPath));
377434

378-
dtsRollupGenerator.writeTypingsFile(dtsFilename, dtsKind);
435+
dtsRollupGenerator.writeTypingsFile(mainDtsRollupFullPath, dtsKind);
379436
}
380437

381438
private _getShortFilePath(absolutePath: string): string {

‎apps/api-extractor/src/extractor/IExtractorConfig.ts‎

Lines changed: 45 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -178,58 +178,80 @@ export interface IExtractorApiJsonFileConfig {
178178
}
179179

180180
/**
181-
* Configures how the package typings (*.d.ts) will be generated.
181+
* Configures how the *.d.ts rollup files will be generated.
182+
*
182183
* @remarks
183-
* API Extractor can generate a single unified *.d.ts file that contains all
184-
* the exported typings for the package entry point. It can also remove
185-
* \@alpha \@beta \@internal definitions depending on the release type.
184+
* API Extractor can generate a consolidated *.d.ts file that contains all
185+
* the exported typings for the package entry point. It can also trim
186+
* \@alpha, \@beta, and \@internal definitions according to the release type.
186187
*
187188
* @beta
188189
*/
189190
export interface IExtractorDtsRollupConfig {
190191
/**
191-
* Whether to generate package typings. The default is false.
192+
* Whether to generate rollup *.d.ts files. The default is false.
192193
*/
193194
enabled: boolean;
194195

195196
/**
196-
* Specifies where the *.d.ts files should be written.
197+
* If "trimming" is false (the default), then a single *.d.ts rollup file will be generated in the
198+
* "publishFolder". If "trimming" is true, then three separate *.d.ts rollups will be
199+
* generated in "publishFolderForInternal", "publishFolderForBeta", and "publishFolderForPublic".
197200
*
198-
* The default value is "./dist"
201+
* @remarks
202+
* In either case, "mainDtsRollupPath" indicates the relative file path.
199203
*/
200-
outputFolder?: string;
204+
trimming?: boolean;
205+
206+
/**
207+
* This setting is only used if "trimming" is false.
208+
* It indicates the folder where "npm publish" will be run. The default value is "./dist".
209+
*/
210+
publishFolder?: string;
201211

202212
/**
203-
* Specifies the *.d.ts file path used for an internal release.
204-
* The default value is "index-internal.d.ts".
213+
* This setting is only used if "trimming" is true.
214+
* It indicates the folder where "npm publish" will be run for an internal release.
215+
* The default value is "./dist/internal".
205216
*
206217
* @remarks
207-
* If the path is not an absolute path, it will be resolved relative to the outputFolder.
208-
* This output file will contain all definitions that are reachable from the entry point.
218+
* An internal release will contain all definitions that are reachable from the entry point.
209219
*/
210-
dtsFilePathForInternal?: string;
220+
publishFolderForInternal?: string;
211221

212222
/**
213-
* Specifies the output filename for a preview release.
214-
* The default value is "index-preview.d.ts".
223+
* This setting is only used if "trimming" is true.
224+
* It indicates the folder where "npm publish" will be run for a beta release.
225+
* The default value is "./dist/beta".
215226
*
216227
* @remarks
217-
* If the path is not an absolute path, it will be resolved relative to the outputFolder.
218-
* This output file will contain all definitions that are reachable from the entry point,
228+
* A beta release will contain all definitions that are reachable from the entry point,
219229
* except definitions marked as \@alpha or \@internal.
220230
*/
221-
dtsFilePathForPreview?: string;
231+
publishFolderForBeta?: string;
222232

223233
/**
224-
* Specifies the output filename for a public release.
225-
* The default value is "index-public.d.ts".
234+
* This setting is only used if "trimming" is true.
235+
* It indicates the folder where "npm publish" will be run for a public release.
236+
* The default value is "./dist/public".
226237
*
227238
* @remarks
228-
* If the path is not an absolute path, it will be resolved relative to the outputFolder.
229-
* This output file will contain all definitions that are reachable from the entry point,
239+
* A public release will contain all definitions that are reachable from the entry point,
230240
* except definitions marked as \@beta, \@alpha, or \@internal.
231241
*/
232-
dtsFilePathForPublic?: string;
242+
publishFolderForPublic?: string;
243+
244+
/**
245+
* Specifies the relative path for the *.d.ts rollup file to be generated for the
246+
* package's main entry point. The default value is an empty string, which causes
247+
* the path to be automatically inferred from the "typings" field of the project's
248+
* package.json file.
249+
*
250+
* @remarks
251+
* If specified, the value must be a relative path that can be combined with one of
252+
* the publish folder settings.
253+
*/
254+
mainDtsRollupPath?: string;
233255
}
234256

235257
/**

‎apps/api-extractor/src/extractor/api-extractor-defaults.json‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,14 @@
2828

2929
"dtsRollup": {
3030
"enabled": false,
31-
"outputFolder": "./dist",
32-
"dtsFilePathForInternal": "index-internal.d.ts",
33-
"dtsFilePathForPreview": "index-preview.d.ts",
34-
"dtsFilePathForPublic": "index-public.d.ts"
31+
"trimming": false,
32+
33+
"publishFolder": "./dist",
34+
35+
"publishFolderForInternal": "./dist/internal",
36+
"publishFolderForBeta": "./dist/beta",
37+
"publishFolderForPublic": "./dist/public",
38+
39+
"mainDtsRollupPath": ""
3540
}
3641
}

0 commit comments

Comments
 (0)