/
WebServer.ts
157 lines (131 loc) · 3.96 KB
/
WebServer.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
156
157
import Koa from 'koa';
import Logger from 'koa-logger';
import CORS from '@koa/cors';
import Body from 'koa-body';
import Static from 'koa-static';
import { AddressInfo } from 'net';
import { v4, v6 } from 'internal-ip';
import open from 'open';
import { join } from 'path';
import { fork } from 'child_process';
import { patternOf, currentModulePath } from '@tech_query/node-toolkit';
import { ProxyAgent } from './ProxyAgent';
export * from './ProxyAgent';
interface WebServerMessage {
type: string;
data: Record<string, any>;
}
export class WebServer {
staticPath?: string;
netPort?: number;
XDomain?: boolean;
openPath?: boolean | string;
address?: AddressInfo;
private core: Koa;
private proxyMap: ReturnType<typeof patternOf>;
constructor({
proxyMap = {},
...rest
}: {
staticPath?: string;
netPort?: number;
XDomain?: boolean;
openPath?: boolean | string;
proxyMap?: Parameters<typeof patternOf>[0];
} = {}) {
Object.assign(this, rest);
this.address = null;
this.core = new Koa();
this.proxyMap = patternOf(proxyMap);
this.boot();
}
private boot() {
this.core.use(Logger());
if (this.proxyMap)
this.core
.use(Body({ multipart: true }))
.use(ProxyAgent(this.proxyMap));
if (this.XDomain) this.core.use(CORS());
this.core.use(Static(this.staticPath));
}
/**
* Origin URI
*/
get baseURL() {
const { address: { address, port } = {} } = this;
return address ? `http://${address}:${port}` : '';
}
/**
* URL to open in default browser
*/
get openURL() {
const { openPath, baseURL } = this;
return typeof openPath !== 'string'
? baseURL
: new URL(openPath, baseURL) + '';
}
static getIPA() {
const address = v4.sync() || v6.sync() || '127.0.0.1';
return {
family: address.includes(':') ? 'IPv6' : 'IPv4',
address
};
}
/**
* Create a server in the same Node.JS process
*/
localHost() {
const server = this;
return this.core
.listen(this.netPort, async function () {
server.address = {
...this.address(),
...WebServer.getIPA()
};
if (process.send instanceof Function)
return process.send({
type: 'ready',
data: server.address
});
console.info(`Web server runs at ${server.baseURL}`);
if (server.openPath) await open(server.openURL + '');
})
.on('error', error => {
if (process.send instanceof Function)
process.send({
type: 'error',
data: error
});
else console.error(error);
});
}
/**
* Boot a server in a forked Node.JS process
*/
workerHost() {
const child = fork(
join(currentModulePath(), '../../dist/'),
[
this.staticPath,
'-p',
this.netPort + '',
this.XDomain && '--CORS'
],
{ execArgv: [] }
);
return new Promise<AddressInfo>((resolve, reject) =>
child.on('message', ({ type, data }: WebServerMessage) => {
switch (type) {
case 'ready':
return resolve(data as AddressInfo);
case 'error': {
const { name, message, ...rest } = data as Error;
reject(
Object.assign(new globalThis[name](message), rest)
);
}
}
})
);
}
}