-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
index.js
47 lines (40 loc) · 1.23 KB
/
index.js
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
38
39
40
41
42
43
44
45
46
47
/**
* @typedef {import('@mdx-js/mdx').CompileOptions} Options
*/
import fs from 'node:fs/promises'
import {createFormatAwareProcessors} from '@mdx-js/mdx/internal-create-format-aware-processors'
import {extnamesToRegex} from '@mdx-js/mdx/internal-extnames-to-regex'
import {VFile} from 'vfile'
/**
* Create a loader to handle markdown and MDX.
*
* @param {Readonly<Options> | null | undefined} [options]
* Configuration (optional).
* @returns
* Loader.
*/
export function createLoader(options) {
const options_ = options || {}
const {extnames, process} = createFormatAwareProcessors(options_)
const regex = extnamesToRegex(extnames)
return {load}
/**
* @param {string} href
* URL.
* @param {unknown} context
* Context.
* @param {Function} defaultLoad
* Default `load` function.
* @returns
* Result.
*/
async function load(href, context, defaultLoad) {
const url = new URL(href)
if (url.protocol === 'file:' && regex.test(url.pathname)) {
const value = await fs.readFile(url)
const file = await process(new VFile({value, path: url}))
return {format: 'module', shortCircuit: true, source: String(file)}
}
return defaultLoad(href, context, defaultLoad)
}
}