/
converter.ts
629 lines (556 loc) · 20.3 KB
/
converter.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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
import * as ts from "typescript";
import type { Application } from "../application";
import {
Comment,
CommentDisplayPart,
ProjectReflection,
Reflection,
ReflectionKind,
SomeType,
} from "../models/index";
import { Context } from "./context";
import { ConverterComponent } from "./components";
import { Component, ChildableComponent } from "../utils/component";
import { BindOption, MinimalSourceFile, readFile } from "../utils";
import { convertType } from "./types";
import { ConverterEvents } from "./converter-events";
import { convertSymbol } from "./symbols";
import { createMinimatch, matchesAny } from "../utils/paths";
import type { Minimatch } from "minimatch";
import { hasAllFlags, hasAnyFlag } from "../utils/enum";
import type { DocumentationEntryPoint } from "../utils/entry-point";
import { CommentParserConfig, getComment } from "./comments";
import type {
CommentStyle,
ValidationOptions,
} from "../utils/options/declaration";
import { parseComment } from "./comments/parser";
import { lexCommentString } from "./comments/rawLexer";
import { resolvePartLinks, resolveLinks } from "./comments/linkResolver";
import type { DeclarationReference } from "./comments/declarationReference";
/**
* Compiles source files using TypeScript and converts compiler symbols to reflections.
*/
@Component({
name: "converter",
internal: true,
childClass: ConverterComponent,
})
export class Converter extends ChildableComponent<
Application,
ConverterComponent
> {
/** @internal */
@BindOption("externalPattern")
externalPattern!: string[];
private externalPatternCache?: Minimatch[];
private excludeCache?: Minimatch[];
/** @internal */
@BindOption("excludeExternals")
excludeExternals!: boolean;
/** @internal */
@BindOption("excludeNotDocumented")
excludeNotDocumented!: boolean;
/** @internal */
@BindOption("excludePrivate")
excludePrivate!: boolean;
/** @internal */
@BindOption("excludeProtected")
excludeProtected!: boolean;
/** @internal */
@BindOption("commentStyle")
commentStyle!: CommentStyle;
/** @internal */
@BindOption("validation")
validation!: ValidationOptions;
/** @internal */
@BindOption("externalSymbolLinkMappings")
externalSymbolLinkMappings!: Record<string, Record<string, string>>;
private _config?: CommentParserConfig;
private _externalSymbolResolvers: Array<
(ref: DeclarationReference) => string | undefined
> = [];
get config(): CommentParserConfig {
return this._config || this._buildCommentParserConfig();
}
/**
* General events
*/
/**
* Triggered when the converter begins converting a project.
* The listener will be given a {@link Context} object.
* @event
*/
static readonly EVENT_BEGIN = ConverterEvents.BEGIN;
/**
* Triggered when the converter has finished converting a project.
* The listener will be given a {@link Context} object.
* @event
*/
static readonly EVENT_END = ConverterEvents.END;
/**
* Factory events
*/
/**
* Triggered when the converter has created a declaration reflection.
* The listener will be given {@link Context} and a {@link DeclarationReflection}.
* @event
*/
static readonly EVENT_CREATE_DECLARATION =
ConverterEvents.CREATE_DECLARATION;
/**
* Triggered when the converter has created a signature reflection.
* The listener will be given {@link Context}, {@link SignatureReflection} | {@link ProjectReflection} and
* `ts.SignatureDeclaration | ts.IndexSignatureDeclaration | ts.JSDocSignature | undefined`
* @event
*/
static readonly EVENT_CREATE_SIGNATURE = ConverterEvents.CREATE_SIGNATURE;
/**
* Triggered when the converter has created a parameter reflection.
* The listener will be given {@link Context}, {@link ParameterReflection} and a `ts.Node?`
* @event
*/
static readonly EVENT_CREATE_PARAMETER = ConverterEvents.CREATE_PARAMETER;
/**
* Triggered when the converter has created a type parameter reflection.
* The listener will be given {@link Context} and a {@link TypeParameterReflection}
* @event
*/
static readonly EVENT_CREATE_TYPE_PARAMETER =
ConverterEvents.CREATE_TYPE_PARAMETER;
/**
* Resolve events
*/
/**
* Triggered when the converter begins resolving a project.
* The listener will be given {@link Context}.
* @event
*/
static readonly EVENT_RESOLVE_BEGIN = ConverterEvents.RESOLVE_BEGIN;
/**
* Triggered when the converter resolves a reflection.
* The listener will be given {@link Context} and a {@link Reflection}.
* @event
*/
static readonly EVENT_RESOLVE = ConverterEvents.RESOLVE;
/**
* Triggered when the converter has finished resolving a project.
* The listener will be given {@link Context}.
* @event
*/
static readonly EVENT_RESOLVE_END = ConverterEvents.RESOLVE_END;
constructor(owner: Application) {
super(owner);
this.addUnknownSymbolResolver((ref) => {
// Require global links, matching local ones will likely hide mistakes where the
// user meant to link to a local type.
if (ref.resolutionStart !== "global" || !ref.symbolReference) {
return;
}
const modLinks =
this.externalSymbolLinkMappings[ref.moduleSource ?? "global"];
if (typeof modLinks !== "object") {
return;
}
let name = "";
if (ref.symbolReference.path) {
name += ref.symbolReference.path.map((p) => p.path).join(".");
}
if (ref.symbolReference.meaning) {
name += ":" + ref.symbolReference.meaning;
}
if (typeof modLinks[name] === "string") {
return modLinks[name];
}
if (typeof modLinks["*"] === "string") {
return modLinks["*"];
}
});
}
/**
* Compile the given source files and create a project reflection for them.
*/
convert(
entryPoints: readonly DocumentationEntryPoint[]
): ProjectReflection {
const programs = entryPoints.map((e) => e.program);
this.externalPatternCache = void 0;
const project = new ProjectReflection(
this.application.options.getValue("name")
);
const context = new Context(this, programs, project);
this.trigger(Converter.EVENT_BEGIN, context);
this.compile(entryPoints, context);
this.resolve(context);
// This should only do anything if a plugin does something bad.
project.removeDanglingReferences();
this.trigger(Converter.EVENT_END, context);
return project;
}
/** @internal */
convertSymbol(
context: Context,
symbol: ts.Symbol,
exportSymbol?: ts.Symbol
) {
convertSymbol(context, symbol, exportSymbol);
}
/**
* Convert the given TypeScript type into its TypeDoc type reflection.
*
* @param context The context object describing the current state the converter is in.
* @param referenceTarget The target to be used to attempt to resolve reference types
* @returns The TypeDoc type reflection representing the given node and type.
* @internal
*/
convertType(
context: Context,
node: ts.TypeNode | ts.Type | undefined
): SomeType {
return convertType(context, node);
}
/**
* Parse the given file into a comment. Intended to be used with markdown files.
*/
parseRawComment(file: MinimalSourceFile) {
return parseComment(
lexCommentString(file.text),
this.config,
file,
this.application.logger
);
}
/**
* Adds a new resolver that the theme can use to try to figure out how to link to a symbol declared
* by a third-party library which is not included in the documentation.
*
* The resolver function will be passed a declaration reference which it can attempt to resolve. If
* resolution fails, the function should return undefined.
*
* Note: This will be used for both references to types declared in node_modules (in which case the
* reference passed will have the `moduleSource` set and the `symbolReference` will navigate via `.`)
* and user defined \{\@link\} tags which cannot be resolved.
* @since 0.22.14
*/
addUnknownSymbolResolver(
resolver: (ref: DeclarationReference) => string | undefined
): void {
this._externalSymbolResolvers.push(resolver);
}
/** @internal */
resolveExternalLink(ref: DeclarationReference): string | undefined {
for (const resolver of this._externalSymbolResolvers) {
const resolved = resolver(ref);
if (resolved) return resolved;
}
}
resolveLinks(comment: Comment, owner: Reflection): void;
resolveLinks(
parts: readonly CommentDisplayPart[],
owner: Reflection
): CommentDisplayPart[];
resolveLinks(
comment: Comment | readonly CommentDisplayPart[],
owner: Reflection
): CommentDisplayPart[] | undefined {
if (comment instanceof Comment) {
resolveLinks(
comment,
owner,
this.validation,
this.owner.logger,
(ref) => this.resolveExternalLink(ref)
);
} else {
let warned = false;
const warn = () => {
if (!warned) {
warned = true;
this.application.logger.warn(
`${owner.name}: Comment [[target]] style links are deprecated and will be removed in 0.24`
);
}
};
return resolvePartLinks(
owner,
comment,
warn,
this.validation,
this.owner.logger,
(ref) => this.resolveExternalLink(ref)
);
}
}
/**
* Compile the files within the given context and convert the compiler symbols to reflections.
*
* @param context The context object describing the current state the converter is in.
* @returns An array containing all errors generated by the TypeScript compiler.
*/
private compile(
entryPoints: readonly DocumentationEntryPoint[],
context: Context
) {
const entries = entryPoints.map((e) => {
return {
entryPoint: e,
context: undefined as Context | undefined,
};
});
entries.forEach((e) => {
context.setActiveProgram(e.entryPoint.program);
e.context = this.convertExports(
context,
e.entryPoint,
entries.length === 1
);
});
for (const { entryPoint, context } of entries) {
// active program is already set on context
// if we don't have a context, then this entry point is being ignored
if (context) {
this.convertReExports(context, entryPoint.sourceFile);
}
}
context.setActiveProgram(undefined);
}
private convertExports(
context: Context,
entryPoint: DocumentationEntryPoint,
singleEntryPoint: boolean
) {
const node = entryPoint.sourceFile;
const entryName = entryPoint.displayName;
const symbol = getSymbolForModuleLike(context, node);
let moduleContext: Context;
if (singleEntryPoint) {
// Special case for when we're giving a single entry point, we don't need to
// create modules for each entry. Register the project as this module.
context.project.registerReflection(context.project, symbol);
context.project.comment =
symbol &&
getComment(
symbol,
context.project.kind,
this.config,
this.application.logger,
this.commentStyle
);
context.trigger(
Converter.EVENT_CREATE_DECLARATION,
context.project
);
moduleContext = context;
} else {
const reflection = context.createDeclarationReflection(
ReflectionKind.Module,
symbol,
void 0,
entryName
);
if (entryPoint.readmeFile) {
const readme = readFile(entryPoint.readmeFile);
const comment = this.parseRawComment(
new MinimalSourceFile(readme, entryPoint.readmeFile)
);
if (comment.blockTags.length || comment.modifierTags.size) {
const ignored = [
...comment.blockTags.map((tag) => tag.tag),
...comment.modifierTags,
];
context.logger.warn(
`Block and modifier tags will be ignored within the readme:\n\t${ignored.join(
"\n\t"
)}`
);
}
reflection.readme = comment.summary;
}
reflection.version = entryPoint.version;
context.finalizeDeclarationReflection(reflection);
moduleContext = context.withScope(reflection);
}
const allExports = getExports(context, node, symbol);
for (const exp of allExports.filter((exp) =>
isDirectExport(context.resolveAliasedSymbol(exp), node)
)) {
convertSymbol(moduleContext, exp);
}
return moduleContext;
}
private convertReExports(moduleContext: Context, node: ts.SourceFile) {
for (const exp of getExports(
moduleContext,
node,
moduleContext.project.getSymbolFromReflection(moduleContext.scope)
).filter(
(exp) =>
!isDirectExport(moduleContext.resolveAliasedSymbol(exp), node)
)) {
convertSymbol(moduleContext, exp);
}
}
/**
* Resolve the project within the given context.
*
* @param context The context object describing the current state the converter is in.
* @returns The final project reflection.
*/
private resolve(context: Context): void {
this.trigger(Converter.EVENT_RESOLVE_BEGIN, context);
const project = context.project;
for (const reflection of Object.values(project.reflections)) {
this.trigger(Converter.EVENT_RESOLVE, context, reflection);
}
this.trigger(Converter.EVENT_RESOLVE_END, context);
}
/**
* Used to determine if we should immediately bail when creating a reflection.
* Note: This should not be used for excludeNotDocumented because we don't have enough
* information at this point since comment discovery hasn't happened.
* @internal
*/
shouldIgnore(symbol: ts.Symbol) {
if (this.isExcluded(symbol)) {
return true;
}
return this.excludeExternals && this.isExternal(symbol);
}
private isExcluded(symbol: ts.Symbol) {
this.excludeCache ??= createMinimatch(
this.application.options.getValue("exclude")
);
const cache = this.excludeCache;
return (symbol.getDeclarations() ?? []).some((node) =>
matchesAny(cache, node.getSourceFile().fileName)
);
}
/** @internal */
isExternal(symbol: ts.Symbol) {
this.externalPatternCache ??= createMinimatch(this.externalPattern);
const cache = this.externalPatternCache;
return (symbol.getDeclarations() ?? []).some((node) =>
matchesAny(cache, node.getSourceFile().fileName)
);
}
private _buildCommentParserConfig() {
this._config = {
blockTags: new Set(this.application.options.getValue("blockTags")),
inlineTags: new Set(
this.application.options.getValue("inlineTags")
),
modifierTags: new Set(
this.application.options.getValue("modifierTags")
),
};
return this._config;
}
}
function getSymbolForModuleLike(
context: Context,
node: ts.SourceFile | ts.ModuleBlock
) {
const symbol = context.checker.getSymbolAtLocation(node) ?? node.symbol;
if (symbol) {
return symbol;
}
// This is a global file, get all symbols declared in this file...
// this isn't the best solution, it would be nice to have all globals given to a special
// "globals" file, but this is uncommon enough that I'm skipping it for now.
const sourceFile = node.getSourceFile();
const globalSymbols = context.checker
.getSymbolsInScope(node, ts.SymbolFlags.ModuleMember)
.filter((s) =>
s.getDeclarations()?.some((d) => d.getSourceFile() === sourceFile)
);
// Detect declaration files with declare module "foo" as their only export
// and lift that up one level as the source file symbol
if (
globalSymbols.length === 1 &&
globalSymbols[0]
.getDeclarations()
?.every(
(declaration) =>
ts.isModuleDeclaration(declaration) &&
ts.isStringLiteral(declaration.name)
)
) {
return globalSymbols[0];
}
}
function getExports(
context: Context,
node: ts.SourceFile,
symbol: ts.Symbol | undefined
): ts.Symbol[] {
let result: ts.Symbol[];
// The generated docs aren't great, but you really ought not be using
// this in the first place... so it's better than nothing.
const exportEq = symbol?.exports?.get("export=" as ts.__String);
if (exportEq) {
// JS users might also have exported types here.
// We need to filter for types because otherwise static methods can show up as both
// members of the export= class and as functions if a class is directly exported.
result = [exportEq].concat(
context.checker
.getExportsOfModule(symbol!)
.filter(
(s) =>
!hasAnyFlag(
s.flags,
ts.SymbolFlags.Prototype | ts.SymbolFlags.Value
)
)
);
} else if (symbol) {
result = context.checker
.getExportsOfModule(symbol)
.filter((s) => !hasAllFlags(s.flags, ts.SymbolFlags.Prototype));
if (result.length === 0) {
const globalDecl = node.statements.find(
(s) =>
ts.isModuleDeclaration(s) &&
s.flags & ts.NodeFlags.GlobalAugmentation
);
if (globalDecl) {
const globalSymbol = context.getSymbolAtLocation(globalDecl);
if (globalSymbol) {
result = context.checker
.getExportsOfModule(globalSymbol)
.filter((exp) =>
exp.declarations?.some(
(d) => d.getSourceFile() === node
)
);
}
}
}
} else {
// Global file with no inferred top level symbol, get all symbols declared in this file.
const sourceFile = node.getSourceFile();
result = context.checker
.getSymbolsInScope(node, ts.SymbolFlags.ModuleMember)
.filter((s) =>
s
.getDeclarations()
?.some((d) => d.getSourceFile() === sourceFile)
);
}
// Put symbols named "default" last, #1795
result.sort((a, b) => {
if (a.name === "default") {
return 1;
} else if (b.name === "default") {
return -1;
}
return 0;
});
return result;
}
function isDirectExport(symbol: ts.Symbol, file: ts.SourceFile): boolean {
return (
symbol
.getDeclarations()
?.every((decl) => decl.getSourceFile() === file) ?? false
);
}