-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.mjs
153 lines (122 loc) Β· 3.92 KB
/
server.mjs
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
import Koa from 'koa';
import {join, relative, resolve} from 'path';
import {execSync} from 'child_process';
import Router from 'koa-router';
import koaSend from 'koa-send';
import watch from 'node-watch';
import websockify from 'koa-websocket';
import chalk from 'chalk';
import {readFileSync} from 'fs';
import opn from 'opn';
const liveReloadOn = true;
const watchFilesOn = true;
const openPageOnStart = true;
// Test that the path of the changed file isn't in the build output path
// without this an infinite loop will occur when you change a source file
const watchIncludeTest = path => !path.includes('/wasm/');
const srcPath = resolve('src');
const staticPath = resolve('static');
const port = process.env.PORT || 8080;
const app = websockify(new Koa());
const router = new Router();
const getUniqueSocketId = createUniqueIdFactory('socket');
let currentWebsockets = [];
router.get('/(.*)', handleHttpRequest);
app
.use(router.routes())
.use(router.allowedMethods());
if (liveReloadOn) {
app.ws.use(handleNewWsConnection);
}
logInfo('Building app...');
buildAppSync();
if (watchFilesOn) {
logInfo('Setting up file watcher...');
watch(
// if live reload is not on
// then only watch source files as they still
// benefit from a watcher so you get
// recompilation on file save
liveReloadOn ? [srcPath, staticPath] : srcPath,
{
recursive: true,
filter: watchIncludeTest,
},
handleFileChange
);
}
if(openPageOnStart) opn(`http://localhost:${port}`);
app.listen(port);
logSuccess(`Serving ${staticPath} on *:${port}`);
function handleFileChange(_, filePath) {
const isSourceFileChange = filePath.includes(srcPath);
const infoMessage = `${filePath} changed. ${isSourceFileChange ? 'Recompiling' : 'Reloading'}...`;
logInfo(infoMessage);
for (const {socket} of currentWebsockets) {
socket.send(
JSON.stringify({action: 'log', data: infoMessage})
);
}
if(isSourceFileChange) buildAppSync();
for (const {socket} of currentWebsockets) {
socket.send(
JSON.stringify({action: 'doReload', data: null})
);
}
}
function handleNewWsConnection(ctx, next) {
logInfo('Client connected');
const socket = ctx.websocket;
const socketId = getUniqueSocketId();
currentWebsockets.push({id: socketId, socket});
socket.on('close', () => {
logInfo(`Closing socket ${socketId}`);
currentWebsockets = currentWebsockets.filter(({id}) => id !== socketId);
});
return next(ctx);
}
async function handleHttpRequest(ctx, next) {
const path = ctx.path;
const scriptDirectory = process.cwd();
if (path === '/') {
const indexPath = join(staticPath, 'index.html');
respondWithHtml(indexPath, liveReloadOn);
return next(ctx);
}
const requestingHtml = path.includes('.html');
const requestedFilePath = join(staticPath, path);
if (requestingHtml) {
respondWithHtml(requestedFilePath, liveReloadOn);
return next(ctx);
}
await koaSend(ctx, relative(scriptDirectory, requestedFilePath));
return next(ctx);
function respondWithHtml(filePath, insertLiveReloadScript) {
const html = readFileSync(filePath, 'utf-8');
const finalHtml = insertLiveReloadScript ? insertLiveReloadScriptIntoHtml(html) : html;
ctx.type = 'html';
ctx.body = finalHtml;
}
}
function insertLiveReloadScriptIntoHtml(html) {
return html.replace('</body>', `<script>
const webSocket = new WebSocket('ws://localhost:${port}');
webSocket.addEventListener('message', ({data}) => {
const {action, data: actionData} = JSON.parse(data);
if (action === 'doReload') location.reload();
if (action === 'log') console.log(actionData);
});</script></body>`);
}
function buildAppSync() {
execSync('yarn build', {stdio: 'inherit'});
}
function logSuccess(message) {
console.log(chalk.green(message));
}
function logInfo(message) {
console.info(chalk.blue(message));
}
function createUniqueIdFactory(prefix) {
let index = 0;
return () => `${prefix}-${index++}`;
}