Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
QuiteAFancyEmerald
GitHub Repository: QuiteAFancyEmerald/Holy-Unblocker
Path: blob/master/lib/rammerhead/src/util/addStaticDirToProxy.js
6530 views
1
const mime = require('mime');
2
const fs = require('fs');
3
const path = require('path');
4
5
// these routes are reserved by hammerhead and rammerhead
6
const forbiddenRoutes = [
7
'/rammerhead.js',
8
'/hammerhead.js',
9
'/task.js',
10
'/iframe-task.js',
11
'/messaging',
12
'/transport-worker.js',
13
'/worker-hammerhead.js'
14
];
15
16
const isDirectory = (dir) => fs.lstatSync(dir).isDirectory();
17
18
/**
19
*
20
* @param {import('testcafe-hammerhead').Proxy} proxy
21
* @param {string} staticDir - all of the files and folders in the specified directory will be served
22
* publicly. /index.html will automatically link to /
23
* @param {string} rootPath - all the files that will be served under rootPath
24
*/
25
function addStaticFilesToProxy(proxy, staticDir, rootPath = '/', shouldIgnoreFile = (_file, _dir) => false) {
26
if (!isDirectory(staticDir)) {
27
throw new TypeError('specified folder path is not a directory');
28
}
29
30
if (!rootPath.endsWith('/')) rootPath = rootPath + '/';
31
if (!rootPath.startsWith('/')) rootPath = '/' + rootPath;
32
33
const files = fs.readdirSync(staticDir);
34
35
files.map((file) => {
36
if (isDirectory(path.join(staticDir, file))) {
37
addStaticFilesToProxy(proxy, path.join(staticDir, file), rootPath + file + '/', shouldIgnoreFile);
38
return;
39
}
40
41
if (shouldIgnoreFile(file, staticDir)) {
42
return;
43
}
44
45
const pathToFile = path.join(staticDir, file);
46
const staticContent = {
47
content: fs.readFileSync(pathToFile),
48
contentType: mime.getType(file)
49
};
50
const route = rootPath + file;
51
52
if (forbiddenRoutes.includes(route)) {
53
throw new TypeError(
54
`route clashes with hammerhead. problematic route: ${route}. problematic static file: ${pathToFile}`
55
);
56
}
57
58
proxy.GET(rootPath + file, staticContent);
59
if (file === 'index.html') {
60
proxy.GET(rootPath, staticContent);
61
}
62
});
63
}
64
65
module.exports = addStaticFilesToProxy;
66
67