-
Notifications
You must be signed in to change notification settings - Fork 209
/
index.mjs
187 lines (172 loc) · 5.44 KB
/
index.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
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
import http from 'http';
import https from 'https';
import url from 'url';
import path from 'path';
import fs from 'fs';
import express from 'express';
import vite from 'vite';
import wsrtc from 'wsrtc/wsrtc-server.mjs';
const SERVER_ADDR = '0.0.0.0';
const SERVER_NAME = 'local.webaverse.com';
Error.stackTraceLimit = 300;
const cwd = process.cwd();
const isProduction = process.argv[2] === '-p';
const _isMediaType = p => /\.(?:png|jpe?g|gif|svg|glb|mp3|wav|webm|mp4|mov)$/.test(p);
const _tryReadFile = p => {
try {
return fs.readFileSync(p);
} catch(err) {
// console.warn(err);
return null;
}
};
const certs = {
key: _tryReadFile('./certs/privkey.pem') || _tryReadFile('./certs-local/privkey.pem'),
cert: _tryReadFile('./certs/fullchain.pem') || _tryReadFile('./certs-local/fullchain.pem'),
};
function makeId(length) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
/* const _proxyUrl = (req, res, u) => {
const proxyReq = /https/.test(u) ? https.request(u) : http.request(u);
proxyReq.on('response', proxyRes => {
for (const header in proxyRes.headers) {
res.setHeader(header, proxyRes.headers[header]);
}
res.statusCode = proxyRes.statusCode;
proxyRes.pipe(res);
});
proxyReq.on('error', err => {
console.error(err);
res.statusCode = 500;
res.end();
});
proxyReq.end();
}; */
(async () => {
const app = express();
app.use('*', async (req, res, next) => {
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp');
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
const o = url.parse(req.originalUrl, true);
if (/^\/(?:@proxy|public)\//.test(o.pathname) && o.query['import'] === undefined) {
const u = o.pathname
.replace(/^\/@proxy\//, '')
.replace(/^\/public/, '')
.replace(/^(https?:\/(?!\/))/, '$1/');
if (_isMediaType(o.pathname)) {
const proxyReq = /https/.test(u) ? https.request(u) : http.request(u);
proxyReq.on('response', proxyRes => {
for (const header in proxyRes.headers) {
res.setHeader(header, proxyRes.headers[header]);
}
res.statusCode = proxyRes.statusCode;
proxyRes.pipe(res);
});
proxyReq.on('error', err => {
console.error(err);
res.statusCode = 500;
res.end();
});
proxyReq.end();
} else {
req.originalUrl = u;
next();
}
} else if (o.query['noimport'] !== undefined) {
const p = path.join(cwd, path.resolve(o.pathname));
const rs = fs.createReadStream(p);
rs.on('error', err => {
if (err.code === 'ENOENT') {
res.statusCode = 404;
res.end('not found');
} else {
console.error(err);
res.statusCode = 500;
res.end(err.stack);
}
});
rs.pipe(res);
// _proxyUrl(req, res, req.originalUrl);
} else if (/^\/login/.test(o.pathname)) {
req.originalUrl = req.originalUrl.replace(/^\/(login)/,'/');
return res.redirect(req.originalUrl);
} else {
next();
}
});
const isHttps = !process.env.HTTP_ONLY && (!!certs.key && !!certs.cert);
const port = parseInt(process.env.PORT, 10) || (isProduction ? 443 : 3000);
const wsPort = port + 1;
const _makeHttpServer = () => isHttps ? https.createServer(certs, app) : http.createServer(app);
const httpServer = _makeHttpServer();
const viteServer = await vite.createServer({
server: {
middlewareMode: 'html',
force:true,
hmr: {
server: httpServer,
port,
overlay: false,
},
}
});
app.use(viteServer.middlewares);
await new Promise((accept, reject) => {
httpServer.listen(port, SERVER_ADDR, () => {
accept();
});
httpServer.on('error', reject);
});
console.log(` > Local: http${isHttps ? 's' : ''}://${SERVER_NAME}:${port}/`);
const wsServer = (() => {
if (isHttps) {
return https.createServer(certs);
} else {
return http.createServer();
}
})();
const initialRoomState = (() => {
const s = fs.readFileSync('./scenes/gunroom.scn', 'utf8');
const j = JSON.parse(s);
const {objects} = j;
const appsMapName = 'apps';
const result = {
[appsMapName]: [],
};
for (const object of objects) {
let {start_url, type, content, position = [0, 0, 0], quaternion = [0, 0, 0, 1], scale = [1, 1, 1]} = object;
const transform = Float32Array.from([...position, ...quaternion, ...scale]);
const instanceId = makeId(5);
if (!start_url && type && content) {
start_url = `data:${type},${encodeURI(JSON.stringify(content))}`;
}
const appObject = {
instanceId,
contentId: start_url,
transform,
components: JSON.stringify([]),
};
result[appsMapName].push(appObject);
}
return result;
})();
const initialRoomNames = [];
wsrtc.bindServer(wsServer, {
initialRoomState,
initialRoomNames,
});
await new Promise((accept, reject) => {
wsServer.listen(wsPort, SERVER_ADDR, () => {
accept();
});
wsServer.on('error', reject);
});
console.log(` > World: ws${isHttps ? 's' : ''}://${SERVER_NAME}:${wsPort}/`);
})();