Skip to content
Source
Sign inSign up
TanStack/markdown
Open History to see the last commit

parser.ts

555 lines16.6 KB

1import { parseInline } from './inline.js'
2import type {
3 BlockNode,
4 CodeBlockNode,
5 FootnoteItemNode,
6 HeadingNode,
7 InlineNode,
8 ListItemNode,
9 ListNode,
10 MarkdownDocument,
11 ParseOptions,
12 TableCellNode,
13 TableNode,
14} from './types.js'
15import { createSlugger, footnoteId, isBlank, normalizeInput, normalizeReferenceLabel, parseDestination, plainText, stripIndent } from './utils.js'
16​
17type Slugger = ReturnType<typeof createSlugger>
18​
19interface BlockParseBudget {
20 depth: number
22​
23const maxBlockDepth = 64
24​
25export function parseMarkdown(markdown: string, options: ParseOptions = {}): MarkdownDocument {
26 const normalized = normalizeInput(markdown)
27 const frontmatterEnabled = options.frontmatter !== false
28 let lines = normalized.split('\n')
29 let frontmatter: string | undefined
30​
31 if (frontmatterEnabled && lines[0] === '---') {
32 const end = lines.findIndex((line, index) => index > 0 && line === '---')
33 if (end > 0) {
34 frontmatter = lines.slice(1, end).join('\n')
35 lines = lines.slice(end + 1)
36 }
37 }
38​
39 const definitions = extractDefinitions(lines)
40 lines = definitions.lines
41 const footnoteOrder: string[] = []
42 const footnoteCounts: Record<string, number> = Object.create(null)
43 const hasReferences = Object.keys(definitions.references).length > 0
44 const hasFootnotes = Object.keys(definitions.footnotes).length > 0
45 const parseOptions =
46 hasReferences || hasFootnotes
47 ? {
48 ...options,
49 ...(hasReferences && { references: definitions.references }),
50 ...(hasFootnotes && { footnotes: definitions.footnotes, footnoteOrder, footnoteCounts }),
51 }
52 : options
53​
54 const slugger = createSlugger()
55 const parser = createBlockParser(lines, parseOptions, slugger)
56 const children = parser.parse()
57 if (hasFootnotes && footnoteOrder.length > 0) {
58 children.push(createFootnotesBlock(definitions.footnotes, footnoteOrder, parseOptions, slugger))
59 }
60 let document: MarkdownDocument = frontmatter === undefined ? { type: 'root', children } : { type: 'root', frontmatter, children }
61​
62 for (const extension of parseOptions.extensions ?? []) {
63 document = extension.transformDocument?.(document, { options: parseOptions }) ?? document
64 }
65​
66 return document
68​
69function createBlockParser(
70 inputLines: string[],
71 options: ParseOptions,
72 slugger: Slugger,
73 budget: BlockParseBudget = { depth: 0 },
74) {
75 let cursor = 0
76 let looseBlocks = false
77 return {
78 parse,
79 get loose() {
80 return looseBlocks
81 },
82 }
83​
84 function parse(): BlockNode[] {
85 if (budget.depth >= maxBlockDepth) {
86 const value = inputLines.slice(cursor).join('\n')
87 cursor = inputLines.length
88 return value ? [{ type: 'paragraph', children: parseInline(value, options) }] : []
89 }
90​
91 budget.depth++
92 const nodes: BlockNode[] = []
93​
94 while (cursor < inputLines.length) {
95 if (isBlank(current())) {
96 if (nodes.length) looseBlocks = true
97 cursor++
98 continue
99 }
100​
101 const extensionNode = parseExtensionBlock()
102 if (extensionNode) {
103 nodes.push(extensionNode)
104 continue
105 }
106​
107 // Letter-led text cannot open a fence, heading, rule, quote, or list.
108 // It can still be a table header, so table detection remains below.
109 const node =
110 (/^[a-z]/i.test(current()) ? undefined : (
111 parseFence() ??
112 parseHeading() ??
113 parseThematicBreak() ??
114 parseBlockquote() ??
115 parseList()
116 )) ??
117 parseTable() ??
118 parseHtmlBlock() ??
119 parseParagraph()
120​
121 nodes.push(node)
122 }
123​
124 budget.depth--
125 return nodes
126 }
127​
128 function parseExtensionBlock(): BlockNode | undefined {
129 for (const extension of options.extensions ?? []) {
130 let consumed = 0
131 const node = extension.parseBlock?.({
132 lines: inputLines,
133 index: cursor,
134 options: options,
135 parseInline: value => parseInline(value, options),
136 parseBlocks: value => createBlockParser(normalizeInput(value).split('\n'), options, slugger, budget).parse(),
137 consume: lines => {
138 consumed = lines
139 },
140 })
141​
142 if (node) {
143 cursor += Math.max(consumed, 1)
144 return node
145 }
146 }
147​
148 return undefined
149 }
150​
151 function parseFence(): CodeBlockNode | undefined {
152 const match = current().match(/^( {0,3})(`{3,}|~{3,})(.*)$/)
153 if (!match) return undefined
154​
155 const fence = match[2]!
156 const info = match[3]!.trim()
157 const code: string[] = []
158 cursor++
159​
160 while (cursor < inputLines.length) {
161 const line = current()
162 if (line.includes(fence) && /^ {0,3}(?:`+|~+)\s*$/.test(line)) {
163 cursor++
164 break
165 }
166 code.push(stripIndent(line, match[1]!.length))
167 cursor++
168 }
169​
170 return {
171 type: 'code',
172 value: code.join('\n'),
173 ...parseCodeInfo(info),
174 }
175 }
176​
177 function parseHeading(): HeadingNode | undefined {
178 const match = current().match(/^ {0,3}(#{1,6})(?:[ \t]+(.*)|[ \t]*)$/)
179 if (!match) return undefined
180​
181 const depth = match[1]!.length as HeadingNode['depth']
182 const rawValue = match[2] ?? ''
183 const value = (/^#+[ \t]*$/.test(rawValue) ? '' : rawValue.replace(/[ \t]+#+[ \t]*$/, '')).trim()
184 const children = parseInline(value, options)
185 const id = createHeadingId(children)
186 cursor++
187​
188 return id ? { type: 'heading', depth, id, children } : { type: 'heading', depth, children }
189 }
190​
191 function parseThematicBreak(): BlockNode | undefined {
192 if (!/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/.test(current())) return undefined
193 cursor++
194 return { type: 'thematicBreak' }
195 }
196​
197 function parseBlockquote(): BlockNode | undefined {
198 if (!/^ {0,3}>\s?/.test(current())) return undefined
199​
200 const quoted: string[] = []
201 while (cursor < inputLines.length) {
202 const line = current()
203 const match = line.match(/^ {0,3}>\s?(.*)$/s)
204 if (!match) {
205 if (!isBlank(line)) break
206 looseBlocks = true
207 }
208 quoted.push(match?.[1] ?? '')
209 cursor++
210 }
211​
212 return {
213 type: 'blockquote',
214 children: createBlockParser(quoted, options, slugger, budget).parse(),
215 }
216 }
217​
218 function parseList(): ListNode | undefined {
219 const first = listMarker(current())
220 if (!first) return undefined
221​
222 const items: ListItemNode[] = []
223 const ordered = first.ordered
224 const baseIndent = first.indent
225 let loose = false
226​
227 while (cursor < inputLines.length) {
228 const marker = listMarker(current())
229 if (!marker || marker.marker !== first.marker || marker.indent !== baseIndent) break
230​
231 let firstLine = marker.content
232 const task = firstLine.match(/^\[([ xX])\]\s+(.*)$/)
233 const checked = task ? task[1]!.toLowerCase() === 'x' : undefined
234 if (task) firstLine = task[2]!
235​
236 const itemLines = [firstLine]
237 cursor++
238​
239 while (cursor < inputLines.length) {
240 const line = current()
241 const nextMarker = listMarker(line)
242 if (nextMarker && nextMarker.indent === baseIndent) break
243 if (isBlank(line)) {
244 let nextIndex = cursor
245 while (nextIndex < inputLines.length && isBlank(inputLines[nextIndex]!)) nextIndex++
246 const following = inputLines[nextIndex]
247 if (following === undefined) break
248​
249 const followingMarker = listMarker(following)
250 if (followingMarker?.indent === baseIndent) {
251 if (followingMarker.marker !== first.marker) break
252 loose = true
253 cursor = nextIndex
254 break
255 }
256​
257 if (leadingSpaces(following) < marker.contentIndent) break
258​
259 while (cursor < nextIndex) itemLines.push(stripIndent(inputLines[cursor++]!, marker.contentIndent))
260 continue
261 }
262 if (leadingSpaces(line) >= marker.contentIndent) {
263 itemLines.push(stripIndent(line, marker.contentIndent))
264 cursor++
265 continue
266 }
267 if (isBlockStart(line, next())) break
268 itemLines.push(line.trimStart())
269 cursor++
270 }
271​
272 const parser = createBlockParser(itemLines, options, slugger, budget)
273 const children = parser.parse()
274 loose ||= parser.loose
275 const item: ListItemNode = { type: 'listItem', children }
276 if (checked !== undefined) item.checked = checked
277 items.push(item)
278 }
279​
280 return {
281 type: 'list',
282 ordered,
283 ...(ordered && { start: first.number! }),
284 ...(loose && { loose: true }),
285 items,
286 }
287 }
288​
289 function parseTable(): TableNode | undefined {
290 const header = current()
291 const delimiter = next()
292 if (!delimiter || !looksLikeTableHeader(header, delimiter)) return undefined
293​
294 const headerCells = splitTableRow(header)
295 const align = splitTableRow(delimiter).map(parseAlign)
296 const columns = headerCells.length
297 const rows: TableCellNode[][] = []
298 cursor += 2
299​
300 while (cursor < inputLines.length) {
301 const line = current()
302 if (isBlank(line) || isBlockStart(line, next())) break
303 const values = splitTableRow(line)
304 rows.push(Array.from({ length: columns }, (_, index) => cell(values[index] ?? '', options)))
305 cursor++
306 }
307​
308 return {
309 type: 'table',
310 align,
311 header: headerCells.map(value => cell(value, options)),
312 rows,
313 }
314 }
315​
316 function parseHtmlBlock(): BlockNode | undefined {
317 if (!options.allowHtml || !/^ {0,3}<([A-Za-z][\w:-]*|!--|\/[A-Za-z])/.test(current())) return undefined
318​
319 const html: string[] = []
320 if (/^ {0,3}<!--/.test(current())) {
321 while (cursor < inputLines.length) {
322 const line = current()
323 html.push(line)
324 cursor++
325 if (line.includes('-->')) break
326 }
327 return { type: 'html', value: html.join('\n') }
328 }
329​
330 while (cursor < inputLines.length && !isBlank(current())) {
331 html.push(current())
332 cursor++
333 }
334​
335 return { type: 'html', value: html.join('\n') }
336 }
337​
338 function parseParagraph(): BlockNode {
339 const lines: string[] = []
340​
341 while (cursor < inputLines.length) {
342 const line = current()
343 if (isBlank(line)) break
344 if (lines.length > 0 && isBlockStart(line, next())) break
345 lines.push(line.trim())
346 cursor++
347 }
348​
349 return {
350 type: 'paragraph',
351 children: parseInline(lines.join('\n'), options),
352 }
353 }
354​
355 function createHeadingId(children: InlineNode[]): string | undefined {
356 if (options.headingIds === false) return undefined
357 const text = plainText(children)
358 if (typeof options.headingIds === 'function') return options.headingIds(text, cursor)
359 return slugger(text)
360 }
361​
362 function current(): string {
363 return inputLines[cursor] ?? ''
364 }
365​
366 function next(): string | undefined {
367 return inputLines[cursor + 1]
368 }
370​
371function parseCodeInfo(info: string): Omit<CodeBlockNode, 'type' | 'value'> {
372 const langMatch = info.match(/^([A-Za-z0-9_+.#-]+)/)
373 const lang = langMatch?.[1]
374 const meta = lang ? info.slice(lang.length).trim() : info
375 const title = meta.match(/(?:^|\s)(?:title|file)=(?:"([^"]+)"|'([^']+)'|([^\s}]+))/)?.slice(1).find(Boolean)
376 const framework = meta.match(/(?:^|\s)framework=(?:"([^"]+)"|'([^']+)'|([^\s}]+))/)?.slice(1).find(Boolean)
377 const rangeMatch = meta.match(/\{([^}]+)\}|(?:^|\s)lines=([^\s]+)/)
378 const highlightLines = rangeMatch ? parseLineRanges(rangeMatch[1] ?? rangeMatch[2]!) : []
379​
380 return {
381 ...(lang && { lang }),
382 ...(meta && { meta }),
383 ...(title && { title, file: title }),
384 ...(framework && { framework: framework.toLowerCase() }),
385 ...(highlightLines.length && { highlightLines }),
386 }
388​
389function extractDefinitions(lines: string[]) {
390 const references: NonNullable<ParseOptions['references']> = Object.create(null)
391 const footnotes: NonNullable<ParseOptions['footnotes']> = Object.create(null)
392 const footnoteIds = createSlugger(footnoteId)
393 const remaining: string[] = []
394 let activeFence = ''
395 let index = 0
396​
397 while (index < lines.length) {
398 const line = lines[index]!
399 const fence = (!activeFence || line.includes(activeFence)) && line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/)
400 if (fence) {
401 if (!activeFence) activeFence = fence[1]!
402 else if (fence[1]!.startsWith(activeFence) && isBlank(fence[2]!)) activeFence = ''
403 } else if (!activeFence) {
404 const footnote = line.match(/^ {0,3}\[\^([^\]\n]+)\]:[ \t]*(.*)$/)
405 if (footnote) {
406 const label = footnote[1]!
407 const content = [footnote[2] ?? '']
408 index++
409​
410 while (index < lines.length) {
411 const continuation = lines[index]!
412 if (!/^(?: {4,}|\t)/.test(continuation)) break
413 content.push(continuation.replace(/^(?: {4}|\t)/, ''))
414 index++
415 }
416​
417 const key = normalizeReferenceLabel(label)
418 if (!footnotes[key]) {
419 footnotes[key] = { label, content: content.join('\n'), id: footnoteIds(label) }
420 }
421 continue
422 }
423​
424 const definition = line.match(/^ {0,3}\[([^\]\n]+)\]:[ \t]*(\S.*)$/)
425 const destination = definition && parseDestination(definition[2]!.trimEnd())
426 if (destination) {
427 references[normalizeReferenceLabel(definition![1]!)] ??= destination
428 index++
429 continue
430 }
431 }
432​
433 remaining.push(line)
434 index++
435 }
436​
437 return { lines: remaining, references, footnotes }
439​
440function createFootnotesBlock(
441 footnotes: NonNullable<ParseOptions['footnotes']>,
442 footnoteOrder: string[],
443 options: ParseOptions,
444 slugger: Slugger,
445): BlockNode {
446 const items: FootnoteItemNode[] = []
447 for (let index = 0; index < footnoteOrder.length; index++) {
448 const key = footnoteOrder[index]!
449 const definition = footnotes[key]
450 if (!definition) continue
451 items.push({
452 id: definition.id ?? footnoteId(definition.label),
453 number: index + 1,
454 children: createBlockParser(normalizeInput(definition.content).split('\n'), options, slugger).parse(),
455 })
456 }
457 for (const item of items) {
458 const count = options.footnoteCounts?.[footnoteOrder[item.number - 1]!] ?? 1
459 if (count > 1) item.referenceCount = count
460 }
461 return { type: 'footnotes', items }
463​
464function parseLineRanges(value: string): number[] {
465 const lines = new Set<number>()
466 for (const part of value.split(',')) {
467 const match = part.trim().match(/^(\d+)(?:-(\d+))?$/)
468 if (!match) continue
469 const start = Number(match[1])
470 const end = Number(match[2] ?? match[1])
471 // Larger integers can stop line++ from making progress.
472 if (end > Number.MAX_SAFE_INTEGER) continue
473 for (let line = start; line <= end && line < start + 1000; line++) lines.add(line)
474 }
475 return [...lines].sort((a, b) => a - b)
477​
478function listMarker(line: string):
479 | {
480 ordered: boolean
481 number?: number
482 indent: number
483 marker: string
484 contentIndent: number
485 content: string
486 }
487 | undefined {
488 const match = line.match(/^(\s{0,8})([-+*]|\d{1,9}[.)])(?:([ \t]+)(.*))?$/)
489 if (!match) return undefined
490​
491 const marker = match[2]!
492 const ordered = /\d/.test(marker[0]!)
493 return {
494 ordered,
495 ...(ordered && { number: Number.parseInt(marker, 10) }),
496 indent: match[1]!.length,
497 marker: ordered ? marker.at(-1)! : marker,
498 contentIndent: match[1]!.length + marker.length + (match[3]?.length ?? 1),
499 content: match[4] ?? '',
500 }
502​
503function leadingSpaces(line: string): number {
504 return line.match(/^ */)?.[0].length ?? 0
506​
507function isBlockStart(line: string, next?: string): boolean {
508 const marker = listMarker(line)
509 return (
510 /^ {0,3}(?:`{3,}|~{3,}|#{1,6}(?:\s|$)|([-*_])(?:\s*\1){2,}\s*$|>)/.test(line) ||
511 (marker !== undefined && (!marker.ordered || marker.number === 1)) ||
512 (!!next && looksLikeTableHeader(line, next))
513 )
515​
516function looksLikeTableHeader(header: string, delimiter: string): boolean {
517 if (!header.includes('|')) return false
518 const cells = splitTableRow(delimiter)
519 return cells.length === splitTableRow(header).length && cells.every(cell => /^:?-+:?$/.test(cell.trim()))
521​
522function splitTableRow(value: string): string[] {
523 const row = value.trim()
524​
525 const cells: string[] = []
526 let current = ''
527 for (let index = row.startsWith('|') ? 1 : 0; index < row.length; index++) {
528 const char = row[index]!
529 if (char === '\\' && row[index + 1] === '|') {
530 current += '|'
531 index++
532 continue
533 }
534 if (char === '|') {
535 cells.push(current.trim())
536 current = ''
537 continue
538 }
539 current += char
540 }
541 if (current || !row.endsWith('|') || !cells.length) cells.push(current.trim())
542 return cells
544​
545function parseAlign(value: string): 'left' | 'center' | 'right' | undefined {
546 const trimmed = value.trim()
547 if (trimmed.startsWith(':') && trimmed.endsWith(':')) return 'center'
548 if (trimmed.endsWith(':')) return 'right'
549 if (trimmed.startsWith(':')) return 'left'
550 return undefined
552​
553function cell(value: string, options: ParseOptions): TableCellNode {
554 return { type: 'tableCell', children: parseInline(value, options) }