-
Notifications
You must be signed in to change notification settings - Fork 28
/
hads.js
420 lines (375 loc) · 12.2 KB
/
hads.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
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
'use strict';
const fs = require('fs-extra');
const path = require('path');
const express = require('express');
const multer = require('multer');
const shortId = require('shortid');
const moment = require('moment');
const pkg = require('./package.json');
const pug = require('pug');
const globby = require('globby');
const Matcher = require('./lib/matcher.js');
const Renderer = require('./lib/renderer.js');
const Helpers = require('./lib/helpers.js');
const Indexer = require('./lib/indexer.js');
const yargs = require('yargs/yargs')(process.argv.slice(2))
.usage(`\n${pkg.name} ${pkg.version}\nUsage: $0 [root dir] [options]`)
.version(false)
.option('port', {
alias: 'p',
describe: 'Port number to listen on',
default: 4040
})
.option('host', {
alias: 'h',
describe: 'Host address to bind to',
default: 'localhost'
})
.option('images-dir', {
alias: 'i',
describe: 'Directory to store images',
default: 'images'
})
.option('open', {
alias: 'o',
describe: 'Open default browser on start'
})
.option('readonly', {
alias: 'r',
describe: 'Read-only mode (no add or edit feature)'
})
.option('export', {
alias: 'e',
describe: 'Export static html'
})
.help(false) // Needed to avoid extra [boolean] type
.option('help', {describe: 'Show this help'});
const args = yargs.argv;
if (args.help || args._.length > 1) {
yargs.showHelp(console.log);
process.exit();
}
const INDEXES = [
'index.md',
'README.md',
'readme.md'
];
const ICONS = {
alert: 'octicon-alert',
file: 'octicon-file',
search: 'octicon-search',
fileCode: 'octicon-file-code'
};
const STYLESHEET = 'custom.css';
const PATHS = {
documentation: args._[0] || './',
public: path.join(__dirname, 'public'),
views: path.join(__dirname, 'views'),
/* eslint-disable no-return-assign */
get code() {
delete this.code;
return this.code = path.join(this.root, '**', `*.{${Matcher.getCode().join(',')}}`);
},
get customStylesheet() {
delete this.customStylesheet;
return this.customStylesheet = path.join(this.root, STYLESHEET);
},
get export() {
delete this.export;
return this.export = path.join(process.cwd(), args.export === true ? 'public' : args.export);
},
get hads() {
delete this.hads;
return this.hads = path.join(this.export, '_hads');
},
get images() {
delete this.images;
return this.images = path.join(this.root, Helpers.sanitizePath(args.i));
},
get root() {
delete this.root;
return this.root = path.resolve(this.documentation);
}
/* eslint-enable no-return-assign */
};
const SCRIPTS = [
'/ace/ace.js',
'/mermaid/mermaid.min.js',
'/dropzone/dropzone.min.js',
'/js/client.js'
];
const STYLESHEETS = [
'/highlight/github.css',
'/octicons/octicons.css',
'/css/github.css',
'/css/style.css',
'/font-awesome/css/font-awesome.css'
].concat(fs.existsSync(PATHS.customStylesheet) ? [`/${STYLESHEET}`] : []);
const indexer = new Indexer(PATHS.root);
const renderer = new Renderer(indexer, {
isExport: args.export
});
if (args.export) {
args.export = args.export === true ? './public' : args.export;
(async () => {
await fs.emptyDir(PATHS.export);
globby(path.join(PATHS.root, '**', `*.{${Matcher.getImages().join(',')}}`))
.then(images => {
images.map(file => {
const dest = file.replace(PATHS.root, '');
return fs.copy(file, path.join(PATHS.export, dest));
});
});
const [documentation, code] = await Promise.all([
indexer.indexFiles().then(files => files.map(file => file.file)),
globby(PATHS.code).then(paths => paths.map(path => path.replace(PATHS.root, '')))
]);
documentation
.concat(code)
.forEach(async file => {
const dir = path.dirname(file);
const ext = path.extname(file);
const base = path.basename(file, ext);
const src = path.join(PATHS.documentation, file);
const content = Matcher.isMarkdown(file) ?
await renderer.renderFile(src) :
await renderer.renderCode(src);
const template = path.join(PATHS.views, 'file.pug');
const html = pug.renderFile(template, {
content,
pkg,
route: Helpers.extractRoute(file),
icon: ICONS.file,
readonly: true,
scripts: SCRIPTS,
static: true,
styles: STYLESHEETS,
title: path.basename(src)
});
const buffer = Buffer.from(html);
const array = new Uint8Array(buffer);
const dest = path.join(dir, `${base}.html`);
const isIndex = INDEXES.find(filename => filename.startsWith(base));
await fs.mkdirp(path.join(PATHS.export, dir));
fs.writeFile(path.join(PATHS.export, dest), array);
if (isIndex) {
const dest = path.join(dir, 'index.html');
fs.writeFile(path.join(PATHS.export, dest), array);
}
});
// We `await` because we'll get EEXIST if this and the copy to
// the same directory in Helpers.processPackages are unresolved.
await fs.copy(PATHS.public, PATHS.hads);
if (await fs.exists(PATHS.customStylesheet)) {
fs.copy(path.join(PATHS.root, STYLESHEET), path.join(PATHS.hads, STYLESHEET));
}
Helpers.processPackages((alias, path$) => {
const dest = path.join(PATHS.hads, alias);
fs.copy(path$, dest);
});
})();
return;
}
const app = express();
app.set('views', PATHS.views);
app.set('view engine', 'pug');
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
app.use('/_hads/', express.static(path.join(__dirname, '/public')));
Helpers.processPackages((alias, path$) => {
app.use('/_hads/' + alias + '/', express.static(path$));
});
if (fs.existsSync(PATHS.customStylesheet)) {
app.use(`/_hads/${STYLESHEET}`, express.static(PATHS.customStylesheet));
}
app.get('*', (req, res, next) => {
let route = Helpers.extractRoute(req.path);
const query = req.query || {};
let rootIndex = -1;
let mdIndex = -1;
const create = Helpers.hasQueryOption(query, 'create');
let edit = Helpers.hasQueryOption(query, 'edit') || create;
let statusCode = 200;
let lastModified = '';
let filePath, icon, search, error, title, contentPromise;
function renderPage() {
if (error) {
edit = false;
contentPromise = Promise.resolve(renderer.renderMarkdown(error));
icon = ICONS.alert;
} else if (search) {
contentPromise = renderer.renderSearch(query.search);
icon = ICONS.search;
} else if (Helpers.hasQueryOption(query, 'raw') || Matcher.isImage(filePath)) {
return res.sendFile(filePath);
} else if (Matcher.isMarkdown(filePath)) {
contentPromise = edit ? renderer.renderRaw(filePath) : renderer.renderFile(filePath);
icon = ICONS.file;
} else if (Matcher.isCode(filePath)) {
contentPromise = renderer.renderCode(filePath);
icon = ICONS.fileCode;
}
if (!title) {
title = search ? renderer.searchResults : path.basename(filePath);
}
if (contentPromise) {
return fs.stat(filePath)
.then(stat => {
if (stat.isFile()) {
lastModified = moment(stat.mtime).fromNow();
}
return contentPromise;
})
.then(content => {
res.status(statusCode);
res.render(edit ? 'edit' : 'file', {
title,
lastModified,
readonly: args.readonly,
route,
icon,
search,
content,
styles: STYLESHEETS,
scripts: SCRIPTS,
pkg
});
})
.catch(err => {
console.error(`Error while retrieving file stats: ${err.code}`);
next();
});
}
return next();
}
function tryProcessFile() {
contentPromise = null;
filePath = path.join(PATHS.root, route);
return fs.stat(filePath)
.then(stat => {
search = query.search && query.search.length > 0 ? query.search.trim() : null;
if (stat.isDirectory() && !search && !error) {
if (!create) {
// Try to find a root file
route = path.join(route, INDEXES[++rootIndex]);
return tryProcessFile();
}
route = '/';
title = 'Error';
error = `Cannot create file \`${filePath}\``;
statusCode = 400;
}
return renderPage();
})
.catch(() => {
if (create) {
const fixedRoute = Helpers.ensureMarkdownExtension(route);
if (fixedRoute !== route) {
return res.redirect(fixedRoute + '?create=1');
}
return fs.mkdirp(path.dirname(filePath))
.then(() => fs.writeFile(filePath, ''))
.then(() => indexer.updateIndexForFile(filePath))
.then(tryProcessFile)
.catch(e => {
console.error(e);
title = 'Error';
error = `Cannot create file \`${filePath}\``;
route = '/';
statusCode = 400;
return renderPage();
});
}
if (rootIndex !== -1 && rootIndex < INDEXES.length - 1) {
route = path.join(path.dirname(route), INDEXES[++rootIndex]);
return tryProcessFile();
}
if (rootIndex === -1 && path.basename(route) !== '' && (path.extname(route) === '' || mdIndex > -1) &&
mdIndex < Matcher.MARKDOWN_EXTENSIONS.length - 1) {
// Maybe it's a github-style link without extension, let's try adding one
const extension = Matcher.MARKDOWN_EXTENSIONS[++mdIndex];
route = path.join(path.dirname(route), `${path.basename(route, path.extname(route))}.${extension}`);
return tryProcessFile();
}
if (path.dirname(route) === path.sep && rootIndex === INDEXES.length - 1) {
error = '## No home page (╥﹏╥)\nDo you want to create an [index.md](/index.md?create=1) or ' +
'[readme.md](/readme.md?create=1) file perhaps?';
} else {
error = '## File not found ¯\\\\\\_(◕\\_\\_◕)_/¯\n> *There\'s a glitch in the matrix...*';
}
title = '404 Error';
route = '/';
statusCode = 404;
return renderPage();
});
}
tryProcessFile();
});
if (!args.readonly) {
app.post('*', (req, res, next) => {
const route = Helpers.extractRoute(req.path);
const filePath = path.join(PATHS.root, route);
let lastModified = '';
fs.stat(filePath)
.then(stat => {
let fileContent = req.body.content;
if (stat.isFile() && fileContent) {
lastModified = moment(stat.mtime).fromNow();
if (process.platform !== 'win32') {
// Www-form-urlencoded data always use CRLF line endings, so this is a quick fix
fileContent = fileContent.replace(/\r\n/g, '\n');
}
return fs.writeFile(filePath, fileContent);
}
return null;
})
.then(() => {
indexer.updateIndexForFile(filePath);
return renderer.renderFile(filePath);
})
.then(content => res.render('file', {
title: path.basename(filePath),
lastModified,
readonly: args.readonly,
route,
icon: 'octicon-file',
content,
styles: STYLESHEETS,
scripts: SCRIPTS,
pkg
}))
.catch(() => {
next();
});
});
app.post('/_hads/upload', [multer({
storage: multer.diskStorage({
destination: (req, file, cb) => {
cb(null, PATHS.images);
},
filename: (req, file, cb) => {
fs.mkdirp(PATHS.images).then(() => {
cb(null, shortId.generate() + path.extname(file.originalname));
});
}
}),
onFileUploadStart: file => !file.mimetype.match(/^image\//),
limits: {
fileSize: 1024 * 1024 * 10 // 10 MB
}
}).single('file'), (req, res) => {
res.json(path.sep + path.relative(PATHS.root, req.file.path));
}]);
}
indexer.indexFiles().then(() => {
app.listen(args.port, args.host, () => {
const serverUrl = `http://${args.host}:${args.port}`;
console.log(`${pkg.name} ${pkg.version} serving at ${serverUrl} (press CTRL+C to exit)`);
if (args.open) {
require('open')(serverUrl, {url: true});
}
});
});
module.exports = app;