Expand file tree
/
Copy pathapi.js
More file actions
Latest commit
234 lines (224 loc) · 6.6 KB
/
Copy pathapi.js
File metadata and controls
234 lines (224 loc) · 6.6 KB
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
constfs=require('fs')
constmicro=require('micro')
constaxios=require('axios')
constpify=require('pify')
constglob=pify(require('glob'))
constmarked=require('marked')
consthighlightjs=require('highlight.js')
constfm=require('front-matter')
const{ resolve }=require('path')
constgithubHook=require('./gh-hook')
constreadFile=pify(fs.readFile)
constsend=micro.send
// Use highlight.js for code blocks
constrenderer=newmarked.Renderer()
renderer.code=(code,language)=>{
constvalidLang=!!(language&&highlightjs.getLanguage(language))
consthighlighted=validLang ? highlightjs.highlight(language,code).value : code
return`<pre><code class="hljs ${language}">${highlighted}</code></pre>`
}
renderer.heading=(text,level)=>{
constpatt=/\s?{([^}]+)}$/
letlink=patt.exec(text)
if(link&&link.length&&link[1]){
text=text.replace(patt,'')
link=link[1]
}else{
link=text.toLowerCase().replace(/[^\wА-яіІїЇєЄ\u4e00-\u9eff一-龠ぁ-ゔァ-ヴー々〆〤\u3130-\u318F\uAC00-\uD7AF]+/gi,'-')
}
return'<h'+level+' id="'+link+'">'+text+'</h'+level+'>'
}
marked.setOptions({ renderer })
// Fetch releases
letRELEASES=[]
asyncfunctiongetReleases(){
console.log('Fetching releases...')
letoptions={url: 'https://api.github.com/repos/nuxt/nuxt.js/releases'}
if(process.env.GITHUB_TOKEN){
options.headers={'Authorization': `token ${process.env.GITHUB_TOKEN}`}
}
try{
constres=awaitaxios(options)
RELEASES=res.data.filter((r)=>!r.draft).map((release)=>{
return{
name: release.name,
date: release.published_at,
body: marked(release.body)
}
})
}catch(e){
console.error('Could not fetch nuxt.js release notes.')
}
// Refresh every 15 minutes
setTimeout(getReleases,15*60*1000)
}
// Fetch doc and menu files
let_DOC_FILES_={}
asyncfunctiongetFiles(cwd){
console.log('Building files...')
cwd=cwd||process.cwd()
letdocPaths=awaitglob('*/**/*.md',{
cwd: cwd,
ignore: 'node_modules/**/*',
nodir: true
})
letpromises=[]
lettmpDocFiles={}
docPaths.forEach((path)=>{
letpromise=getDocFile(path,cwd)
promise.then((file)=>{
tmpDocFiles[path]=file
})
promises.push(promise)
})
awaitPromise.all(promises)
_DOC_FILES_=tmpDocFiles
// Construct the doc menu
awaitgetMenu(cwd)
// Construct the lang object
awaitgetLanguages(cwd)
}
// Get doc file and sent back it's attributes and html body
asyncfunctiongetDocFile(path,cwd){
cwd=cwd||process.cwd()
letfile=awaitreadFile(resolve(cwd,path),'utf-8')
// transform markdown to html
file=fm(file)
_DOC_FILES_[path]={
attrs: file.attributes,
body: marked(file.body)
}
return_DOC_FILES_[path]
}
// Get menu files and create the doc menu
let_MENU_={}
asyncfunctiongetMenu(cwd){
console.log('Building menu...')
cwd=cwd||process.cwd()
letmenuPaths=awaitglob('*/**/menu.json',{
cwd: cwd,
ignore: 'node_modules/**/*',
nodir: true
})
lettmpMenu={}
letpromises=[]
menuPaths.forEach((path)=>{
letmenu=tmpMenu
letkeys=path.split('/').slice(0,-1)
keys.forEach((key,i)=>{
if((i+1)===keys.length){
letpromise=readFile(resolve(cwd,path),'utf-8')
promise.then((fileContent)=>{
menu[key]=JSON.parse(fileContent)
})
promises.push(promise)
return
}
menu[key]=menu[key]||{}
menu=menu[key]
})
})
awaitPromise.all(promises)
_MENU_=tmpMenu
}
// Get lang files and create the lang object
let_LANG_={}
asyncfunctiongetLanguages(cwd){
console.log('Building languages...')
cwd=cwd||process.cwd()
letlangPaths=awaitglob('*/lang.json',{
cwd: cwd,
ignore: 'node_modules/**/*',
nodir: true
})
lettmpLang={}
letpromises=[]
langPaths.forEach((path)=>{
letlang=path.split('/')[0]
letpromise=readFile(resolve(cwd,path),'utf-8')
promise.then((fileContent)=>{
tmpLang[lang]=JSON.parse(fileContent)
})
promises.push(promise)
})
awaitPromise.all(promises)
_LANG_=tmpLang
}
// watch file changes
functionwatchFiles(){
console.log('Watch files changes...')
constoptions={
ignoreInitial: true,
ignored: 'node_modules/**/*'
}
constchokidar=require('chokidar')
// Doc Pages
chokidar.watch('*/**/*.md',options)
.on('add',(path)=>getDocFile(path))
.on('change',(path)=>getDocFile(path))
.on('unlink',(path)=>delete_DOC_FILES_[path])
// Menu
chokidar.watch('*/**/menu.json',options)
.on('add',()=>getMenu())
.on('change',()=>getMenu())
.on('unlink',()=>getMenu())
// Lang
chokidar.watch('*/lang.json',options)
.on('add',()=>getLanguages())
.on('change',()=>getLanguages())
.on('unlink',()=>getLanguages())
}
// Server handle request method
constserver=micro(asyncfunction(req,res){
// If github hook
if(req.method==='POST'&&req.url==='/hook'){
try{
returnawaitgithubHook({ req, res },getFiles)
}catch(e){
console.error('Error!')
console.error(e)
}
}
res.setHeader('Access-Control-Allow-Origin','*')
res.setHeader('Access-Control-Allow-Methods','GET,PUT,POST,DELETE')
res.setHeader('Access-Control-Allow-Headers','Content-Type')
// Releases
if(req.url==='/releases'){
returnsend(res,200,RELEASES)
}
// Menu
if(req.url.indexOf('/menu')===0){
letlang=req.url.split('/')[2]
letcategory=req.url.split('/')[3]
if(lang&&category&&_MENU_[lang]&&_MENU_[lang][category])returnsend(res,200,_MENU_[lang][category])
if(lang&&_MENU_[lang])returnsend(res,200,_MENU_[lang])
elseif(lang)returnsend(res,404,'Language not found')
returnsend(res,200,_MENU_)
}
// Lang
if(req.url.indexOf('/lang')===0){
letlang=req.url.split('/')[2]
if(lang&&_LANG_[lang])returnsend(res,200,_LANG_[lang])
elseif(lang)returnsend(res,404,'Language not found')
returnsend(res,200,_LANG_)
}
// remove first /
letpath=req.url.slice(1)+'.md'
// Check if path exists
if(!_DOC_FILES_[path]){
returnsend(res,404,'File not found')
}
// Send back doc content
send(res,200,_DOC_FILES_[path])
})
module.exports=getFiles()
.then(()=>getReleases())
.then(()=>{
if(process.env.NODE_ENV!=='production'){
watchFiles()
}
constport=process.env.PORT||4000
server.listen(port)
console.log(`Server listening on localhost:${port}`)
returnserver
})