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
|
import { readFileSync } from 'fs';
import glob from 'glob';
import { logger } from './logger.js'
import { marked } from 'marked';
import matter from 'gray-matter';
import chokidar from 'chokidar';
export function buildPage(page: Page) {
try {
const result = matter(page.raw);
const metadata = result.data;
const html = marked.parse(result.content, { mangle: false, headerIds: false });
page.html = html;
page.metadata = metadata;
page.buildTime = Date.now();
} catch (e) {
logger.error(`Failed to build page ${page.path}: ${e.message}`);
}
}
function loadRaw(path: string): string {
return readFileSync(`${path}`, 'utf-8');
}
export class PageDirectory {
private pagesPath: string;
public pages: Record<string, Page> = {};
public lastFullBuild: number;
constructor(pagesPath: string) {
this.pagesPath = pagesPath;
}
public loadFromDisk = () => {
for (const page in this.pages) {
delete this.pages[page];
}
const localPages = glob.sync(`**/*.{md,html}`, { cwd: this.pagesPath })
localPages.forEach(this.loadPage);
this.lastFullBuild = Date.now();
const watcher = chokidar.watch('.', {
persistent: true,
cwd: this.pagesPath,
ignoreInitial: true,
});
const onPageChange = (page: string) => {
logger.info(`File ${page} has been modified`);
this.loadPage(page);
}
const onPageRemoval = (page: string) => {
logger.info(`File ${page} has been removed`);
this.removePage(page);
}
watcher.on('add', onPageChange);
watcher.on('change', onPageChange);
watcher.on('unlink', onPageRemoval);
}
public loadPage = (page: string): void => {
logger.info(`Building page ${page}`);
let route = page.replace(/\.[^.]*$/,'')
let name = /[^/]*$/.exec(route)[0];
let path = `${this.pagesPath}/${page}`
let raw: string;
try {
raw = loadRaw(path);
} catch (e) {
logger.error(`Failed to read page ${path}: ${e.message}`);
return;
}
this.pages[route] = {
route: route,
name: name,
path: path,
raw: raw,
buildTime: 0,
metadata: {
title: "A Page"
}
}
buildPage(this.pages[route]);
}
public removePage = (page: string): void => {
logger.info(`Unloading page ${page}`);
let route = page.replace(/\.[^.]*$/,'')
delete this.pages[route];
}
public get(name: string): Page {
const page = this.pages[name];
if (!page) {
return undefined;
}
return page;
}
}
export type Page = {
html?: string;
raw?: string;
route: string;
name: string;
path: string;
buildTime: number;
metadata: any;
};
|