forked from brunch/auto-reload-brunch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
236 lines (188 loc) · 6.94 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
'use strict';
const sysPath = require('path');
const fs = require('fs');
const https = require('https');
const WebSocketServer = require('ws').Server;
const isWorker = require('cluster').isWorker;
const anymatch = require('anymatch');
const startingPort = 9485;
const portTryPool = 10;
const fileName = 'auto-reload.js';
class AutoReloader {
constructor(config) {
if (config == null) config = {};
if (config.autoReload) {
throw new Error('Warning: config.autoReload is no longer supported, please move it to config.plugins.autoReload');
}
const cfg = this.config = config.plugins && config.plugins.autoReload || {};
if (cfg.port == null) {
this.ports = [];
for (var i = 0; i <= portTryPool; i++) this.ports.push(startingPort + i);
} else {
this.ports = Array.isArray(cfg.port) ? cfg.port.slice() : [cfg.port];
}
if (cfg.host != null) {
this.host = cfg.host;
}
if (config.persistent) {
this.enabled = cfg.enabled == null ? true : cfg.enabled;
}
this.hot = config.hot;
this.delay = cfg.delay;
this.cssMatch = cfg.match && cfg.match.stylesheets || /\.css$/;
this.jsMatch = cfg.match && cfg.match.javascripts || /\.js$/;
this.forcewss = !!config.plugins.autoReload.forcewss;
this.connections = [];
this.port = this.ports.shift();
if (cfg.keyPath && cfg.certPath) {
this.key = fs.readFileSync(cfg.keyPath);
this.cert = fs.readFileSync(cfg.certPath);
this.ssl = !!(this.key && this.cert);
}
if (this.enabled && !isWorker) this.startServer();
if (this.enabled && !isWorker) this.startApp(); // does this go here?
}
startServer() {
const conns = this.connections;
const cfg = this.config;
const host = cfg.host || '0.0.0.0';
const port = this.port;
if (this.ssl) {
this.httpsServer = https.createServer({key: this.key, cert: this.cert});
this.httpsServer.listen(port, host);
this.server = new WebSocketServer({server: this.httpsServer});
} else {
this.server = new WebSocketServer({host, port});
}
this.server.on('connection', conn => {
conns.push(conn);
conn.on('close', () => conns.splice(conns.indexOf(conn), 1));
});
this.server.on('error', error => {
if (error.toString().match(/EADDRINUSE/)) {
if (this.ports.length) {
this.port = this.ports.shift();
this.startServer();
} else {
error = `cannot start because port ${port} is in use`;
}
}
});
}
startApp() {
if ( !this.config.app ) return
// move these?
let http = require( 'http' )
let chokidar = require('chokidar')
let debug = require('debug')('auto-reload-brunch-express')
let appPath = sysPath.resolve(this.config.app.path)
// let app = require(appPath)
let app = require(appPath)
let port = this.config.app.port
const server = http.createServer()
let watch = this.config.app.watch
let ignore = this.config.app.ignore
let chokOptions = { ignored: ignore, ignoreInitial: true }
// NOTE: if reloadBrowser===true this fires a reload message for EACH file
// change detected, will that be a problem or will user only change one
// file at a time or will we get a stampede in some situations ( like a
// global find and replace )?
chokidar.watch( watch, chokOptions ).on( 'all', ( event, path ) => {
debug('chokidar detected', event, path)
debug('reloading', appPath)
server.removeListener( "request", app )
// nuke all the loaded modules. too lazy to target just the relevant
Object.keys( require.cache ).forEach( key => {
delete require.cache[ key ]
} )
try {
// nuking modules cache isnt' good enough, now we must re-require
app = require( appPath )
// this helpfully resinstalls app when its needed
server.on( "request", app )
} catch ( e ) {
console.error( e )
}
// tell all connected browsers to reload
if ( this.config.app.reloadBrowser ) {
const sendMessage = () => {
this.connections
.filter( conn => conn.readyState === 1 )
.forEach( conn => conn.send( 'page' ) )
}
sendMessage()
}
} )
debug('Starting', appPath, 'on', port, 'watching', watch, 'from', process.cwd())
server.on( "request", app )
server.listen( port )
this.appServer = server
}
onCompile(changedFiles) {
const enabled = this.enabled;
const conns = this.connections;
if (!enabled) return;
const didCompile = changedFiles.length > 0;
const isCss = file => anymatch(this.cssMatch, file.path);
const isJs = file => anymatch(this.jsMatch, file.path);
const isJsOrCss = file => isJs(file) || isCss(file);
const allCss = didCompile && changedFiles.every(isCss);
const allJs = this.hot && didCompile && changedFiles.every(isJs);
const allJsOrCss = this.hot && didCompile && changedFiles.every(isJsOrCss);
if (toString.call(enabled) === '[object Object]') {
if (!(didCompile || enabled.assets)) return;
if (allCss) {
if (!enabled.css) return;
} else if (didCompile) {
const changedExts = changedFiles.map(x => sysPath.extname(x.path).slice(1));
const wasChanged = !Object.keys(enabled).some(k => enabled[k] && changedExts.indexOf(k) !== -1);
if (wasChanged) return;
}
}
const messages = [];
if (allJs || allJsOrCss) messages.push('javascript');
if (allCss || allJsOrCss) messages.push('stylesheet');
if (messages.length === 0) messages.push('page');
const sendMessage = () => {
conns
.filter(connection => connection.readyState === 1)
.forEach(connection => messages.forEach(message => connection.send(message)));
};
if (this.delay) {
setTimeout(sendMessage, this.delay);
} else {
sendMessage();
}
}
get include() {
return this.enabled ?
[sysPath.join(__dirname, 'vendor', fileName)] : [];
}
teardown() {
if (this.server) this.server.close();
if (this.httpsServer) this.httpsServer.close();
if (this.appServer) this.appServer.close();
}
compile(file) {
let finalData = file.data;
if (this.enabled &&
this.port !== startingPort &&
sysPath.basename(file.path) === fileName) {
finalData = finalData.replace(startingPort, this.port);
}
if (this.enabled && (this.forcewss || this.ssl) &&
sysPath.basename(file.path) === fileName) {
finalData = finalData.replace('ws://', 'wss://');
}
if (this.enabled && this.host &&
sysPath.basename(file.path) === fileName) {
finalData = finalData.replace(/var host = .*/, `var host = "${this.host}"`);
}
return Promise.resolve(finalData);
}
}
AutoReloader.prototype.supportsHMR = true;
AutoReloader.prototype.brunchPlugin = true;
AutoReloader.prototype.type = 'javascript';
AutoReloader.prototype.extension = 'js';
module.exports = AutoReloader;