|
| 1 | +/** @import { Application, DeclarationReflection } from "typedoc" */ |
| 2 | + |
| 3 | +import { Converter, ReflectionKind } from "typedoc"; |
| 4 | + |
| 5 | +/** @param {DeclarationReflection} declaration */ |
| 6 | +function hackInheritance(declaration) { |
| 7 | + if (!declaration.extendedTypes) { |
| 8 | + return; |
| 9 | + } |
| 10 | + |
| 11 | + for (let i = 0; i < declaration.extendedTypes.length; ++i) { |
| 12 | + const type = declaration.extendedTypes[i]; |
| 13 | + if (type === undefined) { |
| 14 | + continue; |
| 15 | + } |
| 16 | + if (type.type !== "reference") { |
| 17 | + continue; |
| 18 | + } |
| 19 | + if (!type.reflection) { |
| 20 | + continue; |
| 21 | + } |
| 22 | + |
| 23 | + const target = /** @type {DeclarationReflection} */(type.reflection); |
| 24 | + |
| 25 | + if (target.kindOf(ReflectionKind.ClassOrInterface)) { |
| 26 | + continue; |
| 27 | + } |
| 28 | + |
| 29 | + const targetType = target.type; |
| 30 | + if (targetType === undefined || targetType.type !== "query") { |
| 31 | + continue; |
| 32 | + } |
| 33 | + if (!targetType.queryType.reflection?.kindOf(ReflectionKind.ClassOrInterface)) { |
| 34 | + continue; |
| 35 | + } |
| 36 | + |
| 37 | + // We inherit from a property somewhere which is declared as `typeof SomeClass` |
| 38 | + // So re-point the inheritance to SomeClass |
| 39 | + declaration.extendedTypes[i] = targetType.queryType; |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +/** |
| 44 | + * Plugin for TypeDoc to handle `typeof` class inheritance. When `X` is |
| 45 | + * a class, `A = X` is a variable assigned to the class with a declared |
| 46 | + * type of `typeof X`, and another class uses `A` as a base class, then |
| 47 | + * TypeDoc will not resolve the class hierarchy correctly. For example, |
| 48 | + * |
| 49 | + * ```ts |
| 50 | + * class X {} |
| 51 | + * |
| 52 | + * interface Registry { |
| 53 | + * X: typeof X; |
| 54 | + * } |
| 55 | + * declare const registry: Registry; |
| 56 | + * |
| 57 | + * class Y extends registry.X {} |
| 58 | + * ``` |
| 59 | + * |
| 60 | + * This plugin scans for such cases where a class has an expression |
| 61 | + * in its extends clause. If it finds the type of the expression is |
| 62 | + * `typeof X`, it replaces the extends clause with `X`. This way, |
| 63 | + * the class hierarchy is correctly resolved. |
| 64 | + * |
| 65 | + * See also: |
| 66 | + * https://github.com/TypeStrong/typedoc/issues/2775 |
| 67 | + * |
| 68 | + * @param {Application} app |
| 69 | + */ |
| 70 | +export function load(app) { |
| 71 | + app.converter.on( |
| 72 | + Converter.EVENT_RESOLVE_BEGIN, |
| 73 | + (context) => { |
| 74 | + for (const decl of context.project.getReflectionsByKind(ReflectionKind.ClassOrInterface)) { |
| 75 | + hackInheritance(/** @type {DeclarationReflection} */(decl)); |
| 76 | + } |
| 77 | + }, |
| 78 | + 1e6, |
| 79 | + ); |
| 80 | +} |
0 commit comments