forked from sr258/mustache-preview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreview.js
More file actions
executable file
·216 lines (187 loc) · 5.55 KB
/
preview.js
File metadata and controls
executable file
·216 lines (187 loc) · 5.55 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
#!/usr/bin/env node
/**
* Automatic preview system for Mustache templates
*/
import express from "express";
import handlebars from "handlebars";
import { create } from "express-handlebars";
import { resolve } from "path";
import bodyParser from "body-parser";
import {
readdirSync,
readFileSync,
existsSync,
writeFileSync,
unlinkSync,
} from "fs";
import { program } from "commander";
import ExpressWs from "express-ws";
import chokidar from "chokidar";
import { dirname } from 'path';
import { fileURLToPath } from 'url';
// Convert import.meta.url to a file path
const __filename = fileURLToPath(import.meta.url);
// Get the directory name from the file path
const __dirname = dirname(__filename);
// Now you can use __dirname as expected
const filePath = `${__dirname}/preview-index.mustache`;
program.option("-c, --config <config>").option("-p, --port <port>");
program.parse();
const cliOptions = program.opts();
const config = (
await import(
cliOptions.config
? resolve(cliOptions.config)
: resolve("./preview.config.mjs")
)
).default;
if (!config) {
console.error("No configuration file at ./preview.config.js");
exit(1);
}
let app = express();
const expressWs = ExpressWs(app);
app.set("views", resolve(config.paths.views));
app.set("view engine", "mustache");
const hdlbrs = create({
extname: ".mustache",
partialsDir: config.paths.partials,
layoutsDir: config.paths.layouts ? resolve(config.paths.layouts) : undefined,
helpers: config.helpers,
});
app.engine("mustache", hdlbrs.engine);
app.use(bodyParser.urlencoded({ extended: true }));
// Serve static files
app.use("/", express.static(resolve(config.paths.public)));
app.use("/", (req, res, next) => {
if (!req.query.view || !req.query.testcase || !req.query.layout) {
return next();
}
const testCaseFilename = resolve(
`${config.paths["test-data"]}/${req.query.view}/${req.query.testcase}.json`
);
if (
!existsSync(resolve(`${config.paths.views}/${req.query.view}.mustache`))
) {
return res.status(404).send(`unknown view ${req.query.view}`);
}
if (!existsSync(testCaseFilename)) {
return res.status(404).send(`unknown test case ${req.query.testcase}`);
}
res.render(req.query.view, {
...JSON.parse(readFileSync(testCaseFilename)),
layout: config.paths.layouts ? req.query.layout : undefined,
});
});
app.use("/", async (req, res, next) => {
if (!req.query.partial || !req.query.testcase || !req.query.layout) {
return next();
}
const testCaseFilename = resolve(
`${config.paths["test-data"]}/${req.query.partial}/${req.query.testcase}.json`
);
if (!(await hdlbrs.getPartials())[req.query.partial]) {
return res.status(404).send(`unknown partial ${req.query.partial}`);
}
if (!existsSync(testCaseFilename)) {
return res.status(404).send(`unknown test case ${req.query.testcase}`);
}
writeFileSync(
resolve(`${config.paths.views}/tmp.mustache`),
`{{>${req.query.partial}}}`
);
res.render(
"tmp",
{
...JSON.parse(readFileSync(testCaseFilename)),
layout: config.paths.layouts ? req.query.layout : undefined,
},
(err, html) => {
unlinkSync(`${config.paths.views}/tmp.mustache`);
res.send(html);
}
);
});
app.get("/", async (_req, res) => {
const views = readdirSync(resolve(config.paths.views))
.filter((f) => f.endsWith(".mustache"))
.map((f) => f.substring(0, f.length - 9));
let layouts = ["preview"];
if (config.paths.layouts) {
layouts = readdirSync(resolve(config.paths.layouts))
.filter((f) => f.endsWith(".mustache"))
.map((f) => f.substring(0, f.length - 9));
}
const partialNames = Object.keys(await hdlbrs.getPartials());
const partials = partialNames
.map((p) => {
let testCases = [];
try {
testCases = readdirSync(resolve(`${config.paths["test-data"]}/${p}`))
.filter((f) => f.endsWith(".json"))
.map((f) => f.substring(0, f.length - 5));
} catch {
// maybe there are no test cases, so we silently ignore errors
}
return {
name: p,
testCases,
};
})
.filter((p) => p.testCases.length > 0);
res.status(200).send(
handlebars.compile(
readFileSync(
resolve(filePath)
).toString()
)({
layouts,
views: views.map((view) => {
let testCases = [];
try {
testCases = readdirSync(
resolve(`${config.paths["test-data"]}/${view}`)
)
.filter((f) => f.endsWith(".json"))
.map((f) => f.substring(0, f.length - 5));
} catch {
// maybe there are no test cases, so we silently ignore errors
}
return {
name: view,
testCases,
};
}),
partials,
})
);
});
const getWatchDirs = () => {
const dirs = [
resolve(config.paths.views),
resolve(config.paths.public),
resolve(config.paths["test-data"]),
...(typeof config.paths.partials === "string"
? [resolve(config.paths.partials)]
: config.paths.partials.map((p) => resolve(p.dir))),
];
if (config.paths.layouts) {
dirs.push(resolve(config.paths.layouts));
}
return dirs;
};
app.ws("/", (ws) => {
const watcher = chokidar.watch(getWatchDirs(), {
ignored: resolve(`${config.paths.views}/tmp.mustache`),
});
watcher.on("all", () => {
ws.send("refresh");
});
ws.on("close", () => {
watcher.close();
});
});
const port = cliOptions.port ? Number.parseInt(cliOptions.port) : 3000;
app.listen(port, function () {
console.log(`Preview server started at http://localhost:${port}`);
});