-
Notifications
You must be signed in to change notification settings - Fork 94
/
docs.tsx
240 lines (199 loc) · 6.85 KB
/
docs.tsx
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import type { Doc, DocToC } from '@/app/[...slug]/DocsContext'
import * as components from '@/components/mdx'
import { rehypeCode } from '@/components/mdx/Code/rehypeCode'
import { Codesandbox } from '@/components/mdx/Codesandbox'
import { fetchCSB } from '@/components/mdx/Codesandbox/fetchCSB'
import { rehypeCodesandbox } from '@/components/mdx/Codesandbox/rehypeCodesandbox'
import { rehypeDetails } from '@/components/mdx/Details/rehypeDetails'
import { rehypeGha } from '@/components/mdx/Gha/rehypeGha'
import { rehypeImg } from '@/components/mdx/Img/rehypeImg'
import { rehypeSummary } from '@/components/mdx/Summary/rehypeSummary'
import { rehypeToc } from '@/components/mdx/Toc/rehypeToc'
import resolveMdxUrl from '@/utils/resolveMdxUrl'
import matter from 'gray-matter'
import { compileMDX } from 'next-mdx-remote/rsc'
import fs from 'node:fs'
import React, { cache } from 'react'
import rehypePrismPlus from 'rehype-prism-plus'
import remarkGFM from 'remark-gfm'
/**
* Checks for .md(x) file extension
*/
export const MARKDOWN_REGEX = /\.mdx?/
/**
* Uncomments frontMatter from vanilla markdown
*/
const FRONTMATTER_REGEX = /^<!--[\s\n]*?(?=---)|(?!---)[\s\n]*?-->/g
/**
* Removes multi and single-line comments from markdown
*/
const COMMENT_REGEX = /<!--(.|\n)*?-->|<!--[^\n]*?\n/g
/**
* Removes <https://inline.links> formatting from markdown
*/
const INLINE_LINK_REGEX = /<(http[^>]+)>/g
/**
* Recursively crawls a directory, returning an array of file paths.
*/
async function crawl(dir: string, filter?: RegExp, files: string[] = []) {
if (fs.lstatSync(dir).isDirectory()) {
const filenames = fs.readdirSync(dir) as string[]
await Promise.all(filenames.map(async (filename) => crawl(`${dir}/${filename}`, filter, files)))
} else if (!filter || filter.test(dir)) {
files.push(dir)
}
return files
}
/**
* Fetches all docs, filters to a lib if specified.
*
* @param root - absolute or relative (to cwd) path to docs folder
*/
const MDX_BASEURL = process.env.MDX_BASEURL
// console.log('MDX_BASEURL', MDX_BASEURL)
async function _getDocs(
root: string,
slugOfInterest: string[] | null,
slugOnly = false,
): Promise<Doc[]> {
const files = await crawl(root, MARKDOWN_REGEX)
// console.log('files', files)
const docs = await Promise.all(
files.map(async (file) => {
const relFilePath = file.substring(root.length) // "/getting-started/tutorials/store.mdx"
// Get slug from local path
const path = file.replace(`${root}/`, '')
const slug = [...path.replace(MARKDOWN_REGEX, '').toLowerCase().split('/')]
//
// "Lightest" version of the doc (for `generateStaticParams`)
//
if (slugOnly) {
return { slug } as Doc
}
//
// Common infos (for every `docs`)
//
const url = `/${slug.join('/')}`
// editURL
const EDIT_BASEURL = process.env.EDIT_BASEURL
const editURL = EDIT_BASEURL?.length ? file.replace(root, EDIT_BASEURL) : undefined
// Read & parse doc
//
// frontmatter
//
const str = await fs.promises.readFile(file, { encoding: 'utf-8' })
const compiled = matter(str)
const frontmatter = compiled.data
const _lastSegment = slug[slug.length - 1]
const title: string = frontmatter.title ?? _lastSegment.replace(/\-/g, ' ')
const description: string = frontmatter.description ?? ''
const sourcecode: string = frontmatter.sourcecode ?? ''
const SOURCECODE_BASEURL = process.env.SOURCECODE_BASEURL
const sourcecodeURL = SOURCECODE_BASEURL?.length
? `${SOURCECODE_BASEURL}/${sourcecode}`
: undefined
const nav: number = frontmatter.nav ?? Infinity
const frontmatterImage: string | undefined = frontmatter.image
const srcImage = frontmatterImage || process.env.LOGO
const image: string = srcImage ? resolveMdxUrl(srcImage, relFilePath, MDX_BASEURL) : ''
//
// MDX content
//
// Skip docs other than `slugOfInterest` -- better perfs)
// if (JSON.stringify(slug) !== JSON.stringify(slugOfInterest)) {
// return {
// slug,
// url,
// editURL,
// title,
// description,
// nav,
// } as Doc
// }
// Sanitize markdown
let content = compiled.content
// Remove <!-- --> comments from frontMatter
.replace(FRONTMATTER_REGEX, '')
// Remove extraneous comments from post
.replace(COMMENT_REGEX, '')
// Remove inline link syntax
.replace(INLINE_LINK_REGEX, '$1')
//
// inline images
//
const boxes: string[] = []
const tableOfContents: DocToC[] = []
const { content: jsx } = await compileMDX({
source: `# ${title}\n ${content}`,
options: {
mdxOptions: {
remarkPlugins: [remarkGFM],
rehypePlugins: [
rehypeImg(relFilePath, MDX_BASEURL),
rehypeDetails,
rehypeSummary,
rehypeGha,
rehypePrismPlus,
rehypeCode(),
rehypeCodesandbox(boxes), // 1. put all Codesandbox[id] into `doc.boxes`
rehypeToc(tableOfContents, url, title), // 2. will populate `doc.tableOfContents`
],
},
},
components: {
...components,
Codesandbox: async (props: React.ComponentProps<typeof Codesandbox>) => {
const ids = boxes // populated from 1.
// console.log('ids', ids)
//
// Batch fetch all CSBs of the page
//
const csbs = await fetchCSB(...ids)
// console.log('boxes', boxes)
const data = csbs[props.id]
// console.log('data', data)
// Merge initial props with data
const merged = { ...props, ...data }
return <Codesandbox {...merged} />
},
},
})
return {
slug,
url,
editURL,
sourcecode,
sourcecodeURL,
title,
image,
description,
nav,
content: jsx,
boxes,
tableOfContents,
}
}),
)
// console.log('docs', docs)
return docs.sort((a, b) => a.nav - b.nav)
}
// export const getDocs = pMemoize(_getDocs, { cacheKey: ([lib]) => lib })
export const getDocs = cache(_getDocs)
// export const getDocs = cache(_getDocs)
async function _getData(...slug: string[]) {
// console.log('getData', slug)
const { MDX } = process.env
if (!MDX) throw new Error('MDX env var not set')
const docs = await getDocs(MDX, slug)
// console.log('allDocs', docs)
const url = `/${slug.join('/')}`.toLowerCase()
// console.log('url', url)
const doc = docs.find((doc) => doc.url === url)
// console.log('doc', doc)
if (!doc) throw new Error(`Doc not found: ${url}`)
return {
docs,
doc,
}
}
export const getData = cache(_getData)