1
import * as bt from '@babel/types'
2
import { NodePath } from 'ast-types/lib/node-path'
3

4
/**
5
 * Helper functions to work with docblock comments.
6
 */
7

8
/**
9
 * Extracts the text from a docblock comment
10
 * @param {rawDocblock} str
11
 * @return str stripped from stars and spaces
12
 */
13 1
export function parseDocblock(str: string): string {
14 1
	const lines = str.split('\n')
15 1
	for (let i = 0, l = lines.length; i < l; i++) {
16 1
		lines[i] = lines[i].replace(/^\s*\*\s?/, '').replace(/\r$/, '')
17
	}
18 1
	return lines.join('\n').trim()
19
}
20

21 1
const DOCBLOCK_HEADER = /^\*\s/
22

23
/**
24
 * Given a path, this function returns the closest preceding docblock if it
25
 * exists.
26
 */
27 1
export default function getDocblock(
28
	path: NodePath,
29 1
	{ commentIndex = 1 } = { commentIndex: 1 }
30
): string | null {
31 1
	commentIndex = commentIndex || 1
32 1
	let comments: bt.Comment[] = []
33 1
	const allComments = path.node.leadingComments
34 1
	if (allComments) {
35 1
		comments = allComments.filter(
36 1
			(comment: bt.Comment) =>
37 1
				comment.type === 'CommentBlock' && DOCBLOCK_HEADER.test(comment.value)
38
		)
39
	}
40

41 1
	if (comments.length + 1 - commentIndex > 0) {
42 1
		return parseDocblock(comments[comments.length - commentIndex].value)
43
	}
44 1
	return null
45
}

Read our documentation on viewing source code .

Loading