-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
335 lines (298 loc) · 9.01 KB
/
index.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/**
* light-server
*
* Serve, watch, exucute commands and live-reload, all in one.
*
* Copyright (c) 2018 by Tianxiang Chen
*/
'use strict'
const getCerts = require('./lib/getCerts')
const registerLocalIps = require('./lib/registerLocalIps')
const axios = require('axios');
var morgan = require('morgan')
var connect = require('connect')
var serveStatic = require('serve-static')
var serveIndex = require('serve-index')
var injector = require('connect-injector')
var Gaze = require('gaze').Gaze
var LR = require('./livereload')
var spawn = require('child_process').spawn
var os = require('os').type()
const WAIT_404_TIMEOUT = 30000
function LightServer (options) {
if (!(this instanceof LightServer)) return new LightServer(options)
this.options = options
this.id = Math.floor(Math.random() * 1e10)
if (os === 'Windows_NT') {
this.shell = 'cmd'
this.firstParam = '/c'
} else {
this.shell = 'bash'
this.firstParam = '-c'
}
}
LightServer.prototype.writeLog = function (logLine) {
!this.options.quiet && console.log(logLine)
}
LightServer.prototype.start = async function () {
var _this = this
if (!_this.options.serve && !_this.options.proxy) {
_this.watch()
return
}
var app = connect()
let urlMap = {}
app.use(function (req, res, next){
if (req._parsedUrl && req._parsedUrl.pathname){
if ( !(urlMap[req._parsedUrl.pathname] > 0)) {
urlMap[req._parsedUrl.pathname] = 0
}
urlMap[req._parsedUrl.pathname]++
}
next()
})
if (!this.options.quiet) {
app.use(function (req, res, next) {
if (req.url === '/favicon.ico') {
next()
} else if (req.url === '/badcertinfo.json') {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({id: _this.id}, null, 2));
} else {
morgan('dev')(req, res, next)
}
})
}
if (!_this.options.noReload) {
_this.lr = LR({
quiet: _this.options.quiet,
https: _this.options.https,
http2: _this.options.http2
})
app.use(_this.lr.middleFunc)
app.use(
injector(
function (req, res) {
return (
res.getHeader('content-type') &&
res.getHeader('content-type').indexOf('text/html') !== -1
)
},
function (data, req, res, callback) {
callback(
null,
data
.toString()
.replace(
'</body>',
'<script src="/__lightserver__/reload-client.js"></script></body>'
)
)
}
)
)
}
if (_this.options.serve) {
if (_this.options.proxy) {
var proxy = require('./proxy')
app.use(proxy(_this.options.proxy, _this.options.proxypaths).middleFunc)
}
if (_this.options.historyindex) {
var history = require('connect-history-api-fallback')
app.use(history({ index: _this.options.historyindex }))
}
const serveStaticMiddleware = serveStatic(_this.options.serve, {
extensions: ['html'],
redirect: _this.options.serveRedirect === true,
fallthrough: true })
app.use(_this.options.servePrefix || '', serveStaticMiddleware)
app.use(
_this.options.servePrefix || '',
serveIndex(_this.options.serve, { icons: true })
)
app.use(async function (req, res, next){
if (req._parsedUrl && req._parsedUrl.pathname){
if ( urlMap[req._parsedUrl.pathname] >= 2) {
const filePath = path.join(_this.options.serve, req._parsedUrl.pathname)
console.log(`Hold URL for ${WAIT_404_TIMEOUT}ms: [${req.url}][${req._parsedUrl.pathname}]`)
urlMap[req._parsedUrl.pathname] = 0
let start = Date.now()
let exists = false
for (let i = 0 ; i < 1000; i++){
await new Promise((res)=>{
setTimeout(res, 100)
})
const time = Date.now() - start
exists = fs.existsSync(filePath)
if (exists){
console.log(`File back online\t${time}ms\t[${req.url}][${req._parsedUrl.pathname}]`)
serveStaticMiddleware(req, res, next)
return
}
if (time > WAIT_404_TIMEOUT) {
break
}
}
console.log('pass', req._parsedUrl.pathname)
delete urlMap[req._parsedUrl.pathname]
} else {
delete urlMap[req._parsedUrl.pathname]
}
}
next()
})
}
var server
const config = await registerLocalIps(_this.options.ipv6);
if (_this.options.http2) {
var fs = require('fs')
var path = require('path')
server = require('spdy').createServer(
{
key: fs.readFileSync(config.keyPath),
cert: fs.readFileSync(config.certPath)
},
app
)
}else if (_this.options.https) {
var fs = require('fs')
var path = require('path')
server = require('https').createServer(
{
key: fs.readFileSync(config.keyPath),
cert: fs.readFileSync(config.certPath)
},
app
)
} else {
server = require('http').createServer(app)
}
server
.listen(_this.options.port, _this.options.bind, async () => {
console.log(`Listening on port ${_this.options.port}`);
let needOpen = _this.options.open;
setTimeout(()=>{
if (needOpen){
const url = `https://ip-127-0-0-1.wrtc.dev:${_this.options.port}`;
console.log(url);
var opener = require('opener')
opener(`${url}/${typeof _this.options.open === "string" ? _this.options.open : ""}`);
needOpen = false
}
}, 5000)
for (let ip in config.ipMap){
const url = `https://${config.ipMap[ip].domain}:${_this.options.port}`;
try{
const info = await axios.get(url + '/badcertinfo.json');
if (info.data.id === this.id){
console.log(`Available ${url}`);
if (needOpen) {
var opener = require('opener')
opener(`${url}/${typeof _this.options.open === "string" ? _this.options.open : ""}`);
needOpen = false
}
}else{
console.log(`wrong domain ${url} (ID ${info.data.id} should be ${instanceId})`)
}
}catch(e){
if (needOpen){
console.log(`Not available for now ${url}`)
}
}
}
if (_this.lr) {
_this.lr.startWS(server) // websocket shares same port with http
}
_this.watch()
})
.on('error', function (err) {
if (err.errno === 'EADDRINUSE') {
console.log(
'## ERROR: port ' + _this.options.port + ' is already in use'
)
process.exit(2)
} else {
console.log(err)
}
})
}
LightServer.prototype.watch = function () {
var _this = this
_this.options.watchexps.forEach(function (we) {
var tokens = we.trim().split(/\s*#\s*/)
var filesToWatch = tokens[0].trim().split(/\s*,\s*/)
var commandToRun = tokens[1]
var reloadOption = tokens[2]
if (reloadOption !== 'reloadcss' && reloadOption !== 'no-reload') {
reloadOption = 'reload' // default value
}
if (commandToRun || _this.lr) {
_this.processWatchExp(filesToWatch, commandToRun, reloadOption)
} else {
console.log(
'## WARNING: Ignoring watch expression "' +
we +
'", because ' +
'it doesn\'t specify a command and live-reloading is disabled.'
)
}
})
}
LightServer.prototype.processWatchExp = function (
filesToWatch,
commandToRun,
reloadOption
) {
var _this = this
var gaze = new Gaze(filesToWatch, { interval: _this.options.interval })
// A file has been added/changed/deleted has occurred
gaze.on('all', function (event, filepath) {
if (gaze.executing) {
return
}
gaze.executing = true
_this.writeLog('* file: ' + filepath + ' was ' + event)
if (!commandToRun) {
if (_this.lr) {
_this.lr.trigger(reloadOption, _this.options.delay)
}
gaze.executing = false
return
}
console.log('## executing command: ' + commandToRun)
var start = new Date().getTime()
var p = spawn(_this.shell, [_this.firstParam, commandToRun], {
stdio: 'inherit'
})
p.on('close', function (code) {
if (code !== 0) {
console.log(
'## ERROR: command ' + commandToRun + ' exited with code ' + code
)
} else {
_this.writeLog(
'## command succeeded in ' + (new Date().getTime() - start) + 'ms'
)
if (_this.lr) {
_this.lr.trigger(reloadOption, _this.options.delay)
}
}
gaze.executing = false
})
})
if (filesToWatch.length) {
_this.writeLog(
'light-server is watching these files: ' + filesToWatch.join(', ')
)
_this.writeLog(' when file changes,')
if (commandToRun) {
_this.writeLog(' this command will be executed: ' + commandToRun)
}
if (_this.lr) {
_this.writeLog(
' this event will be sent to browser: ' + reloadOption + '\n'
)
}
}
}
module.exports = LightServer