-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.ts
More file actions
655 lines (592 loc) · 22.9 KB
/
main.ts
File metadata and controls
655 lines (592 loc) · 22.9 KB
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
import assert from 'node:assert';
import {
type Application,
Comment,
CommentTag,
type Context,
Converter,
DeclarationReflection,
IntersectionType,
IntrinsicType,
ParameterReflection,
PredicateType,
ReferenceType,
ReflectionFlag,
ReflectionKind,
ReflectionType,
Renderer,
SignatureReflection,
type SomeType,
UnionType,
} from 'typedoc';
import ts, { ModifierFlags, SymbolFlags } from 'typescript';
const excludeBaseTypes = ['LitElement', 'HTMLElement'];
export function load(app: Application) {
app.converter.on(
Converter.EVENT_CREATE_DECLARATION,
(context: Context, reflection: DeclarationReflection) => {
// Ignore types like `displayName` or `$$typeOf` and any of the old deprecated modules exported.
const isDeprecated =
reflection.comment?.blockTags?.length &&
reflection.comment?.blockTags.find((tag) => tag.tag === '@deprecated');
const isReactType = reflection.sources?.some((source) =>
source.fileName.endsWith('react/index.d.ts'),
);
if (isReactType || (reflection.name.endsWith('Module') && isDeprecated)) {
// We just remove them since we cannot set a custom filter to not create reflections for them afaik.
context.project.removeReflection(reflection);
}
if (
reflection.name?.startsWith('Igr') &&
reflection.escapedName &&
reflection.name !== reflection.escapedName
) {
reflection.implementationOf = ReferenceType.createResolvedReference(
reflection.escapedName,
reflection,
context.project,
);
}
// This renders the Alias for `PopoverPlacement` a bit better but still no like. Possibly add handling for aliases?
// if (reflection.name === "PopoverPlacement") {
// reflection.kind = ReflectionKind.TypeParameter;
// }
},
);
app.converter.on(
Converter.EVENT_CREATE_SIGNATURE,
(context: Context, reflection: SignatureReflection, sig: any, test: any) => {
// Each component generates a signature due to the nature for the react nodes. We use it to further process it correctly so members appear where we need them.
// A signature is a definition of a more complex type like a function that can have arguments/return type and etc. The other reflection type is a simple type.
if (
(reflection.type as any).qualifiedName === 'React.ReactNode' &&
context.scope instanceof DeclarationReflection
) {
const sourceFile = context.program.getSourceFile(
context.scope.sources ? context.scope.sources[0].fileName : '',
) as any;
sourceFile.symbol.exports.forEach((value: any, key: string) => {
if (!key.endsWith('Module')) {
const declaration = value.getDeclarations()?.find(ts.isVariableDeclaration);
const accessDeclaration = declaration ?? value.valueDeclaration;
const type = accessDeclaration
? context.checker.getTypeOfSymbolAtLocation(value, accessDeclaration)
: context.checker.getDeclaredTypeOfSymbol(value);
if (type.aliasTypeArguments) {
// The 1st element is the ref to the node of the component it pretty much implements or otherwise `elementClass` prop of `createComponent`.
parseTypeProperties(type.aliasTypeArguments[0], context);
// The 2nd element is the `events` prop of the `createComponent` method.
type.aliasTypeArguments[1].symbol?.members?.forEach(
(value: ts.Symbol, key: ts.__String) => {
createEventDeclaration(context, value);
},
);
// The 3rd element is for the `renderProps` prop of the `createComponent` method, but this is only declaration of them.
// Definition of them should be handled in the 1st part.
// Fill out "extendedTypes" section in TypeDoc with base types
extractBaseType(type.aliasTypeArguments[0], context, reflection);
// Save a reference to the wc component name for reference in case of deeper WC types being resolved.
reflection.implementationOf = ReferenceType.createResolvedReference(
type.aliasTypeArguments[0].symbol.name,
reflection,
context.project,
);
}
// Clear out component signature parameters, since they are only internal and we should already have processed them correctly.
reflection.parameters = undefined;
// No need to show sources for the root component reflection.
reflection.sources = undefined;
if (type.aliasTypeArguments) {
// Register symbolId for this component base type that comes from the webcomponents and points to its reflection.
// That way later on a link from example IgcSelectItemComponent(alias symbol) can be created to IgrSelectItem(the current context).
context.project.registerSymbolId(
context.scope,
context.createSymbolId(type.aliasTypeArguments[0].symbol),
);
}
}
});
}
},
);
app.converter.on(Converter.EVENT_RESOLVE_END, (context: Context) => {
// Maybe there is a better way to ignore everything from typescript except CustomEvent on init level?
for (const item of Object.values(context.project.reflections)) {
const reflection = item as DeclarationReflection;
const isTsType = reflection?.sources?.some((source: any) =>
source.fileName.endsWith('typescript/lib/lib.dom.d.ts'),
);
if (
isTsType &&
!(
(reflection.name === 'CustomEvent' && reflection.kind === ReflectionKind.Interface) ||
(reflection.parent?.name === 'CustomEvent' && reflection.name === 'detail')
)
) {
context.project.children?.length
? context.project.children[0].removeChild(reflection)
: null;
context.project.removeReflection(reflection);
}
// Clear out @link references in comments when parsing to json, because it results in circular deps.
if (reflection.comment?.summary) {
clearProps(reflection.comment.summary, 'parent');
}
}
// Shorten name since there's no need to show the full path to the destination folder.
for (const child of context.project.children || []) {
if (child.name.endsWith('lib.dom')) {
child.name = 'typescript';
}
}
});
app.converter.on(Converter.EVENT_END, (context: Context) => {
console.log('Converter finished!');
});
app.renderer.on(Renderer.EVENT_BEGIN_PAGE, (page: any) => {
// Filter out @fires tags for components, since they should be already processed and added as events.
if (page.model?.comment) {
page.model.comment.blockTags = page.model.comment.blockTags?.filter(
(commentTag: CommentTag) => commentTag.tag !== '@fires',
);
}
// Force camelCase on the links for props. This is to be consistent with other docs.
if (page?.model?.children?.length && page.model.children[0].url?.includes('.html#')) {
for (const childDeclaration of page.model.children) {
if (childDeclaration.url.includes('.html#')) {
const urlParts = childDeclaration.url.split('#');
childDeclaration.anchor = childDeclaration.name;
childDeclaration.url = `${urlParts[0]}#${childDeclaration.name}`;
}
}
}
});
}
function parseTypeProperties(type: any, context: Context) {
if (excludeBaseTypes.includes(type.symbol?.name)) {
return;
}
const props = type.declaredProperties || type.symbol?.members;
props?.forEach((value: ts.Symbol, key: ts.__String) => {
const memberDeclaration = value?.declarations?.length
? (value.declarations[0] as any)
: ((value.valueDeclaration as any) ?? null);
const modifiers = memberDeclaration
? ts.getCombinedModifierFlags(memberDeclaration)
: ModifierFlags.None;
if (
!key.toString().startsWith('_') &&
(modifiers === ModifierFlags.None ||
modifiers === ModifierFlags.Public ||
modifiers === ModifierFlags.Static)
) {
let reflectionKind = ReflectionKind.Property;
let category = 'Other';
switch (value.flags) {
case SymbolFlags.GetAccessor:
category = 'Accessors';
reflectionKind = ReflectionKind.Accessor;
break;
case SymbolFlags.Method:
category = 'Methods';
reflectionKind = ReflectionKind.Method;
break;
case SymbolFlags.Accessor:
case SymbolFlags.Property:
category = 'Properties';
}
if (value.flags.toString() === '16777220') {
// For some reason optional properties get flagged to this number, even though the optional is 16777216
category = 'Properties';
}
if (category === 'Other') {
// Other types we just ignore creating.
return;
}
createMemberDeclaration(context, value, reflectionKind, category);
}
});
if (type.resolvedBaseTypes) {
for (const baseType of type.resolvedBaseTypes) {
parseTypeProperties(baseType, context);
}
}
}
function clearProps(inObj: any, propName: string) {
if (!inObj || typeof inObj !== 'object') {
return;
}
if (Array.isArray(inObj)) {
for (let i = 0; i < inObj.length; i++) {
clearProps(inObj[i], propName);
}
} else {
const props = Object.getOwnPropertyNames(inObj);
for (const prop of props) {
if (prop === propName) {
delete inObj[prop];
} else {
clearProps(inObj[prop], propName);
}
}
}
}
function createMemberDeclaration(
context: Context,
value: ts.Symbol,
reflectionKind: ReflectionKind,
category: string,
) {
const declaration = value.getDeclarations()?.[0] as any;
// Reflections automatically get added using this method to the context provided as parent.
const reflection = context.createDeclarationReflection(reflectionKind, value, undefined, void 0);
const type = context.checker.getTypeOfSymbol(value);
reflection.type = context.converter.convertType(context.withScope(reflection), type);
if (reflectionKind === ReflectionKind.Method) {
// Create signatures that describe methods in greater detail compared to a simple type in the reflection.
// One should be enough but maybe there could be multiple?
for (const signature of type.getCallSignatures()) {
createSignature(
context.withScope(reflection),
ReflectionKind.CallSignature,
signature,
value,
);
}
}
// To Do: Better handling of default values?
reflection.defaultValue = declaration?.initializer
? (declaration as any).initializer.getText()
: undefined;
const categoryTag = new CommentTag('@category', [{ kind: 'text', text: category }]);
if (reflection.comment) {
reflection.comment.blockTags = [categoryTag];
} else {
const comment = declaration?.jsDoc?.length ? declaration?.jsDoc[0].comment : '';
reflection.comment = new Comment([{ kind: 'text', text: comment }], [categoryTag]);
}
// For some reason everything by default is static.
reflection.setFlag(ReflectionFlag.Static, false);
return reflection;
}
function createEventDeclaration(context: Context, value: ts.Symbol) {
const declaration = value.getDeclarations()?.find(ts.isVariableDeclaration) as any;
const reflection = context.createDeclarationReflection(
ReflectionKind.SetSignature,
value,
undefined,
void 0,
);
const typeReflection = new DeclarationReflection(
'__type',
ReflectionKind.TypeLiteral,
reflection,
);
// Mock signature reflection for the events, since their type is a function.
const eventSignature = new SignatureReflection(
'__type',
ReflectionKind.CallSignature,
typeReflection,
);
// Mark all events to return void.
eventSignature.type = new IntrinsicType('void');
// Create the `args` parameter reflection and get its type from the value node.
const paramRefl = new ParameterReflection('args', ReflectionKind.Parameter, eventSignature);
const symbolType = context.checker.getTypeOfSymbol(value);
const eventDefinitionType = context.converter.convertType(
context.withScope(reflection),
symbolType,
) as any;
const argsType = eventDefinitionType?.typeArguments?.length
? eventDefinitionType.typeArguments[0]
: eventDefinitionType;
paramRefl.type = argsType;
eventSignature.parameters = [paramRefl];
const categoryTag = new CommentTag('@category', [{ kind: 'text', text: 'Events' }]);
if (reflection.comment) {
reflection.comment.blockTags = [categoryTag];
} else {
// Get the event description from the @fires tag of the parent component and just extract the text.
const parentComment = context.scope.comment?.blockTags
.filter((tag) => tag.tag === '@fires')
.map((tag) => tag.content[0].text)
.find((tag) => tag.startsWith(`igc${reflection.name.substring(2)}`))
?.split('-')[1]
.trim();
const comment = declaration?.jsDoc?.length ? declaration?.jsDoc[0].comment : parentComment;
reflection.comment = new Comment([{ kind: 'text', text: comment }], [categoryTag]);
}
typeReflection.signatures = [eventSignature];
const resolvedType = new ReflectionType(typeReflection);
reflection.type = resolvedType;
reflection.setFlag(ReflectionFlag.Static, false);
return reflection;
}
function extractBaseType(type: any, context: Context, reflection: SignatureReflection) {
if (!type.baseTypesResolved) {
return;
}
assert(context.scope instanceof DeclarationReflection);
// Expected only 1 item so far?
const resolvedBaseTypeString = context.checker.typeToString(type.resolvedBaseTypes[0]);
const intersectTypes = resolvedBaseTypeString.split('&').map((t) => t.trim());
if (intersectTypes.length > 1) {
for (const [index, typeName] of intersectTypes.entries()) {
if (typeName.includes('EventEmitterInterface') || excludeBaseTypes.includes(typeName)) {
continue;
}
const baseType = type.resolvedBaseTypes[0].types[index];
const refType = ReferenceType.createResolvedReference(
baseType.symbol.name,
reflection,
context.project,
);
if (context.scope.extendedTypes && context.scope.extendedTypes[0].type === 'intersection') {
(context.scope.extendedTypes[0] as IntersectionType).types.push(refType);
} else if (context.scope.extendedTypes) {
const intersectionType = new IntersectionType(context.scope.extendedTypes);
intersectionType.types.push(refType);
context.scope.extendedTypes = [intersectionType];
} else {
context.scope.extendedTypes = [refType];
}
}
} else if (!excludeBaseTypes.includes(resolvedBaseTypeString)) {
const baseType = type.resolvedBaseTypes[0];
const refType = ReferenceType.createResolvedReference(
baseType.symbol.name,
reflection,
context.project,
);
context.scope.extendedTypes = context.scope.extendedTypes
? [...context.scope.extendedTypes, refType]
: [refType];
}
}
//#region Taken from typedoc source for creating a generic signature of a Symbol.
function removeUndefined(type: SomeType): SomeType {
if (type instanceof UnionType) {
const types = type.types.filter((t) => {
if (t instanceof IntrinsicType) {
return t.name !== 'undefined';
}
return true;
});
if (types.length === 1) {
return types[0];
}
type.types = types;
return type;
}
return type;
}
function convertParameters(
context: Context,
sigRef: SignatureReflection,
parameters: readonly (ts.Symbol & { type?: ts.Type })[],
parameterNodes: readonly ts.ParameterDeclaration[] | readonly ts.JSDocParameterTag[] | undefined,
) {
// #2698 if `satisfies` is used to imply a this parameter, we might have
// more parameters than parameter nodes and need to shift the parameterNode
// access index. Very ugly, but it does the job.
const parameterNodeOffset = parameterNodes?.length !== parameters.length ? -1 : 0;
return parameters.map((param, i) => {
const declaration = param.valueDeclaration;
assert(!declaration || ts.isParameter(declaration) || ts.isJSDocParameterTag(declaration));
const paramRefl = new ParameterReflection(
/__\d+/.test(param.name) ? '__namedParameters' : param.name,
ReflectionKind.Parameter,
sigRef,
);
if (declaration && ts.isJSDocParameterTag(declaration)) {
paramRefl.comment = context.getJsDocComment(declaration);
}
paramRefl.comment ||= context.getComment(param, paramRefl.kind);
context.registerReflection(paramRefl, param);
let type: ts.Type | ts.TypeNode | undefined;
let typeNode: ts.TypeNode | undefined;
if (declaration) {
type = context.checker.getTypeOfSymbolAtLocation(param, declaration);
if (ts.isParameter(declaration)) {
typeNode = declaration.type;
} else {
typeNode = declaration.typeExpression?.type;
}
} else {
type = param.type;
}
if (
declaration &&
ts.isParameter(declaration) &&
declaration.type?.kind === ts.SyntaxKind.ThisType
) {
paramRefl.type = new IntrinsicType('this');
} else if (!type) {
paramRefl.type = new IntrinsicType('any');
} else {
paramRefl.type = context.converter.convertType(context.withScope(paramRefl), type, typeNode);
}
let isOptional = false;
if (declaration) {
isOptional = ts.isParameter(declaration)
? !!declaration.questionToken ||
ts.getJSDocParameterTags(declaration).some((tag) => tag.isBracketed)
: declaration.isBracketed;
}
if (isOptional) {
paramRefl.type = removeUndefined(paramRefl.type);
}
// paramRefl.defaultValue = convertDefaultValue(
// parameterNodes?.[i + parameterNodeOffset],
// );
paramRefl.setFlag(ReflectionFlag.Optional, isOptional);
// If we have no declaration, then this is an implicitly defined parameter in JS land
// because the method body uses `arguments`... which is always a rest argument
let isRest = true;
if (declaration) {
isRest = ts.isParameter(declaration)
? !!declaration.dotDotDotToken
: !!declaration.typeExpression && ts.isJSDocVariadicType(declaration.typeExpression.type);
}
paramRefl.setFlag(ReflectionFlag.Rest, isRest);
checkForDestructuredParameterDefaults(paramRefl, parameterNodes?.[i + parameterNodeOffset]);
return paramRefl;
});
}
function checkForDestructuredParameterDefaults(
param: ParameterReflection,
decl: ts.ParameterDeclaration | ts.JSDocParameterTag | undefined,
) {
if (!decl || !ts.isParameter(decl)) return;
if (param.name !== '__namedParameters') return;
if (!ts.isObjectBindingPattern(decl.name)) return;
if (param.type?.type !== 'reflection') return;
for (const child of param.type.declaration.children || []) {
const tsChild = decl.name.elements.find(
(el) => (el.propertyName || el.name).getText() === child.name,
);
if (tsChild) {
//child.defaultValue = convertDefaultValue(tsChild);
}
}
}
function createSignature(
context: Context,
kind:
| ReflectionKind.CallSignature
| ReflectionKind.ConstructorSignature
| ReflectionKind.GetSignature
| ReflectionKind.SetSignature,
signature: ts.Signature,
symbol: ts.Symbol | undefined,
inDeclaration?: ts.SignatureDeclaration | ts.JSDocSignature,
) {
assert(context.scope instanceof DeclarationReflection);
const declaration =
inDeclaration || (signature.getDeclaration() as ts.SignatureDeclaration | undefined);
const sigRef = new SignatureReflection(
kind === ReflectionKind.ConstructorSignature ? context.scope.parent!.name : context.scope.name,
kind,
context.scope,
);
// This feels awful, but we need some way to tell if callable signatures on classes
// are "static" (e.g. `Foo()`) or not (e.g. `(new Foo())()`)
if (context.shouldBeStatic) {
sigRef.setFlag(ReflectionFlag.Static);
}
if (symbol && declaration) {
// context.project.registerSymbolId(
// sigRef,
// createSymbolId(symbol, declaration),
// );
}
let parentReflection = context.scope;
if (
parentReflection.kindOf(ReflectionKind.TypeLiteral) &&
parentReflection.parent instanceof DeclarationReflection
) {
parentReflection = parentReflection.parent;
}
if (declaration) {
const sigComment = context.getSignatureComment(declaration);
if (parentReflection.comment?.discoveryId !== sigComment?.discoveryId) {
sigRef.comment = sigComment;
if (parentReflection.kindOf(ReflectionKind.MayContainDocuments)) {
context.converter.processDocumentTags(sigRef, parentReflection);
}
}
}
const sigRefCtx = context.withScope(sigRef);
// sigRef.typeParameters = convertTypeParameters(
// sigRefCtx,
// sigRef,
// signature.typeParameters,
// );
const parameterSymbols: ReadonlyArray<ts.Symbol & { type?: ts.Type }> = signature.thisParameter
? [signature.thisParameter, ...signature.parameters]
: signature.parameters;
sigRef.parameters = convertParameters(
sigRefCtx,
sigRef,
parameterSymbols,
declaration?.parameters,
);
const predicate = context.checker.getTypePredicateOfSignature(signature);
if (predicate) {
sigRef.type = convertPredicate(predicate, sigRefCtx);
} else if (kind === ReflectionKind.SetSignature) {
sigRef.type = new IntrinsicType('void');
} else if (declaration?.type?.kind === ts.SyntaxKind.ThisType) {
sigRef.type = new IntrinsicType('this');
} else {
let typeNode = declaration?.type;
if (typeNode && ts.isJSDocReturnTag(typeNode)) {
typeNode = typeNode.typeExpression?.type;
}
sigRef.type = context.converter.convertType(sigRefCtx, signature.getReturnType(), typeNode);
}
context.registerReflection(sigRef, undefined);
switch (kind) {
case ReflectionKind.GetSignature:
context.scope.getSignature = sigRef;
break;
case ReflectionKind.SetSignature:
context.scope.setSignature = sigRef;
break;
case ReflectionKind.CallSignature:
case ReflectionKind.ConstructorSignature:
context.scope.signatures ??= [];
context.scope.signatures.push(sigRef);
break;
}
}
function convertPredicate(predicate: ts.TypePredicate, context: Context): PredicateType {
let name: string;
switch (predicate.kind) {
case ts.TypePredicateKind.This:
case ts.TypePredicateKind.AssertsThis:
name = 'this';
break;
case ts.TypePredicateKind.Identifier:
case ts.TypePredicateKind.AssertsIdentifier:
name = predicate.parameterName;
break;
}
let asserts: boolean;
switch (predicate.kind) {
case ts.TypePredicateKind.This:
case ts.TypePredicateKind.Identifier:
asserts = false;
break;
case ts.TypePredicateKind.AssertsThis:
case ts.TypePredicateKind.AssertsIdentifier:
asserts = true;
break;
}
return new PredicateType(
name,
asserts,
predicate.type ? context.converter.convertType(context, predicate.type) : void 0,
);
}
//#endregion