| 1 | import type { |
| 2 | PreparserExtensionLoader, |
| 3 | SlideInfo, |
| 4 | SlidevData, |
| 5 | SlidevMarkdown, |
| 6 | SlidevPreparserExtension, |
| 7 | SourceSlideInfo, |
| 8 | } from '@slidev/types' |
| 9 | import { existsSync } from 'node:fs' |
| 10 | import { readFile, writeFile } from 'node:fs/promises' |
| 11 | import { slash } from '@antfu/utils' |
| 12 | import { dirname, isAbsolute, relative, resolve } from 'pathe' |
| 13 | import YAML from 'yaml' |
| 14 | import { detectFeatures, parse, parseRangeString, stringify } from './core' |
| 15 | |
| 16 | /** |
| 17 | * Whether `filePath` resolves inside any of `roots` (no `..` escape). |
| 18 | * Inlined here (rather than imported from the `slidev` package) because |
| 19 | * `@slidev/parser` must stay independent of `@slidev/slidev`. |
| 20 | */ |
| 21 | export function isPathInsideRoots(filePath: string, roots: string[]): boolean { |
| 22 | return roots.some((root) => { |
| 23 | const rel = relative(root, filePath) |
| 24 | return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel)) |
| 25 | }) |
| 26 | } |
| 27 | |
| 28 | const RE_FRONTMATTER_START = /^---(?:[^-].*)?$/ |
| 29 | const RE_BLANK_LINE = /^\s*$/ |
| 30 | const RE_FRONTMATTER_END = /^---$/ |
| 31 | const RE_CRLF = /\r?\n/g |
| 32 | |
| 33 | export * from './core' |
| 34 | |
| 35 | let preparserExtensionLoader: PreparserExtensionLoader | null = null |
| 36 | |
| 37 | export function injectPreparserExtensionLoader(fn: PreparserExtensionLoader) { |
| 38 | preparserExtensionLoader = fn |
| 39 | } |
| 40 | |
| 41 | export interface LoadRootsInfo { |
| 42 | roots: string[] |
| 43 | userRoot: string |
| 44 | /** |
| 45 | * When provided, `src:` includes resolving outside these roots are |
| 46 | * rejected (recorded as an error) instead of being loaded. Optional for |
| 47 | * backward compatibility with other `@slidev/parser` consumers. |
| 48 | */ |
| 49 | allowedRoots?: string[] |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Slidev data without config and themeMeta, |
| 54 | * because config and themeMeta depends on the theme to be loaded. |
| 55 | */ |
| 56 | export type LoadedSlidevData = Omit<SlidevData, 'config' | 'themeMeta'> |
| 57 | |
| 58 | export async function load( |
| 59 | options: LoadRootsInfo, |
| 60 | filepath: string, |
| 61 | sources: Record<string, string> | ((path: string) => Promise<string>) = {}, |
| 62 | mode?: string, |
| 63 | ): Promise<LoadedSlidevData> { |
| 64 | const loadSource = typeof sources === 'function' ? sources : async (path: string) => sources[path] ?? readFile(path, 'utf-8') |
| 65 | |
| 66 | const markdown = await loadSource(filepath) |
| 67 | |
| 68 | let extensions: SlidevPreparserExtension[] | undefined |
| 69 | if (preparserExtensionLoader) { |
| 70 | // #703 |
| 71 | // identify the headmatter, to be able to load preparser extensions |
| 72 | // (strict parsing based on the parsing code) |
| 73 | const lines = markdown.split(RE_CRLF) |
| 74 | let hm = '' |
| 75 | if (RE_FRONTMATTER_START.test(lines[0]) && !lines[1]?.match(RE_BLANK_LINE)) { |
| 76 | let hEnd = 1 |
| 77 | while (hEnd < lines.length && !RE_FRONTMATTER_END.test(lines[hEnd].trimEnd())) |
| 78 | hEnd++ |
| 79 | hm = lines.slice(1, hEnd).join('\n') |
| 80 | } |
| 81 | const o = YAML.parse(hm) as Record<string, unknown> ?? {} |
| 82 | extensions = await preparserExtensionLoader(options.roots, o, filepath, mode) |
| 83 | } |
| 84 | |
| 85 | const markdownFiles: Record<string, SlidevMarkdown> = {} |
| 86 | const watchFiles: Record<string, Set<number>> = {} |
| 87 | const slides: SlideInfo[] = [] |
| 88 | |
| 89 | async function loadMarkdown(path: string, range?: string, frontmatterOverride?: Record<string, unknown>, importers?: SourceSlideInfo[]) { |
| 90 | let md = markdownFiles[path] |
| 91 | if (!md) { |
| 92 | const raw = await loadSource(path) |
| 93 | md = await parse(raw, path, extensions) |
| 94 | markdownFiles[path] = md |
| 95 | watchFiles[path] = new Set() |
| 96 | } |
| 97 | |
| 98 | const directImporter = importers?.at(-1) |
| 99 | for (const index of parseRangeString(md.slides.length, range)) { |
| 100 | const subSlide = md.slides[index - 1] |
| 101 | try { |
| 102 | await loadSlide(md, subSlide, frontmatterOverride, importers) |
| 103 | } |
| 104 | catch (e) { |
| 105 | md.errors ??= [] |
| 106 | md.errors.push({ |
| 107 | row: subSlide.start, |
| 108 | message: `Error when loading slide: ${e}`, |
| 109 | }) |
| 110 | continue |
| 111 | } |
| 112 | if (directImporter) |
| 113 | (directImporter.imports ??= []).push(subSlide) |
| 114 | } |
| 115 | |
| 116 | return md |
| 117 | } |
| 118 | |
| 119 | async function loadSlide(md: SlidevMarkdown, slide: SourceSlideInfo, frontmatterOverride?: Record<string, unknown>, importChain?: SourceSlideInfo[]) { |
| 120 | if (slide.frontmatter.disabled || slide.frontmatter.hide) |
| 121 | return |
| 122 | if (slide.frontmatter.src) { |
| 123 | const [rawPath, rangeRaw] = slide.frontmatter.src.split('#') |
| 124 | const path = slash( |
| 125 | rawPath.startsWith('/') |
| 126 | ? resolve(options.userRoot, rawPath.substring(1)) |
| 127 | : resolve(dirname(slide.filepath), rawPath), |
| 128 | ) |
| 129 | |
| 130 | frontmatterOverride = { |
| 131 | ...slide.frontmatter, |
| 132 | ...frontmatterOverride, |
| 133 | } |
| 134 | delete frontmatterOverride.src |
| 135 | |
| 136 | const ancestorPaths = new Set((importChain ?? []).map(s => s.filepath)) |
| 137 | if (path === slide.filepath || ancestorPaths.has(path)) { |
| 138 | md.errors ??= [] |
| 139 | md.errors.push({ |
| 140 | row: slide.start, |
| 141 | message: `Circular import detected for "${slide.frontmatter.src}" (${path})`, |
| 142 | }) |
| 143 | return |
| 144 | } |
| 145 | |
| 146 | if (options.allowedRoots && !isPathInsideRoots(path, options.allowedRoots)) { |
| 147 | md.errors ??= [] |
| 148 | md.errors.push({ |
| 149 | row: slide.start, |
| 150 | message: `Imported markdown escapes the project root: ${path}`, |
| 151 | }) |
| 152 | } |
| 153 | else if (!existsSync(path)) { |
| 154 | md.errors ??= [] |
| 155 | md.errors.push({ |
| 156 | row: slide.start, |
| 157 | message: `Imported markdown file not found: ${path}`, |
| 158 | }) |
| 159 | } |
| 160 | else { |
| 161 | await loadMarkdown(path, rangeRaw, frontmatterOverride, importChain ? [...importChain, slide] : [slide]) |
| 162 | } |
| 163 | } |
| 164 | else { |
| 165 | slides.push({ |
| 166 | frontmatter: { ...slide.frontmatter, ...frontmatterOverride }, |
| 167 | content: slide.content, |
| 168 | revision: slide.revision, |
| 169 | frontmatterRaw: slide.frontmatterRaw, |
| 170 | note: slide.note, |
| 171 | title: slide.title, |
| 172 | level: slide.level, |
| 173 | index: slides.length, |
| 174 | importChain, |
| 175 | source: slide, |
| 176 | }) |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | const entry = await loadMarkdown(slash(filepath)) |
| 181 | |
| 182 | const headmatter = { ...entry.slides[0]?.frontmatter } |
| 183 | if (slides[0]?.title) |
| 184 | headmatter.title ??= slides[0].title |
| 185 | |
| 186 | return { |
| 187 | slides, |
| 188 | entry, |
| 189 | headmatter, |
| 190 | features: detectFeatures(slides.map(s => s.source.raw).join('')), |
| 191 | markdownFiles, |
| 192 | watchFiles, |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | export async function save(markdown: SlidevMarkdown) { |
| 197 | const fileContent = stringify(markdown) |
| 198 | await writeFile(markdown.filepath, fileContent, 'utf-8') |
| 199 | return fileContent |
| 200 | } |
| 201 |