forked from darkreader/darkreader
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
127 lines (110 loc) · 3.28 KB
/
Copy pathserver.js
File metadata and controls
127 lines (110 loc) · 3.28 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
// @ts-check
import http from 'node:http';
import path from 'node:path';
const mimeTypes = new Map(
Object.entries({
'.css': 'text/css',
'.html': 'text/html',
'.jpg': 'image/jpeg',
'.js': 'text/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.svg': 'image/svg+xml',
}),
);
/**
* We reuse a single listener for each of exit and SIGINT events to
* avoid warnings about possible event listener leaks.
* @type {Array<() => Promise<void>>}
*/
const terminationListeners = [];
const terminationListener = () => {
terminationListeners.forEach((listener) => listener());
};
export function generateRandomId() {
return Math.floor(Math.random() * 2 ** 55).toString();
}
/**
* @param {number} port
*/
export async function createTestServer(port) {
/** @type {import('http').Server} */
let server;
/** @type {{[path: string]: string | import('http').RequestListener}} */
const paths = {};
/** @type {Set<import('net').Socket>} */
const sockets = new Set();
/** @type {import('http').RequestListener} */
function handleRequest(req, res) {
const parsedURL = new URL(req.url, 'https://localhost');
const pathName = parsedURL.pathname;
if (!paths.hasOwnProperty(pathName)) {
res.statusCode = 404;
res.end('Not found');
return;
}
const contentOrListener = paths[pathName];
if (typeof contentOrListener === 'function') {
const listener = contentOrListener;
return listener(req, res);
}
const content = contentOrListener;
const ext = pathName === '/' ? '.html' : path.extname(pathName);
const contentType = mimeTypes.get(ext) || 'text/plain';
res.statusCode = 200;
res.setHeader('Content-Type', contentType);
res.setHeader('Cache-Control', 'no-cache');
res.end(content, 'utf8');
}
/**
* @returns {Promise<void>}
*/
function start() {
return new Promise((resolve) => {
server = http
.createServer(handleRequest)
.listen(port, () => resolve());
server.on('connection', (socket) => {
sockets.add(socket);
socket.on('close', () => sockets.delete(socket));
});
});
}
/**
* @param {{[path: string]: string | import('http').RequestListener}} newPaths
*/
function setPaths(newPaths) {
Object.assign(paths, newPaths);
}
/**
* @returns {Promise<void>}
*/
function close() {
if (!server) {
return;
}
return new Promise((resolve) => {
server.close((err) => {
if (err) {
console.error(err);
}
server = null;
resolve();
});
sockets.forEach((socket) => {
socket.destroy();
});
});
}
if (terminationListeners.length === 0) {
process.on('exit', terminationListener);
process.on('SIGINT', terminationListener);
}
terminationListeners.push(close);
await start();
return {
setPaths,
close,
url: `http://localhost:${port}`,
};
}