forked from vuejs/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.data.ts
69 lines (62 loc) · 1.44 KB
/
api.data.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// api.data.ts
// a file ending with data.(j|t)s will be evaluated in Node.js
import fs from 'fs'
import path from 'path'
import { sidebar } from '../../.vitepress/config'
export interface APIGroup {
text: string
items: {
text: string
link: string
headers: string[]
}[]
}
// declare resolved data type
export declare const data: APIGroup[]
export default {
// declare files that should trigger HMR
watch: './*.md',
// read from fs and generate the data
load(): APIGroup[] {
return sidebar['/api/'].map((group) => ({
text: group.text,
items: group.items.map((item) => ({
...item,
headers: parsePageHeaders(item.link)
}))
}))
}
}
const headersCache = new Map<
string,
{
headers: string[]
timestamp: number
}
>()
function parsePageHeaders(link: string) {
const fullPath = path.join(__dirname, '../', link) + '.md'
const timestamp = fs.statSync(fullPath).mtimeMs
const cached = headersCache.get(fullPath)
if (cached && timestamp === cached.timestamp) {
return cached.headers
}
const src = fs.readFileSync(fullPath, 'utf-8')
const h2s = src.match(/^## [^\n]+/gm)
let headers: string[] = []
if (h2s) {
headers = h2s.map((h) =>
h
.slice(2)
.replace(/<sup class=.*/, '')
.replace(/\\</g, '<')
.replace(/`([^`]+)`/g, '$1')
.trim()
)
}
headersCache.set(fullPath, {
timestamp,
headers
})
return headers
}