-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatch.js
289 lines (257 loc) · 8.09 KB
/
watch.js
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
const express = require('express');
const historyApiFallback = require("connect-history-api-fallback");
const proxy = require('http-proxy-middleware');
const ws = require('ws');
const chokidar = require('chokidar');
const { execFile, spawn } = require('node:child_process');
const winston = require('winston');
(async () => {
const chalk = (await import('chalk')).default;
const labelColors = {
meta: chalk.hex('#FFA000'),
exec: chalk.hex('#00A0FF'),
net: chalk.hex('#D02000'),
info: chalk.bgHex('#102080').white,
error: chalk.bgRed.white
}
const defaultFormat = winston.format.combine(
winston.format.printf(({ level, label, message }) => {
label = labelColors[label](label.padStart(5, ' '))
level = labelColors[level](level.padStart(5, ' '))
let x = "";
let l = message.split("\n")
for (let i = 0; i < l.length; i++) {
if (i === l.length - 1) {
x += `${label}|${level}|${l[i]}`
} else {
x += `${label}|${level}|${l[i]}\n`
}
}
return x;
})
)
const defaultLoggerOptions = {
transports: [ new winston.transports.Console() ]
}
const logger_meta = winston.createLogger({
...defaultLoggerOptions,
format: winston.format.combine(
winston.format.label({label: ('meta')}),
defaultFormat
)
});
const logger_exec = winston.createLogger({
...defaultLoggerOptions,
format: winston.format.combine(
winston.format.label({label: ('exec')}),
defaultFormat
)
});
const logger_net = winston.createLogger({
...defaultLoggerOptions,
format: winston.format.combine(
winston.format.label({label: ('net')}),
defaultFormat
)
});
function getYaml () {
let yaml;
if ( process.env.SERVER_MODE === 'WARP' ) {
yaml = "./stack.linux.warp.yaml"
} else if ( process.env.SERVER_MODE === 'WEBKIT' ) {
yaml = "./stack.linux.webkit.yaml"
}
return yaml;
}
function makeExecError ({error, stderr}) {
return {type: "ExecError", error, stderr}
}
function doBuild () {
return new Promise((res, rej) => {
execFile("stack", ["build", "--stack-yaml=" + getYaml()], (error, stdout, stderr) => {
if (error === null) {
res(stdout)
} else {
rej(makeExecError({error, stderr}))
}
})
})
}
function doExec (path) {
let s = spawn(path, {
cwd: './frontend/assets',
env: {
JSADDLE_WARP_PORT: 11924
}
})
s.stdout.on('data', (data) => {
logger_exec.info(`${data}`);
});
s.stderr.on('data', (data) => {
logger_exec.error(`${data}`);
});
s.on('close', (code, signal) => {
logger_exec.info(`child process exited with code ${code} signal ${signal}`);
});
return s
}
function getExecutablePath () {
return new Promise((res, rej) => {
execFile("stack", ["exec", "--stack-yaml=" + getYaml(), "--", "which", "RDWP-exe"], (error, stdout, stderr) => {
if (error === null) {
res(stdout.replace("\n", ""))
} else {
rej(makeExecError({error, stderr}))
}
})
})
}
function getHostname () {
if ( process.env.SERVER_HOST === undefined ) {
return "localhost"
} else {
return process.env.SERVER_HOST
}
}
function appCommon () {
if ( process.env.SERVER_MODE === 'WARP' ) {
const app = express()
// existing static files
app.use(express.static('./frontend/assets'))
// requests that has no dots AND its contents type is html -> /index-warp.html
app.use(historyApiFallback({
index: '/index-warp.html'
}))
// /index-warp.html
app.use(express.static('./index-warp'))
// all other requests that is not /wsapi (eg. /jsaddle.js, websocket /, sync xhr requests) -> proxy
app.use(proxy.createProxyMiddleware({
target: 'http://localhost:11924/',
changeOrigin: true,
pathFilter: function (x) {
return !(x.match(/^\/wsapi$/))
},
ws: true
}))
const server = app.listen(11923, getHostname())
// /wsapi : custom websocket server
return app, server
} else if ( process.env.SERVER_MODE === 'WEBKIT' ) {
const app = express()
const server = app.listen(11923, getHostname())
return app, server
}
}
function wsCommon (server) {
const wsServer = new ws.Server({ noServer: true });
wsServer.on('connection', socket => {
socket.on('error', logger_net.error);
socket.on('message', logger_net.info);
});
server.on('upgrade', (request, socket, head) => {
if (request.url === '/wsapi') {
logger_net.info('client connected...')
wsServer.handleUpgrade(request, socket, head, socket => {
socket.send('CONNECT- HELLO')
wsServer.emit('connection', socket, request);
});
}
});
return wsServer
}
function broadcastReload (wsServer) {
wsServer.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
if ( process.env.SERVER_MODE === 'WARP' ) {
client.send("RELOAD-- NOW");
} else if ( process.env.SERVER_MODE === 'WEBKIT' ) {
client.send("SHUTDOWN NOW");
}
}
})
}
const chokidarState = {
__inner_main: false,
__inner_timeouts: new Set(),
lock: function () {
this.__inner_main = true
this.__inner_timeouts.forEach((x) => {
clearTimeout(x)
this.__inner_timeouts.delete(x)
})
},
unlock: function () {
let to = setTimeout(() => {
this.__inner_main = false
this.__inner_timeouts.delete(to)
}, 1000)
this.__inner_timeouts.add(to)
},
isLocked: function () {
return this.__inner_main === true
},
mainProcess: null
};
function killMainProcess () {
return new Promise((res, rej) => {
chokidarState.mainProcess.on('close', (code, signal) => {
res()
})
chokidarState.mainProcess.kill()
})
}
function sleep (time) {
return new Promise((res, rej) => {
setTimeout(res, time)
})
}
function chokidarCommon (wsServer) {
// TODO: implement for webkit
chokidar.watch('frontend').on('change', async () => {
if (chokidarState.isLocked()) { return; }
chokidarState.lock()
try {
logger_meta.info("Start Build...")
const stdout = await doBuild()
logger_exec.info(stdout)
logger_meta.info("Build Complete! Running Executable...")
const execpath = await getExecutablePath()
if (chokidarState.mainProcess !== null) {
logger_meta.info("Terminating Previous Process...")
// broadcast reload script (takes 3 seconds to invoke location.reload())
broadcastReload(wsServer)
// 3 second left
await sleep(1000) // send location.reload() here
// 2 second left
await killMainProcess()
}
logger_meta.info('Launching New Process...')
chokidarState.mainProcess = doExec(execpath)
// 0 second left
chokidarState.unlock()
} catch (e) {
if (e.type === "ExecError") {
logger_exec.error(e.error)
logger_exec.error(e.stderr)
} else {
logger_meta.error(e)
}
chokidarState.unlock()
}
})
}
if ( process.env.SERVER_MODE === 'GHCJS' ){
const browserSync = require("browser-sync").create();
browserSync.init({
port: 11923,
watch: true,
server: "./RDWP-exe.jsexe",
files: "./RDWP-exe.jsexe/all.js",
middleware: [historyApiFallback()]
});
} else if ( process.env.SERVER_MODE === 'WARP' || process.env.SERVER_MODE === 'WEBKIT' ) {
let app, server = appCommon()
const wsServer = wsCommon(server)
chokidarCommon(wsServer)
}
})();