-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.ts
155 lines (137 loc) Β· 4.37 KB
/
index.ts
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
import Fastify from 'fastify';
import fastifyMiddie from '@fastify/middie';
import fastifyStatic from '@fastify/static';
import fastifyCompress from '@fastify/compress';
import basicAuth from '@fastify/basic-auth';
import fs from 'node:fs';
import { execSync } from 'child_process';
import chalk from 'chalk';
import { createServer } from 'node:http';
import { Socket } from 'node:net';
import { server as wisp } from '@mercuryworkshop/wisp-js/server';
import path from 'node:path';
import { version } from './package.json';
import config from './config';
const port: number = config.port;
const host: string = '0.0.0.0';
function getCommitDate(): string {
try {
return execSync('git log -1 --format=%cd', { stdio: 'pipe' })
.toString()
.trim();
} catch {
return new Date().toISOString();
}
}
async function build() {
if (!fs.existsSync('dist')) {
console.log(chalk.yellow.bold('π Building Lunar...'));
try {
execSync('pnpm build', { stdio: 'inherit' });
console.log(chalk.green.bold('β
Build successful!'));
} catch (error) {
throw new Error(
`Build Error: ${error instanceof Error ? error.message : String(error)}`
);
}
} else {
console.log(chalk.blue.bold('π Lunar is already built. Skipping...'));
}
}
const app = Fastify({
logger: false,
serverFactory: (handler) =>
createServer(handler).on('upgrade', (req, socket: Socket, head) => {
wisp.routeRequest(req, socket, head);
}),
});
await app.register(fastifyCompress, { encodings: ['deflate', 'gzip', 'br'] });
if (config.auth.protect) {
console.log(chalk.magenta.bold('π Password Protection Enabled.'));
config.auth.users.forEach((user) => {
Object.entries(user).forEach(([username, password]) => {
console.log(chalk.yellow('π User Credentials:'));
console.log(
chalk.cyan(`β‘ Username: ${username}, Password: ${password}`)
);
});
});
await app.register(basicAuth, {
authenticate: true,
validate(username, password, _req, _reply, done) {
const user = config.auth.users.find((user) => user[username]);
if (user && user[username] === password) {
if (config.auth.log) {
console.log(chalk.green(`β
Authenticated: ${username}`));
}
return done();
}
return done(new Error('Invalid credentials'));
},
});
app.addHook('onRequest', app.basicAuth);
}
app.setErrorHandler((error, _request, reply) => {
if (error.statusCode === 401) {
reply.status(401).header('Content-Type', 'text/html').send(`
<!doctype html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html {
color-scheme: light dark;
}
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>
If you see this page, the nginx web server is successfully installed and
working. Further configuration is required. If you are expecting another
page, please check your network or
<a id="rcheck" onclick="location.reload();"><b>Refresh this page</b></a>
</p>
<p>
For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br />
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.
</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
`);
} else {
reply.send(error);
}
});
await build();
const commitDate = getCommitDate();
// @ts-ignore dir may not exist
const { handler } = await import('./dist/server/entry.mjs');
app.register(fastifyStatic, {
root: path.join(import.meta.dirname, 'dist', 'client'),
});
await app.register(fastifyMiddie);
app.use(handler);
app.listen({ host, port }, (err, address) => {
if (err) {
throw new Error(`β Failed to start Lunar V1: ${err.message}`);
}
console.log(chalk.green.bold(`\nπ Lunar V1`));
console.log(
chalk.whiteBright(
`π
Last Updated: ${chalk.cyanBright(new Date(commitDate).toLocaleString())}`
)
);
console.log(chalk.whiteBright(`π Version: ${chalk.cyanBright(version)}`));
console.log(chalk.green.bold(`\nπ Lunar is running at:`));
console.log(chalk.blueBright(` β‘ Local: ${chalk.underline(address)}`));
console.log(chalk.blueBright(` β‘ Network: http://127.0.0.1:${port}`));
});