markdown.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /** Shared Markdown parsing and depth-first traversal for documentation gates. */
  2. import { fromMarkdown } from 'mdast-util-from-markdown'
  3. import { gfmFromMarkdown } from 'mdast-util-gfm'
  4. import { gfm } from 'micromark-extension-gfm'
  5. import type { Nodes } from 'mdast'
  6. /** One authored Markdown line outside fenced code and rendered-away HTML comments. */
  7. export interface MarkdownProseLine {
  8. /** 1-based source line number. */
  9. index: number
  10. /** Source text without normalization. */
  11. raw: string
  12. }
  13. /** One parsed Markdown heading, retaining its authored first line and rendered text. */
  14. export interface MarkdownHeadingLine extends MarkdownProseLine {
  15. /** Parsed ATX or Setext heading depth. */
  16. depth: 1 | 2 | 3 | 4 | 5 | 6
  17. /** Rendered heading text, excluding raw HTML such as comments. */
  18. text: string
  19. }
  20. /** One code block from a parsed Markdown source. */
  21. export interface MarkdownFence {
  22. /** 1-based source line of the opening fence. */
  23. line: number
  24. /** Info-string language (its first word), null on a bare or indented block. */
  25. lang: string | null
  26. /** Full info string (e.g. `ts ignore-check`), '' on a bare or indented block. */
  27. info: string
  28. /** Block body without the fence delimiters. */
  29. code: string
  30. /**
  31. * Whether a closing fence delimiter terminates the block — mdast silently
  32. * closes an unterminated fence at end of file. False on indented
  33. * (non-fenced) blocks, whose end line is code.
  34. */
  35. closed: boolean
  36. }
  37. /** Parse GitHub-flavored Markdown with the repository's standard extensions. */
  38. export function parseMarkdown(source: string): Nodes {
  39. return fromMarkdown(source, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] })
  40. }
  41. /**
  42. * Visit a Markdown tree depth-first; returning false prunes a node's children.
  43. * @param node - current tree node.
  44. * @param visitor - callback invoked before each node's children.
  45. */
  46. export function visitMarkdown(node: Nodes, visitor: (node: Nodes) => boolean | void): void {
  47. if (visitor(node) === false) return
  48. if ('children' in node) {
  49. for (const child of node.children) visitMarkdown(child, visitor)
  50. }
  51. }
  52. /** Markdown nodes whose authored destination occupies a replaceable source range. */
  53. export type MarkdownDestinationNode = Extract<Nodes, { type: 'link' | 'image' | 'definition' }>
  54. /** One authored Markdown destination and its absolute source offsets. */
  55. export interface MarkdownDestination {
  56. start: number
  57. end: number
  58. url: string
  59. }
  60. /** Whether a Markdown URL is external, repository-root absolute, or purely in-page. */
  61. export function isExternalOrAbsoluteMarkdownUrl(url: string): boolean {
  62. return url.startsWith('#')
  63. || url.startsWith('//')
  64. || url.startsWith('/')
  65. || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)
  66. }
  67. /** Split one Markdown URL without normalizing its query or fragment suffix. */
  68. export function splitMarkdownUrlTarget(url: string): { path: string; suffix: string } {
  69. const boundary = url.search(/[?#]/)
  70. if (boundary === -1) return { path: url, suffix: '' }
  71. return { path: url.slice(0, boundary), suffix: url.slice(boundary) }
  72. }
  73. function skipWhitespace(source: string, start: number): number {
  74. let index = start
  75. while (/\s/.test(source[index] ?? '')) index += 1
  76. return index
  77. }
  78. function labelEnd(source: string): number {
  79. const first = source.indexOf('[')
  80. if (first === -1) return -1
  81. let depth = 0
  82. for (let index = first; index < source.length; index += 1) {
  83. const char = source[index]
  84. if (char === '\\') index += 1
  85. else if (char === '[') depth += 1
  86. else if (char === ']') {
  87. depth -= 1
  88. if (depth === 0) return index
  89. }
  90. }
  91. return -1
  92. }
  93. function destinationRange(rawNode: string, type: MarkdownDestinationNode['type']): { start: number; end: number } {
  94. const endOfLabel = labelEnd(rawNode)
  95. if (endOfLabel === -1) throw new Error(`markdown: cannot locate label end in ${JSON.stringify(rawNode)}`)
  96. let start: number
  97. if (type === 'definition') {
  98. const colon = rawNode.indexOf(':', endOfLabel + 1)
  99. if (colon === -1) throw new Error(`markdown: cannot locate definition separator in ${JSON.stringify(rawNode)}`)
  100. start = skipWhitespace(rawNode, colon + 1)
  101. } else {
  102. if (rawNode[endOfLabel + 1] !== '(') {
  103. throw new Error(`markdown: cannot locate inline destination in ${JSON.stringify(rawNode)}`)
  104. }
  105. start = skipWhitespace(rawNode, endOfLabel + 2)
  106. }
  107. if (rawNode[start] === '<') {
  108. for (let index = start + 1; index < rawNode.length; index += 1) {
  109. if (rawNode[index] === '\\') index += 1
  110. else if (rawNode[index] === '>') return { start: start + 1, end: index }
  111. }
  112. throw new Error(`markdown: cannot locate angle-bracket destination end in ${JSON.stringify(rawNode)}`)
  113. }
  114. let depth = 0
  115. for (let index = start; index < rawNode.length; index += 1) {
  116. const char = rawNode[index]
  117. if (char === '\\') index += 1
  118. else if (char === '(') depth += 1
  119. else if (char === ')') {
  120. if (depth === 0) return { start, end: index }
  121. depth -= 1
  122. } else if (/\s/.test(char ?? '') && depth === 0) {
  123. return { start, end: index }
  124. }
  125. }
  126. return { start, end: rawNode.length }
  127. }
  128. /** Locate one parsed destination in the original Markdown without reserializing it. */
  129. export function markdownDestination(source: string, node: MarkdownDestinationNode): MarkdownDestination {
  130. const start = node.position?.start.offset
  131. const end = node.position?.end.offset
  132. if (start === undefined || end === undefined) {
  133. throw new Error(`markdown: destination ${JSON.stringify(node.url)} has no source offsets`)
  134. }
  135. const range = destinationRange(source.slice(start, end), node.type)
  136. const absolute = { start: start + range.start, end: start + range.end }
  137. return { ...absolute, url: source.slice(absolute.start, absolute.end) }
  138. }
  139. /**
  140. * Extract every parsed code block with its info string, in document order.
  141. * @param source - Markdown source to scan.
  142. * @returns each block's opening line, language, info string, and body.
  143. */
  144. export function markdownFences(source: string): MarkdownFence[] {
  145. const lines = source.split('\n')
  146. const fences: MarkdownFence[] = []
  147. visitMarkdown(parseMarkdown(source), (node) => {
  148. if (node.type !== 'code' || node.position === undefined) return
  149. const lang = node.lang ?? null
  150. const meta = node.meta ?? ''
  151. const info = lang === null ? '' : meta === '' ? lang : `${lang} ${meta}`
  152. const endLine = lines[node.position.end.line - 1] ?? ''
  153. const closed = /^ {0,3}(`{3,}|~{3,})\s*$/.test(endLine)
  154. fences.push({ line: node.position.start.line, lang, info, code: node.value, closed })
  155. })
  156. return fences
  157. }
  158. /** Text a reader sees from one Markdown node; raw HTML itself contributes none. */
  159. function renderedText(node: Nodes): string {
  160. if (node.type === 'text' || node.type === 'inlineCode') return node.value
  161. if (node.type === 'image' || node.type === 'imageReference') return node.alt ?? ''
  162. if (node.type === 'break') return ' '
  163. if ('children' in node) return node.children.map(child => renderedText(child)).join('')
  164. return ''
  165. }
  166. /** Return every parsed Markdown heading with its rendered text and source line. */
  167. export function markdownHeadingLines(source: string): MarkdownHeadingLine[] {
  168. const rawLines = source.split('\n')
  169. const headings: MarkdownHeadingLine[] = []
  170. visitMarkdown(parseMarkdown(source), (node) => {
  171. if (node.type !== 'heading' || node.position === undefined) return
  172. headings.push({
  173. depth: node.depth,
  174. index: node.position.start.line,
  175. raw: rawLines[node.position.start.line - 1] ?? '',
  176. text: renderedText(node),
  177. })
  178. })
  179. return headings
  180. }
  181. type ColumnRange = readonly [start: number, end: number]
  182. type OffsetRange = readonly [start: number, end: number]
  183. /** Source-column ranges occupied by parsed HTML comments, keyed by source line. */
  184. function htmlCommentRanges(source: string, rawLines: readonly string[]): Map<number, ColumnRange[]> {
  185. const comments: OffsetRange[] = []
  186. visitMarkdown(parseMarkdown(source), (node) => {
  187. if (node.type !== 'html' || node.position?.start.offset === undefined) return
  188. let cursor = 0
  189. while (true) {
  190. const start = node.value.indexOf('<!--', cursor)
  191. if (start < 0) break
  192. const close = node.value.indexOf('-->', start + '<!--'.length)
  193. const end = close < 0 ? node.value.length : close + '-->'.length
  194. comments.push([node.position.start.offset + start, node.position.start.offset + end])
  195. cursor = end
  196. }
  197. })
  198. const ranges = new Map<number, ColumnRange[]>()
  199. let lineOffset = 0
  200. rawLines.forEach((raw, index) => {
  201. const lineEnd = lineOffset + raw.length
  202. for (const [start, end] of comments) {
  203. const from = Math.max(start, lineOffset)
  204. const to = Math.min(end, lineEnd)
  205. const coversEmptyLine = raw.length === 0 && start <= lineOffset && end > lineOffset
  206. if (from < to || coversEmptyLine) {
  207. const lineRanges = ranges.get(index + 1) ?? []
  208. lineRanges.push([from - lineOffset, to - lineOffset])
  209. ranges.set(index + 1, lineRanges)
  210. }
  211. }
  212. lineOffset = lineEnd + 1
  213. })
  214. return ranges
  215. }
  216. /** Whether a source line retains non-whitespace text after HTML comments disappear. */
  217. function hasRenderedTextOutsideComments(raw: string, ranges: readonly ColumnRange[] | undefined): boolean {
  218. if (ranges === undefined) return true
  219. let cursor = 0
  220. let visible = ''
  221. for (const [start, end] of [...ranges].sort((left, right) => left[0] - right[0])) {
  222. visible += raw.slice(cursor, start)
  223. cursor = Math.max(cursor, end)
  224. }
  225. visible += raw.slice(cursor)
  226. return visible.trim().length > 0
  227. }
  228. /**
  229. * Return source lines outside code blocks and HTML comments.
  230. * @param source - Markdown source whose prose should be retained verbatim.
  231. * @returns unfenced lines with their original 1-based locations.
  232. */
  233. export function markdownProseLines(source: string): MarkdownProseLine[] {
  234. const rawLines = source.split('\n')
  235. const comments = htmlCommentRanges(source, rawLines)
  236. const fenced = new Set<number>()
  237. visitMarkdown(parseMarkdown(source), (node) => {
  238. if (node.type !== 'code' || node.position === undefined) return
  239. for (let line = node.position.start.line; line <= node.position.end.line; line += 1) fenced.add(line)
  240. })
  241. const kept: MarkdownProseLine[] = []
  242. rawLines.forEach((raw, i) => {
  243. if (fenced.has(i + 1)) return
  244. if (hasRenderedTextOutsideComments(raw, comments.get(i + 1))) {
  245. kept.push({ index: i + 1, raw })
  246. }
  247. })
  248. return kept
  249. }