| 1 | import ts from "typescript"; |
| 2 | import * as tsdoc from "@microsoft/tsdoc"; |
| 3 | |
| 4 | export const tagDefinitions = { |
| 5 | filenameTag: new tsdoc.TSDocTagDefinition({ |
| 6 | tagName: "@filename", |
| 7 | syntaxKind: tsdoc.TSDocTagSyntaxKind.BlockTag, |
| 8 | }), |
| 9 | excludedTag: new tsdoc.TSDocTagDefinition({ |
| 10 | tagName: "@excluded", |
| 11 | syntaxKind: tsdoc.TSDocTagSyntaxKind.ModifierTag, |
| 12 | }), |
| 13 | irreplacedTag: new tsdoc.TSDocTagDefinition({ |
| 14 | tagName: "@irreplaced", |
| 15 | syntaxKind: tsdoc.TSDocTagSyntaxKind.ModifierTag, |
| 16 | }), |
| 17 | irreplaceableTag: new tsdoc.TSDocTagDefinition({ |
| 18 | tagName: "@irreplaceable", |
| 19 | syntaxKind: tsdoc.TSDocTagSyntaxKind.ModifierTag, |
| 20 | }), |
| 21 | replaceFirstLevelTag: new tsdoc.TSDocTagDefinition({ |
| 22 | tagName: "@replaceFirstLevel", |
| 23 | syntaxKind: tsdoc.TSDocTagSyntaxKind.ModifierTag, |
| 24 | }), |
| 25 | categoryTag: new tsdoc.TSDocTagDefinition({ |
| 26 | tagName: "@category", |
| 27 | syntaxKind: tsdoc.TSDocTagSyntaxKind.InlineTag, |
| 28 | }), |
| 29 | }; |
| 30 | |
| 31 | const configuration = new tsdoc.TSDocConfiguration(); |
| 32 | configuration.addTagDefinitions(Object.values(tagDefinitions)); |
| 33 | |
| 34 | export class DocManager { |
| 35 | static parser = new tsdoc.TSDocParser(configuration); |
| 36 | |
| 37 | static getJSDocCommentRanges(node: ts.Node, text: string): ts.CommentRange[] { |
| 38 | const commentRanges: ts.CommentRange[] = []; |
| 39 | commentRanges.push(...(ts.getLeadingCommentRanges(text, node.pos) || [])); |
| 40 | |
| 41 | // True if the comment starts with '/**' but not if it is '/**/' |
| 42 | return commentRanges.filter( |
| 43 | (comment) => |
| 44 | text.charCodeAt(comment.pos + 1) === 0x2a /* ts.CharacterCodes.asterisk */ && |
| 45 | text.charCodeAt(comment.pos + 2) === 0x2a /* ts.CharacterCodes.asterisk */ && |
| 46 | text.charCodeAt(comment.pos + 3) !== 0x2f /* ts.CharacterCodes.slash */ |
| 47 | ); |
| 48 | } |
| 49 | |
| 50 | static parseFirstDocComment(node: ts.Node, sourceText: string): tsdoc.DocComment | undefined; |
| 51 | |
| 52 | static parseFirstDocComment( |
| 53 | comments: ts.CommentRange[], |
| 54 | sourceText: string |
| 55 | ): tsdoc.DocComment | undefined; |
| 56 | |
| 57 | static parseFirstDocComment(nodeOrComments: ts.CommentRange[] | ts.Node, sourceText: string) { |
| 58 | const comments = Array.isArray(nodeOrComments) |
| 59 | ? nodeOrComments |
| 60 | : this.getJSDocCommentRanges(nodeOrComments, sourceText); |
| 61 | if (comments.length > 0) { |
| 62 | const comment = comments[0]; |
| 63 | const { docComment } = this.parser.parseRange( |
| 64 | tsdoc.TextRange.fromStringRange(sourceText, comment.pos, comment.end) |
| 65 | ); |
| 66 | return docComment; |
| 67 | } |
| 68 | return undefined; |
| 69 | } |
| 70 | } |