返回 slidev
core.ts
根目录 / packages / parser / src / core.ts
1 import type { FrontmatterStyle, SlidevDetectedFeatures, SlidevMarkdown, SlidevPreparserExtension, SourceSlideInfo } from '@slidev/types'
2 import { ensurePrefix } from '@antfu/utils'
3 import YAML from 'yaml'
4
5 const RE_FRONTMATTER = /^---.*\r?\n([\s\S]*?)---/
6 const RE_YAML_CODEBLOCK = /^\s*```ya?ml([\s\S]*?)```/
7 const RE_DOLLAR_INLINE = /\$.*?\$/
8 const RE_DOLLAR_BLOCK = /\$\$/
9 const RE_MONACO_BLOCK = /\{monaco.*\}/
10 const RE_TWEET_TAG = /<Tweet\b/
11 const RE_BLUESKY_TAG = /<BlueSky\b/
12 const RE_MERMAID_CODEBLOCK = /^```mermaid/m
13 const RE_HEADING = /^(#+) (.*)$/m
14 const RE_CODE_BLOCK = /^```[\s\S]+?^```/gm
15 const RE_LEADING_FENCE = /^\s*(?:`+|~+)/
16 const RE_TILDE_FENCE = /^ {0,3}~~~/
17 const RE_CRLF = /\r?\n/g
18 const RE_BOM = /^\uFEFF/
19
20 export interface SlidevParserOptions {
21 noParseYAML?: boolean
22 preserveCR?: boolean
23 }
24
25 function advanceHtmlCommentState(line: string, inHtmlComment: boolean) {
26 let cursor = 0
27
28 while (cursor < line.length) {
29 if (inHtmlComment) {
30 const end = line.indexOf('-->', cursor)
31 if (end < 0)
32 return true
33 inHtmlComment = false
34 cursor = end + 3
35 }
36 else {
37 const start = line.indexOf('<!--', cursor)
38 if (start < 0)
39 return false
40 const end = line.indexOf('-->', start + 4)
41 if (end < 0)
42 return true
43 cursor = end + 3
44 }
45 }
46
47 return inHtmlComment
48 }
49
50 export function stringify(data: SlidevMarkdown) {
51 return `${data.slides.map(stringifySlide).join('\n').trim()}\n`
52 }
53
54 export function stringifySlide(data: SourceSlideInfo, idx = 0) {
55 return (data.raw.startsWith('---') || idx === 0)
56 ? data.raw
57 : `---\n${ensurePrefix('\n', data.raw)}`
58 }
59
60 export function prettifySlide(data: SourceSlideInfo) {
61 const trimed = data.content.trim()
62 data.content = trimed
63 ? `\n${data.content.trim()}\n`
64 : ''
65 data.raw = data.frontmatterDoc?.contents
66 ? data.frontmatterStyle === 'yaml'
67 ? `\`\`\`yaml\n${data.frontmatterDoc.toString().trim()}\n\`\`\`\n${data.content}`
68 : `---\n${data.frontmatterDoc.toString().trim()}\n---\n${data.content}`
69 : data.content
70 if (data.note)
71 data.raw += `\n<!--\n${data.note.trim()}\n-->\n`
72 return data
73 }
74
75 export function prettify(data: SlidevMarkdown) {
76 data.slides.forEach(prettifySlide)
77 return data
78 }
79
80 function matter(code: string, options: SlidevParserOptions) {
81 let type: FrontmatterStyle | undefined
82 let raw: string | undefined
83
84 let content = code
85 .replace(RE_FRONTMATTER, (_, f) => {
86 type = 'frontmatter'
87 raw = f
88 return ''
89 })
90
91 if (type !== 'frontmatter') {
92 content = content
93 .replace(RE_YAML_CODEBLOCK, (_, f) => {
94 type = 'yaml'
95 raw = f
96 return ''
97 })
98 }
99
100 const doc = raw && !options.noParseYAML
101 ? YAML.parseDocument(raw)
102 : undefined
103
104 return {
105 type,
106 raw,
107 doc,
108 data: doc?.toJSON(),
109 content,
110 }
111 }
112
113 const IMAGE_EXTENSIONS = /\.(?:png|jpe?g|gif|svg|webp|avif|ico|bmp|tiff?)$/i
114 const RE_MD_IMAGE_TITLE = /\s+(?:"[^"]*"|'[^']*')\s*$/
115
116 /**
117 * Strip the optional CommonMark title and the angle-bracket form from a
118 * markdown image destination, so `![a](/x.png "Title")` yields `/x.png`.
119 */
120 function normalizeMarkdownImageTarget(target: string) {
121 const url = target.trim().replace(RE_MD_IMAGE_TITLE, '').trim()
122 return url.startsWith('<') && url.endsWith('>')
123 ? url.slice(1, -1).trim()
124 : url
125 }
126
127 /**
128 * Extract image URLs from slide content and frontmatter.
129 * Strips code blocks first to avoid false positives.
130 */
131 export function extractImagesUsage(content: string, frontmatter: Record<string, any>): string[] {
132 const images = new Set<string>()
133
134 // Collect from frontmatter keys
135 for (const key of ['image', 'backgroundImage', 'background']) {
136 const val = frontmatter[key]
137 if (typeof val === 'string' && val && !val.startsWith('data:')) {
138 // For `background`, only include if it looks like an image URL
139 if (key === 'background') {
140 if (IMAGE_EXTENSIONS.test(val) || val.startsWith('/') || val.startsWith('http'))
141 images.add(val)
142 }
143 else {
144 images.add(val)
145 }
146 }
147 }
148
149 // Strip code blocks to avoid false positives
150 const stripped = content.replace(RE_CODE_BLOCK, '')
151
152 // Markdown images: ![alt](url), ![alt](url "title"), ![alt](<url>)
153 for (const [, target] of stripped.matchAll(/!\[[^\]]*\]\(([^)]+)\)/g)) {
154 const url = normalizeMarkdownImageTarget(target)
155 if (url && !url.startsWith('data:'))
156 images.add(url)
157 }
158
159 // Vue component props: src="url", image="url"
160 for (const [, url] of stripped.matchAll(/\b(?:src|image)=["']([^"']+)["']/g)) {
161 if (url && !url.startsWith('data:') && !url.includes('{{') && IMAGE_EXTENSIONS.test(url))
162 images.add(url.trim())
163 }
164
165 // Vue bound props: :src="'/path/to/img.png'"
166 for (const [, url] of stripped.matchAll(/:(?:src|image)=["']'([^']+)'["']/g)) {
167 if (url && !url.startsWith('data:') && IMAGE_EXTENSIONS.test(url))
168 images.add(url.trim())
169 }
170
171 // CSS url() with image extension filter
172 for (const [, url] of stripped.matchAll(/url\(["']?([^"')]+)["']?\)/g)) {
173 if (url && !url.startsWith('data:') && IMAGE_EXTENSIONS.test(url))
174 images.add(url.trim())
175 }
176
177 return Array.from(images)
178 }
179
180 export function detectFeatures(code: string): SlidevDetectedFeatures {
181 return {
182 katex: !!code.match(RE_DOLLAR_INLINE) || !!code.match(RE_DOLLAR_BLOCK),
183 monaco: RE_MONACO_BLOCK.test(code)
184 ? scanMonacoReferencedMods(code)
185 : false,
186 tweet: !!code.match(RE_TWEET_TAG),
187 bluesky: !!code.match(RE_BLUESKY_TAG),
188 mermaid: !!code.match(RE_MERMAID_CODEBLOCK),
189 }
190 }
191
192 /**
193 * Detect slide content that was parsed as frontmatter because the blank line
194 * after `---` is missing, e.g. `---\n<!-- note -->\n\n---`.
195 */
196 function isMisplacedFrontmatter(type: FrontmatterStyle | undefined, raw: string | undefined, data: unknown) {
197 if (type !== 'frontmatter' || !raw?.trim())
198 return false
199 if (raw.trimStart().startsWith('<!--'))
200 return true
201 return data != null && (typeof data !== 'object' || Array.isArray(data))
202 }
203
204 /**
205 * Keys produced by an HTML comment written inside frontmatter,
206 * e.g. `layout: center\n<!-- note -->` gives `{ "<!-- note -->": null }`.
207 */
208 function getHtmlCommentKeys(data: unknown) {
209 if (data == null || typeof data !== 'object' || Array.isArray(data))
210 return []
211 return Object.keys(data).filter(key => key.trimStart().startsWith('<!--'))
212 }
213
214 function resolveFrontmatter(type: FrontmatterStyle | undefined, raw: string | undefined, data: any): Record<string, any> {
215 if (isMisplacedFrontmatter(type, raw, data))
216 return {}
217 const commentKeys = getHtmlCommentKeys(data)
218 if (!commentKeys.length)
219 return data || {}
220 const frontmatter = { ...data }
221 for (const key of commentKeys)
222 delete frontmatter[key]
223 return frontmatter
224 }
225
226 const MISPLACED_FRONTMATTER_MESSAGE = 'Missing blank line after "---": the content below it was parsed as frontmatter and ignored. Add a blank line after "---" if it is slide content.'
227 const HTML_COMMENT_IN_FRONTMATTER_MESSAGE = 'HTML comments are not supported in frontmatter and were ignored. Use "#" for YAML comments.'
228
229 function checkMisplacedFrontmatter(slide: SourceSlideInfo, md: SlidevMarkdown) {
230 const data = slide.frontmatterDoc?.toJSON()
231 let message: string | undefined
232 if (isMisplacedFrontmatter(slide.frontmatterStyle, slide.frontmatterRaw, data))
233 message = MISPLACED_FRONTMATTER_MESSAGE
234 else if (slide.frontmatterStyle === 'frontmatter' && getHtmlCommentKeys(data).length)
235 message = HTML_COMMENT_IN_FRONTMATTER_MESSAGE
236 if (!message)
237 return
238 md.errors ??= []
239 md.errors.push({
240 row: slide.start,
241 message,
242 })
243 }
244
245 export function parseSlide(raw: string, options: SlidevParserOptions = {}): Omit<SourceSlideInfo, 'filepath' | 'index' | 'start' | 'contentStart' | 'end'> {
246 const matterResult = matter(raw, options)
247 let note: string | undefined
248 const frontmatter = resolveFrontmatter(matterResult.type, matterResult.raw, matterResult.data)
249 let content = matterResult.content.trim()
250 const revision = hash(raw.trim())
251
252 const comments = Array.from(content.matchAll(/<!--([\s\S]*?)-->/g))
253 if (comments.length) {
254 const last = comments[comments.length - 1]
255 if (last.index !== undefined && last.index + last[0].length >= content.length) {
256 note = last[1].trim()
257 content = content.slice(0, last.index).trim()
258 }
259 }
260
261 let title
262 let level
263 if (frontmatter.title || frontmatter.name) {
264 title = frontmatter.title || frontmatter.name
265 }
266 else {
267 // `#` lines inside a fenced block are code comments, not the slide title
268 const match = content.replace(RE_CODE_BLOCK, '').match(RE_HEADING)
269 title = match?.[2]?.trim()
270 level = match?.[1]?.length
271 }
272 if (frontmatter.level)
273 level = frontmatter.level || 1
274
275 const images = extractImagesUsage(content, frontmatter)
276
277 return {
278 raw,
279 title,
280 level,
281 revision,
282 content,
283 contentRaw: content,
284 frontmatter,
285 frontmatterStyle: matterResult.type,
286 frontmatterDoc: matterResult.doc,
287 frontmatterRaw: matterResult.raw,
288 note,
289 images,
290 }
291 }
292
293 export async function parse(
294 markdown: string,
295 filepath: string,
296 extensions?: SlidevPreparserExtension[],
297 options: SlidevParserOptions = {},
298 ): Promise<SlidevMarkdown> {
299 // a leading UTF-8 BOM would hide the headmatter, as the first line no longer starts with `---`
300 markdown = markdown.replace(RE_BOM, '')
301 const lines = markdown.split(options.preserveCR ? '\n' : RE_CRLF)
302 const slides: SourceSlideInfo[] = []
303
304 let start = 0
305 let contentStart = 0
306 let inHtmlComment = false
307
308 async function slice(end: number) {
309 if (start === end)
310 return
311 const raw = lines.slice(start, end).join('\n')
312 const slide: SourceSlideInfo = {
313 ...parseSlide(raw, options),
314 filepath,
315 index: slides.length,
316 start,
317 contentStart,
318 end,
319 }
320 if (extensions) {
321 for (const e of extensions) {
322 if (e.transformSlide) {
323 const newContent = await e.transformSlide(slide.content, slide.frontmatter)
324 if (newContent !== undefined)
325 slide.content = newContent
326 if (typeof slide.frontmatter.title === 'string') {
327 slide.title = slide.frontmatter.title
328 }
329 if (typeof slide.frontmatter.level === 'number') {
330 slide.level = slide.frontmatter.level
331 }
332 }
333
334 if (e.transformNote) {
335 const newNote = await e.transformNote(slide.note, slide.frontmatter)
336 if (newNote !== undefined)
337 slide.note = newNote
338 }
339 }
340 }
341 slides.push(slide)
342 start = end + 1
343 contentStart = end + 1
344 }
345
346 if (extensions) {
347 for (const e of extensions) {
348 if (e.transformRawLines)
349 await e.transformRawLines(lines)
350 }
351 }
352
353 for (let i = 0; i < lines.length; i++) {
354 const rawLine = lines[i]
355 const line = rawLine.trimEnd()
356 if (inHtmlComment) {
357 inHtmlComment = advanceHtmlCommentState(rawLine, true)
358 continue
359 }
360
361 if (line.startsWith('---')) {
362 await slice(i)
363
364 const next = lines[i + 1]
365 // found frontmatter, skip next dash
366 if (line[3] !== '-' && next?.trim()) {
367 start = i
368 for (i += 1; i < lines.length; i++) {
369 if (lines[i].trimEnd() === '---')
370 break
371 }
372 contentStart = i + 1
373 }
374 }
375 // skip code block
376 else if (line.trimStart().startsWith('```') || RE_TILDE_FENCE.test(line)) {
377 const codeBlockLevel = line.match(RE_LEADING_FENCE)![0]
378 let j = i + 1
379 for (; j < lines.length; j++) {
380 if (lines[j].startsWith(codeBlockLevel))
381 break
382 }
383 // Update i only when code block ends
384 if (j !== lines.length)
385 i = j
386 }
387 else {
388 inHtmlComment = advanceHtmlCommentState(rawLine, false)
389 }
390 }
391
392 if (start <= lines.length - 1)
393 await slice(lines.length)
394
395 const md: SlidevMarkdown = {
396 filepath,
397 raw: markdown,
398 slides,
399 }
400 for (const slide of slides)
401 checkMisplacedFrontmatter(slide, md)
402 return md
403 }
404
405 export function parseSync(
406 markdown: string,
407 filepath: string,
408 options: SlidevParserOptions = {},
409 ): SlidevMarkdown {
410 markdown = markdown.replace(RE_BOM, '')
411 const lines = markdown.split(options.preserveCR ? '\n' : RE_CRLF)
412 const slides: SourceSlideInfo[] = []
413
414 let start = 0
415 let contentStart = 0
416 let inHtmlComment = false
417
418 function slice(end: number) {
419 if (start === end)
420 return
421 const raw = lines.slice(start, end).join('\n')
422 const slide: SourceSlideInfo = {
423 ...parseSlide(raw, options),
424 filepath,
425 index: slides.length,
426 start,
427 contentStart,
428 end,
429 }
430 slides.push(slide)
431 start = end + 1
432 contentStart = end + 1
433 }
434
435 for (let i = 0; i < lines.length; i++) {
436 const rawLine = lines[i]
437 const line = rawLine.trimEnd()
438 if (inHtmlComment) {
439 inHtmlComment = advanceHtmlCommentState(rawLine, true)
440 continue
441 }
442
443 if (line.startsWith('---')) {
444 slice(i)
445
446 const next = lines[i + 1]
447 // found frontmatter, skip next dash
448 if (line[3] !== '-' && next?.trim()) {
449 start = i
450 for (i += 1; i < lines.length; i++) {
451 if (lines[i].trimEnd() === '---')
452 break
453 }
454 contentStart = i + 1
455 }
456 }
457 // skip code block
458 else if (line.trimStart().startsWith('```') || RE_TILDE_FENCE.test(line)) {
459 const codeBlockLevel = line.match(RE_LEADING_FENCE)![0]
460 let j = i + 1
461 for (; j < lines.length; j++) {
462 if (lines[j].startsWith(codeBlockLevel))
463 break
464 }
465 // Update i only when code block ends
466 if (j !== lines.length)
467 i = j
468 }
469 else {
470 inHtmlComment = advanceHtmlCommentState(rawLine, false)
471 }
472 }
473
474 if (start <= lines.length - 1)
475 slice(lines.length)
476
477 const md: SlidevMarkdown = {
478 filepath,
479 raw: markdown,
480 slides,
481 }
482 for (const slide of slides)
483 checkMisplacedFrontmatter(slide, md)
484 return md
485 }
486
487 function scanMonacoReferencedMods(md: string) {
488 const types = new Set<string>()
489 const deps = new Set<string>()
490 md.replace(
491 /^```(\w+)\s*\{monaco([^}]*)\}\s*(\S[\s\S]*?)^```/gm,
492 (full, lang = 'ts', kind: string, code: string) => {
493 lang = lang.trim()
494 const isDep = kind === '-run'
495 if (['js', 'javascript', 'ts', 'typescript'].includes(lang)) {
496 for (const [, , specifier] of code.matchAll(/\s+from\s+(["'])([/.\w@-]+)\1/g)) {
497 if (specifier) {
498 if (!'./'.includes(specifier))
499 types.add(specifier) // All local TS files are loaded by globbing
500 if (isDep)
501 deps.add(specifier)
502 }
503 }
504 }
505 return ''
506 },
507 )
508 return {
509 types: Array.from(types),
510 deps: Array.from(deps),
511 }
512 }
513
514 function hash(str: string) {
515 let hash = 0
516 for (let i = 0; i < str.length; i++) {
517 hash = ((hash << 5) - hash) + str.charCodeAt(i)
518 hash |= 0
519 }
520 return hash.toString(36).slice(0, 12)
521 }
522
523 export * from './config'
524 export * from './utils'
525
525 lines TYPESCRIPT