/
index.ts
37 lines (30 loc) · 1.19 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { extname } from 'pathe'
import type { ParsedContent, ContentTransformer } from '../../types'
import { getParser, getTransformers } from '#content/virtual/transformers'
// eslint-disable-next-line import/named
import { useNitroApp } from '#imports'
/**
* Parse content file using registered plugins
*/
export async function parseContent (id: string, content: string) {
const nitroApp = useNitroApp()
// Call hook before parsing the file
const file = { _id: id, content }
await nitroApp.hooks.callHook('content:file:beforeParse', file)
const ext = extname(id)
const plugin: ContentTransformer = getParser(ext)
if (!plugin) {
// eslint-disable-next-line no-console
console.warn(`${ext} files are not supported, "${id}" falling back to raw content`)
return file
}
const parsed: ParsedContent = await plugin.parse!(file._id, file.content)
const transformers = getTransformers(ext)
const result = await transformers.reduce(async (prev, cur) => {
const next = (await prev) || parsed
return cur.transform!(next)
}, Promise.resolve(parsed))
// Call hook after parsing the file
await nitroApp.hooks.callHook('content:file:afterParse', result)
return result
}