forked from lumeland/lume
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
308 lines (250 loc) Β· 6.64 KB
/
server.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
import { listenAndServe } from "./deps/server.js";
import { acceptWebSocket } from "./deps/ws.js";
import { dirname, extname, join, relative } from "./deps/path.js";
import { brightGreen, red } from "./deps/colors.js";
import { exists } from "./deps/fs.js";
import { mimes } from "./utils.js";
const script = `
let ws;
function socket() {
if (ws && ws.readyState !== 3) {
return;
}
ws = new WebSocket("ws://" + document.location.host);
ws.onopen = () => {
console.log("Socket connection open. Listening for events.");
const files = read("refresh");
if (files) {
refresh(files);
}
};
ws.onmessage = (e) => {
const files = JSON.parse(e.data);
console.log(files);
if (!Array.isArray(files)) {
console.log(e.data);
return;
}
refresh(files);
};
ws.onerror = (e) => {
console.error("WebSocket error observed:", event);
}
}
setInterval(socket, 1000);
function refresh(files) {
let path = document.location.pathname;
if (!path.endsWith(".html")) {
path += path.endsWith("/") ? "index.html" : "/index.html";
}
const index = files.indexOf(path);
if (index !== -1) {
files.splice(index, 1);
save("refresh", files);
location.reload();
return;
}
files.forEach((file) => {
const format = file.split(".").pop().toLowerCase();
switch (format) {
case "css":
document.querySelectorAll('link[rel="stylesheet"]').forEach((el) =>
cache(el, "href", file, true)
);
break;
case "jpeg":
case "jpg":
case "png":
case "svg":
case "gif":
document.querySelectorAll("img").forEach((el) =>
cache(el, "src", file)
);
break;
case "js":
document.querySelectorAll("script").forEach((el) =>
cache(el, "src", file)
);
break;
}
});
}
function cache(el, prop, file, clone = false) {
const value = el[prop];
if (!value) {
return;
}
const url = new URL(value);
if (url.pathname !== file) {
return;
}
url.searchParams.set("_cache", (new Date()).getTime());
if (clone) {
const newEl = el.cloneNode();
newEl[prop] = url.toString();
el.after(newEl);
setTimeout(() => el.remove(), 500);
return;
}
el[prop] = url.toString();
}
function save(key, data) {
localStorage.setItem(key, JSON.stringify(data));
}
function read(key) {
const data = localStorage.getItem(key);
localStorage.removeItem(key);
if (data) {
return JSON.parse(data);
}
}
`;
export async function server(site, options) {
const root = site.dest();
const port = parseInt(options.port) || site.options.server.port || 3000;
const page404 = site.options.server.page404 || "/404.html";
console.log("");
console.log(" Server started at:");
console.log(brightGreen(` http://localhost:${port}/`));
console.log("");
//Live reload server
const watcher = Deno.watchFs(root);
//Static files server
listenAndServe({ port }, async (req) => {
//Is websocket
if (req.headers.get("upgrade") === "websocket") {
handleSocket(req);
} else {
handleFile(req);
}
});
async function handleFile(req) {
let path = join(root, decodeURIComponent(req.url.split("?", 2).shift()));
try {
const info = await Deno.stat(path);
if (info.isDirectory) {
path = join(path, "index.html");
await Deno.stat(path);
}
const mimeType = mimes.get(extname(path).toLowerCase()) ||
"application/octet-stream";
try {
await req.respond({
status: 200,
headers: new Headers({
"content-type": mimeType,
"cache-control": "no-cache no-store must-revalidate",
}),
body: await (mimeType === "text/html; charset=utf-8"
? getHtmlBody(path)
: getBody(path)),
});
} catch (err) {
return;
}
console.log(`${brightGreen("200")} ${req.url}`);
} catch (err) {
console.log(`${red("404")} ${req.url}`);
await req.respond({
status: 404,
headers: new Headers({
"content-type": mimes.get(".html"),
}),
body: await getNotFoundBody(root, page404, path),
});
}
}
let timer = 0;
let socket;
const changes = new Set();
async function handleSocket(req) {
const { conn, r: bufReader, w: bufWriter, headers } = req;
socket = await acceptWebSocket({
conn,
bufReader,
bufWriter,
headers,
});
async function sendChanges() {
if (!changes.size) {
return;
}
const files = Array.from(changes).map((path) =>
join("/", relative(root, path))
);
changes.clear();
try {
await socket.send(JSON.stringify(files));
console.log("Changes sent to browser");
} catch (err) {
console.log(
`Changes couldn't be sent to browser due "${err.message.trim()}"`,
);
}
}
console.log("Connected to browser");
for await (const event of watcher) {
if (event.kind !== "modify") {
continue;
}
event.paths.forEach((path) => changes.add(path));
//Debounce
clearTimeout(timer);
timer = setTimeout(sendChanges, 100);
}
}
}
async function getHtmlBody(path) {
const content = await Deno.readTextFile(path);
return `${content}<script>${script}</script>`;
}
async function getNotFoundBody(root, page404, file) {
const filepath = join(root, page404);
if (await exists(filepath)) {
return getHtmlBody(filepath);
}
const content = await listDirectory(dirname(file));
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>404 - Not found</title>
<style> body { font-family: sans-serif; max-width: 40em; margin: auto; padding: 2em; line-height: 1.5; }</style>
</head>
<body>
<h1>404 - Not found</h1>
<p>The url <code>${relative(root, file)}</code> does not exist</p>
<ul>
${
content.map((item) =>
`<li>
<a href="${relative(root, item[1])}">
${item[0]}
</a>
</li>`
).join("\n")
}
</ul>
</body>
</html>`;
}
async function getBody(path) {
const file = await Deno.open(path);
const content = await Deno.readAll(file);
Deno.close(file.rid);
return content;
}
async function listDirectory(directory) {
const files = [];
if (!await exists(directory)) {
return files;
}
for await (const info of Deno.readDir(directory)) {
const name = info.name;
const href = join(directory, name);
files.push([name, href]);
}
return files;
}