-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
199 lines (175 loc) · 5.79 KB
/
Copy pathserver.js
File metadata and controls
199 lines (175 loc) · 5.79 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
'use strict';
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const { WebSocketServer } = require('ws');
const PORT = 8000;
const STATIC_PATH = path.resolve(process.cwd(), 'static');
const MIME_TYPES = {
default: 'text/plain; charset=UTF-8',
html: 'text/html; charset=UTF-8',
js: 'application/javascript; charset=UTF-8',
json: 'application/json',
css: 'text/css; charset=UTF-8',
svg: 'image/svg+xml',
ico: 'image/x-icon',
};
const MESSAGES = {
403: 'Forbidden',
404: 'Not found',
};
const TEXT_EXTS = new Set(['html', 'js', 'json', 'css', 'svg']);
const toBool = [() => true, () => false];
const isSubpath = (root, filePath) => {
const rel = path.relative(root, filePath);
return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
};
const mimeType = (filePath) => {
const ext = path.extname(filePath).slice(1).toLowerCase();
return MIME_TYPES[ext] || MIME_TYPES.default;
};
const resolveStatic = (urlPath) => {
const decoded = decodeURIComponent(urlPath);
let rel = decoded.replace(/^\/+/, '');
if (rel === '' || rel.endsWith('/')) rel += 'index.html';
else if (!path.extname(rel)) rel += '/index.html';
const filePath = path.resolve(STATIC_PATH, rel);
if (!isSubpath(STATIC_PATH, filePath)) return null;
return filePath;
};
const toCanonical = (urlPath) => {
const filePath = resolveStatic(urlPath);
if (!filePath) return '';
const rel = path.relative(STATIC_PATH, filePath);
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return '';
return `/${rel.split(path.sep).join('/')}`;
};
const readStatic = async (urlPath) => {
const filePath = resolveStatic(urlPath);
if (!filePath || !isSubpath(STATIC_PATH, filePath)) return null;
const exists = await fs.promises.access(filePath).then(...toBool);
if (!exists) return null;
const mime = mimeType(filePath);
const ext = path.extname(filePath).slice(1).toLowerCase();
const raw = await fs.promises.readFile(filePath).catch((error) => {
console.error(error);
return null;
});
if (raw === null) return null;
const body = TEXT_EXTS.has(ext) ? raw.toString('utf8') : raw;
return { mime, body };
};
const subscribe = (socket, files, reset = false) => {
if (reset || !socket.subscribed) socket.subscribed = new Set();
for (const urlPath of files) {
const canonical = toCanonical(urlPath);
if (canonical) socket.subscribed.add(canonical);
}
if (reset) console.log(`WS subscribe ${socket.subscribed.size}`);
};
const parsePacket = (packet) => {
try {
return JSON.parse(packet.toString());
} catch {
return null;
}
};
const sendPacket = (socket, packet) => {
const data = JSON.stringify(packet);
socket.send(data);
};
const receivePacket = (socket) => async (data) => {
const packet = parsePacket(data);
if (!packet) return;
if (Array.isArray(packet.files)) {
return void subscribe(socket, packet.files, true);
}
const { id, path: urlPath = '/' } = packet;
subscribe(socket, [urlPath]);
const file = await readStatic(urlPath);
if (!file) {
console.log(`WS get ${urlPath} 404`);
return void sendPacket(socket, { id, status: 404 });
}
console.log(`WS get ${urlPath} 200`);
sendPacket(socket, { id, ...file });
};
const sendReply = (response, status, body = null, type) => {
const { method, url } = response.req;
console.log(`HTTP ${method} ${url} ${status}`);
const data = body ?? MESSAGES[status];
const headers = { 'Content-Type': type || MIME_TYPES.default };
response.writeHead(status, headers);
response.end(data);
};
const handleRequest = async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const { pathname } = url;
if (pathname === '/' || pathname === '/index.html') {
console.log(`HTTP ${req.method} ${pathname} 302`);
res.writeHead(302, { Location: '/platform/' });
res.end();
return;
}
const file = await readStatic(pathname);
if (file) return void sendReply(res, 200, file.body, file.mime);
const ext = path.extname(pathname);
if (ext === '' || ext === '.html') {
const fallback = await readStatic('/404.html');
if (fallback) return void sendReply(res, 404, fallback.body, fallback.mime);
}
return void sendReply(res, 404);
};
const server = http.createServer();
const ws = new WebSocketServer({ server });
ws.on('connection', (socket, req) => {
const ip = req.socket.remoteAddress;
socket.subscribed = new Set();
console.log(`WS connected ${ip}`);
socket.on('message', receivePacket(socket));
socket.on('close', () => {
socket.subscribed.clear();
console.log(`WS disconnected ${ip}`);
});
});
const pushChange = async (urlPath) => {
const sockets = [];
for (const socket of ws.clients) {
if (socket.subscribed.has(urlPath)) sockets.push(socket);
}
if (sockets.length === 0) return;
const file = await readStatic(urlPath);
if (!file) {
console.log(`WS push ${urlPath} 404`);
for (const socket of sockets) {
if (socket.readyState === socket.OPEN) {
sendPacket(socket, { path: urlPath, status: 404 });
}
}
return;
}
console.log(`WS push ${urlPath} 200`);
for (const socket of sockets) {
if (socket.readyState === socket.OPEN) {
sendPacket(socket, { path: urlPath, ...file });
}
}
};
const pending = new Map();
fs.watch(STATIC_PATH, { recursive: true }, (event, filename) => {
if (!filename) return;
const urlPath = toCanonical(`/${filename.split(path.sep).join('/')}`);
if (!urlPath) return;
const prev = pending.get(urlPath);
if (prev) clearTimeout(prev);
const timeout = () => {
pending.delete(urlPath);
pushChange(urlPath);
};
const timer = setTimeout(timeout, 100);
pending.set(urlPath, timer);
});
server.on('request', handleRequest);
server.listen(PORT, () => {
console.log(`Server running at http://127.0.0.1:${PORT}/`);
});