/
converter.ts
497 lines (440 loc) · 16.6 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
import * as ts from "typescript";
import * as _ from "lodash";
import * as assert from "assert";
import { resolve } from "path";
import { Application } from "../application";
import { Type, ProjectReflection, ReflectionKind } from "../models/index";
import { Context } from "./context";
import { ConverterComponent } from "./components";
import { Component, ChildableComponent } from "../utils/component";
import { BindOption, normalizePath } from "../utils";
import { convertType } from "./types";
import { ConverterEvents } from "./converter-events";
import { convertSymbol } from "./symbols";
import { relative } from "path";
import { getCommonDirectory } from "../utils/fs";
import { createMinimatch } from "../utils/paths";
import { IMinimatch } from "minimatch";
import { hasAllFlags, hasAnyFlag } from "../utils/enum";
import { resolveAliasedSymbol } from "./utils/symbols";
/**
* 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
> {
/**
* The human readable name of the project. Used within the templates to set the title of the document.
*/
@BindOption("name")
name!: string;
@BindOption("externalPattern")
externalPattern!: string[];
private externalPatternCache?: IMinimatch[];
@BindOption("excludeExternals")
excludeExternals!: boolean;
@BindOption("excludeNotDocumented")
excludeNotDocumented!: boolean;
@BindOption("excludePrivate")
excludePrivate!: boolean;
@BindOption("excludeProtected")
excludeProtected!: boolean;
/**
* General events
*/
/**
* Triggered when the converter begins converting a project.
* The listener should implement [[IConverterCallback]].
* @event
*/
static readonly EVENT_BEGIN = ConverterEvents.BEGIN;
/**
* Triggered when the converter has finished converting a project.
* The listener should implement [[IConverterCallback]].
* @event
*/
static readonly EVENT_END = ConverterEvents.END;
/**
* Factory events
*/
/**
* Triggered when the converter has created a declaration reflection.
* The listener should implement [[IConverterNodeCallback]].
* @event
*/
static readonly EVENT_CREATE_DECLARATION =
ConverterEvents.CREATE_DECLARATION;
/**
* Triggered when the converter has created a signature reflection.
* The listener should implement [[IConverterNodeCallback]].
* @event
*/
static readonly EVENT_CREATE_SIGNATURE = ConverterEvents.CREATE_SIGNATURE;
/**
* Triggered when the converter has created a parameter reflection.
* The listener should implement [[IConverterNodeCallback]].
* @event
*/
static readonly EVENT_CREATE_PARAMETER = ConverterEvents.CREATE_PARAMETER;
/**
* Triggered when the converter has created a type parameter reflection.
* The listener should implement [[IConverterNodeCallback]].
* @event
*/
static readonly EVENT_CREATE_TYPE_PARAMETER =
ConverterEvents.CREATE_TYPE_PARAMETER;
/**
* Resolve events
*/
/**
* Triggered when the converter begins resolving a project.
* The listener should implement [[IConverterCallback]].
* @event
*/
static readonly EVENT_RESOLVE_BEGIN = ConverterEvents.RESOLVE_BEGIN;
/**
* Triggered when the converter resolves a reflection.
* The listener should implement [[IConverterResolveCallback]].
* @event
*/
static readonly EVENT_RESOLVE = ConverterEvents.RESOLVE;
/**
* Triggered when the converter has finished resolving a project.
* The listener should implement [[IConverterCallback]].
* @event
*/
static readonly EVENT_RESOLVE_END = ConverterEvents.RESOLVE_END;
/**
* Compile the given source files and create a project reflection for them.
*
* @param entryPoints the entry points of this program.
* @param program the program to document that has already been type checked.
*/
convert(
entryPoints: readonly string[],
programs: ts.Program | readonly ts.Program[]
): ProjectReflection {
programs = programs instanceof Array ? programs : [programs];
this.externalPatternCache = void 0;
const project = new ProjectReflection(this.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) {
convertSymbol(context, symbol);
}
/**
* 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
): Type {
return convertType(context, node);
}
/** @internal */
getNodesForSymbol(symbol: ts.Symbol, kind: ReflectionKind) {
const wantedKinds: ts.SyntaxKind[] = {
[ReflectionKind.Project]: [ts.SyntaxKind.SourceFile],
[ReflectionKind.Module]: [ts.SyntaxKind.SourceFile],
[ReflectionKind.Namespace]: [
ts.SyntaxKind.ModuleDeclaration,
ts.SyntaxKind.SourceFile,
],
[ReflectionKind.Enum]: [ts.SyntaxKind.EnumDeclaration],
[ReflectionKind.EnumMember]: [ts.SyntaxKind.EnumMember],
[ReflectionKind.Variable]: [ts.SyntaxKind.VariableDeclaration],
[ReflectionKind.Function]: [
ts.SyntaxKind.FunctionDeclaration,
ts.SyntaxKind.VariableDeclaration,
],
[ReflectionKind.Class]: [ts.SyntaxKind.ClassDeclaration],
[ReflectionKind.Interface]: [
ts.SyntaxKind.InterfaceDeclaration,
ts.SyntaxKind.JSDocTypedefTag,
],
[ReflectionKind.Constructor]: [ts.SyntaxKind.Constructor],
[ReflectionKind.Property]: [
ts.SyntaxKind.PropertyDeclaration,
ts.SyntaxKind.PropertySignature,
ts.SyntaxKind.JSDocPropertyTag,
],
[ReflectionKind.Method]: [
ts.SyntaxKind.MethodDeclaration,
ts.SyntaxKind.PropertyDeclaration,
ts.SyntaxKind.PropertySignature,
],
[ReflectionKind.CallSignature]: [
ts.SyntaxKind.FunctionDeclaration,
ts.SyntaxKind.VariableDeclaration,
ts.SyntaxKind.MethodDeclaration,
ts.SyntaxKind.MethodDeclaration,
ts.SyntaxKind.PropertyDeclaration,
ts.SyntaxKind.PropertySignature,
ts.SyntaxKind.CallSignature,
],
[ReflectionKind.IndexSignature]: [ts.SyntaxKind.IndexSignature],
[ReflectionKind.ConstructorSignature]: [
ts.SyntaxKind.ConstructSignature,
],
[ReflectionKind.Parameter]: [ts.SyntaxKind.Parameter],
[ReflectionKind.TypeLiteral]: [ts.SyntaxKind.TypeLiteral],
[ReflectionKind.TypeParameter]: [ts.SyntaxKind.TypeParameter],
[ReflectionKind.Accessor]: [
ts.SyntaxKind.GetAccessor,
ts.SyntaxKind.SetAccessor,
],
[ReflectionKind.GetSignature]: [ts.SyntaxKind.GetAccessor],
[ReflectionKind.SetSignature]: [ts.SyntaxKind.SetAccessor],
[ReflectionKind.ObjectLiteral]: [
ts.SyntaxKind.ObjectLiteralExpression,
],
[ReflectionKind.TypeAlias]: [
ts.SyntaxKind.TypeAliasDeclaration,
ts.SyntaxKind.JSDocTypedefTag,
],
[ReflectionKind.Event]: [], /// this needs to go away
[ReflectionKind.Reference]: [
ts.SyntaxKind.NamespaceExport,
ts.SyntaxKind.ExportSpecifier,
],
}[kind];
const declarations = symbol.getDeclarations() ?? [];
return declarations.filter((d) => wantedKinds.includes(d.kind));
}
/**
* 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 string[], context: Context) {
const baseDir = getCommonDirectory(entryPoints);
const entries: {
file: string;
sourceFile: ts.SourceFile;
program: ts.Program;
context?: Context;
}[] = [];
entryLoop: for (const file of entryPoints.map(normalizePath)) {
for (const program of context.programs) {
const sourceFile = program.getSourceFile(file);
if (sourceFile) {
entries.push({ file, sourceFile, program });
continue entryLoop;
}
}
this.application.logger.warn(
`Unable to locate entry point: ${file}`
);
}
for (const entry of entries) {
context.setActiveProgram(entry.program);
entry.context = this.convertExports(
context,
entry.sourceFile,
entryPoints,
getModuleName(resolve(entry.file), baseDir)
);
}
for (const { sourceFile, context } of entries) {
// active program is already set on context
assert(context);
this.convertReExports(context, sourceFile);
}
context.setActiveProgram(undefined);
}
private convertExports(
context: Context,
node: ts.SourceFile,
entryPoints: readonly string[],
entryName: string
) {
const symbol = getSymbolForModuleLike(context, node);
let moduleContext: Context;
if (entryPoints.length === 1) {
// 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.trigger(
Converter.EVENT_CREATE_DECLARATION,
context.project,
node
);
moduleContext = context;
} else {
const reflection = context.createDeclarationReflection(
ReflectionKind.Module,
symbol,
void 0,
entryName
);
context.finalizeDeclarationReflection(reflection, symbol);
moduleContext = context.withScope(reflection);
}
for (const exp of getExports(context, node, symbol).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);
}
/** @internal */
shouldIgnore(symbol: ts.Symbol, checker: ts.TypeChecker) {
if (
this.excludeNotDocumented &&
// If the enum is included, we should include members even if not documented.
!hasAllFlags(symbol.flags, ts.SymbolFlags.EnumMember) &&
resolveAliasedSymbol(symbol, checker).getDocumentationComment(
checker
).length === 0
) {
return true;
}
if (!this.excludeExternals) {
return false;
}
return this.isExternal(symbol);
}
/** @internal */
isExternal(symbol: ts.Symbol) {
this.externalPatternCache ??= createMinimatch(this.externalPattern);
for (const node of symbol.getDeclarations() ?? []) {
if (
this.externalPatternCache.some((p) =>
p.match(node.getSourceFile().fileName)
)
) {
return true;
}
}
return false;
}
}
function getModuleName(fileName: string, baseDir: string) {
return normalizePath(relative(baseDir, fileName)).replace(
/(\/index)?(\.d)?\.[tj]sx?$/,
""
);
}
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 | ts.ModuleBlock,
symbol: ts.Symbol | undefined
): 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.
return [exportEq].concat(
context.checker
.getExportsOfModule(symbol!)
.filter(
(s) =>
!hasAnyFlag(
s.flags,
ts.SymbolFlags.Prototype | ts.SymbolFlags.Value
)
)
);
}
if (symbol) {
return context.checker
.getExportsOfModule(symbol)
.filter((s) => !hasAllFlags(s.flags, ts.SymbolFlags.Prototype));
}
// Global file with no inferred top level symbol, get all symbols declared in this file.
const sourceFile = node.getSourceFile();
const globalSymbols = context.checker
.getSymbolsInScope(node, ts.SymbolFlags.ModuleMember)
.filter((s) =>
s.getDeclarations()?.some((d) => d.getSourceFile() === sourceFile)
);
return globalSymbols;
}
function isDirectExport(symbol: ts.Symbol, file: ts.SourceFile): boolean {
return (
symbol
.getDeclarations()
?.every((decl) => decl.getSourceFile() === file) ?? false
);
}