|
| 1 | +import type { TSESTree as AST } from "@typescript-eslint/types"; |
| 2 | +import { ESLintUtils } from "@typescript-eslint/utils"; |
| 3 | + |
| 4 | +export const enforceDocumentationTypes = ESLintUtils.RuleCreator.withoutDocs({ |
| 5 | + create(context) { |
| 6 | + const namespaces = []; |
| 7 | + const shouldBeDocumented: Record< |
| 8 | + string, |
| 9 | + { |
| 10 | + namespaces: string[]; |
| 11 | + node: AST.TSTypeAliasDeclaration; |
| 12 | + } |
| 13 | + > = {}; |
| 14 | + return { |
| 15 | + TSModuleDeclaration(node) { |
| 16 | + if (node.kind !== "namespace") { |
| 17 | + return; |
| 18 | + } |
| 19 | + namespaces.push( |
| 20 | + node.id.type === "Identifier" ? node.id.name : "<unknown>" |
| 21 | + ); |
| 22 | + }, |
| 23 | + "TSModuleDeclaration:exit"(node) { |
| 24 | + if (node.kind !== "namespace") { |
| 25 | + return; |
| 26 | + } |
| 27 | + namespaces.pop(); |
| 28 | + for (const [name, entry] of Object.entries(shouldBeDocumented)) { |
| 29 | + if (entry.namespaces.length > namespaces.length) { |
| 30 | + delete shouldBeDocumented[name]; |
| 31 | + context.report({ |
| 32 | + node: entry.node.id, |
| 33 | + messageId: "shouldBeDocumented", |
| 34 | + }); |
| 35 | + } |
| 36 | + } |
| 37 | + }, |
| 38 | + ExportNamedDeclaration(node) { |
| 39 | + if (!node.declaration) { |
| 40 | + return; |
| 41 | + } |
| 42 | + if (node.declaration.type === "TSTypeAliasDeclaration") { |
| 43 | + const name = node.declaration.id.name; |
| 44 | + if (name.endsWith("Result") || name.endsWith("Options")) { |
| 45 | + shouldBeDocumented[name] = { |
| 46 | + node: node.declaration, |
| 47 | + namespaces: [...namespaces], |
| 48 | + }; |
| 49 | + } |
| 50 | + } else if (node.declaration.type === "TSInterfaceDeclaration") { |
| 51 | + const name = node.declaration.id.name; |
| 52 | + if ( |
| 53 | + name in shouldBeDocumented && |
| 54 | + namespaces.at(-1) === "DocumentationTypes" |
| 55 | + ) { |
| 56 | + delete shouldBeDocumented[name]; |
| 57 | + } |
| 58 | + } |
| 59 | + }, |
| 60 | + }; |
| 61 | + }, |
| 62 | + meta: { |
| 63 | + messages: { |
| 64 | + shouldBeDocumented: |
| 65 | + "This type should have an interface with the same name in a nested `DocumentationTypes` namespace.", |
| 66 | + }, |
| 67 | + type: "problem", |
| 68 | + schema: [], |
| 69 | + fixable: "code", |
| 70 | + }, |
| 71 | + defaultOptions: [], |
| 72 | +}); |
0 commit comments