dgeni-packages
Version:
A collection of dgeni packages for generating documentation from source code
74 lines • 3.19 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getContent = void 0;
const typescript_1 = require("typescript");
const LEADING_STAR = /^[^\S\r\n]*\*[^\S\n\r]?/gm;
const ASTERISK = 42;
const SLASH = 47;
const syntaxKindsWithTrailingComments = [
typescript_1.SyntaxKind.Parameter,
typescript_1.SyntaxKind.TypeParameter,
typescript_1.SyntaxKind.FunctionExpression,
typescript_1.SyntaxKind.ArrowFunction,
];
function getContent(node, concatLeadingComments = true) {
let content = '';
if (!node)
return content;
if (node.kind === typescript_1.SyntaxKind.ModuleDeclaration) {
let moduleDeclaration = node;
// If this is left side of dotted module declaration, there is no doc comment associated with this declaration
if (moduleDeclaration.body && moduleDeclaration.body.kind === typescript_1.SyntaxKind.ModuleDeclaration) {
return content;
}
// If this is dotted module name, get the doc comments from the parent
while (moduleDeclaration.parent && moduleDeclaration.parent.kind === typescript_1.SyntaxKind.ModuleDeclaration) {
moduleDeclaration = moduleDeclaration.parent;
}
node = moduleDeclaration;
}
// If this is a variable declaration then we get the doc comments from the grand parent
if (node.kind === typescript_1.SyntaxKind.VariableDeclaration) {
node = node.parent && node.parent.parent || node;
}
// Get the source file of this node
const sourceFile = node.getSourceFile();
const { leading, trailing } = getJSDocCommentRanges(node, sourceFile.text);
const commentRanges = [];
if (concatLeadingComments) {
commentRanges.push(...leading);
}
else if (leading.length) {
commentRanges.push(leading[leading.length - 1]);
}
if (syntaxKindsWithTrailingComments.includes(node.kind)) {
commentRanges.push(...trailing);
}
commentRanges.forEach(commentRange => {
content += sourceFile.text
.substring(commentRange.pos + '/**'.length, commentRange.end - '*/'.length)
.replace(LEADING_STAR, '')
.trim();
if (commentRange.hasTrailingNewLine) {
content += '\n';
}
});
return content.trim();
}
exports.getContent = getContent;
function getJSDocCommentRanges(node, text) {
const leading = ((0, typescript_1.getLeadingCommentRanges)(text, node.pos) || [])
.filter(range => isJSDocCommentRange(text, range));
const trailing = ((0, typescript_1.getTrailingCommentRanges)(text, node.pos) || [])
.filter(range => isJSDocCommentRange(text, range));
return { leading, trailing };
}
/** Whether the specified comment range refers to a JSDoc comment. */
function isJSDocCommentRange(text, range) {
// Multi line comments are not always JSDoc comments. e.g. /* abc */ or /**/.
return range.kind === typescript_1.SyntaxKind.MultiLineCommentTrivia &&
text.charCodeAt(range.pos + 1) === ASTERISK &&
text.charCodeAt(range.pos + 2) === ASTERISK &&
text.charCodeAt(range.pos + 3) !== SLASH;
}
//# sourceMappingURL=getContent.js.map