-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
livereload-server.js
236 lines (198 loc) · 6.51 KB
/
livereload-server.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 SilentError = require('silent-error');
const walkSync = require('walk-sync');
const path = require('path');
const FSTree = require('fs-tree-diff');
const logger = require('heimdalljs-logger')('ember-cli:live-reload:');
const fs = require('fs');
const Promise = require('rsvp').Promise;
const cleanBaseUrl = require('clean-base-url');
function isNotRemoved(entryTuple) {
let operation = entryTuple[0];
return operation !== 'unlink' && operation !== 'rmdir';
}
function isNotDirectory(entryTuple) {
let entry = entryTuple[2];
return entry && !entry.isDirectory();
}
function relativePath(patch) {
return patch[1];
}
function isNotSourceMapFile(file) {
return !(/\.map$/.test(file));
}
function readSSLandCert(sslKey, sslCert) {
if (!fs.existsSync(sslKey)) {
throw new TypeError(`SSL key couldn't be found in "${sslKey}", ` +
`please provide a path to an existing ssl key file with --ssl-key`);
}
if (!fs.existsSync(sslCert)) {
throw new TypeError(`SSL certificate couldn't be found in "${sslCert}", ` +
`please provide a path to an existing ssl certificate file with --ssl-cert`);
}
let key = fs.readFileSync(sslKey);
let cert = fs.readFileSync(sslCert);
return { key, cert };
}
const DEFAULT_PREFIX = '/';
module.exports = class LiveReloadServer {
constructor({ app, watcher, ui, project, analytics, httpServer }) {
this.app = app;
this.watcher = watcher;
this.ui = ui;
this.project = project;
this.analytics = analytics;
this.httpServer = httpServer;
this.liveReloadPrefix = DEFAULT_PREFIX;
}
setupMiddleware(options) {
const tinylr = require('tiny-lr');
const Server = tinylr.Server;
if (options.liveReloadPrefix) {
this.liveReloadPrefix = cleanBaseUrl(options.liveReloadPrefix);
}
if (options.liveReload) {
if (options.liveReloadPort && options.port !== options.liveReloadPort) {
return this.createServerforCustomPort(options, Server)
.catch(error => {
if (error !== null && typeof error === 'object' && error.code === 'EADDRINUSE') {
let url = `http${options.ssl ? 's' : ''}://${this.displayHost(options.liveReloadHost)}:${options.liveReloadPort}`;
throw new SilentError(`${error.message}\nLivereload failed on '${url}', It may be in use.`);
} else {
throw error;
}
});
} else if (options.ssl) {
this.liveReloadServer = this.createHttpsServer(options, Server);
} else {
this.liveReloadServer = new Server({
app: this.app,
dashboard: 'false',
prefix: DEFAULT_PREFIX,
port: options.port,
});
}
this.start();
} else {
this.ui.writeWarnLine('Livereload server manually disabled.');
}
return Promise.resolve();
}
start() {
this.tree = new FSTree.fromEntries([]);
// Reload on file changes
this.watcher.on('change', function() {
try {
this.didChange.apply(this, arguments);
} catch (e) {
this.ui.writeError(e);
}
}.bind(this));
this.watcher.on('error', this.didChange.bind(this));
// Reload on express server restarts
this.app.on('restart', this.didRestart.bind(this));
this.httpServer.on('upgrade', this.liveReloadServer.websocketify.bind(this.liveReloadServer));
this.httpServer.on('error', this.liveReloadServer.error.bind(this.liveReloadServer));
this.httpServer.on('close', this.liveReloadServer.close.bind(this.liveReloadServer));
this.app.use(this.liveReloadPrefix, this.liveReloadServer.handler.bind(this.liveReloadServer));
}
createHttpsServer(options, Server) {
let { key, cert } = readSSLandCert(options.sslKey, options.sslCert);
return new Server({
app: this.app,
dashboard: 'false',
prefix: options.liveReloadPrefix,
port: options.liveReloadPort,
key,
cert,
});
}
createServerforCustomPort(options, Server) {
let instance;
Server.prototype.error = function() {
instance.error.apply(instance, arguments);
};
let serverOptions = {
dashboard: 'false',
prefix: options.liveReloadPrefix,
port: options.liveReloadPort,
host: options.liveReloadHost,
};
if (options.ssl) {
let { key, cert } = readSSLandCert(options.sslKey, options.sslCert);
serverOptions.key = key;
serverOptions.cert = cert;
}
instance = new Server(serverOptions);
this.liveReloadServer = instance;
this.start();
return new Promise((resolve, reject) => {
this.liveReloadServer.error = reject;
this.liveReloadServer.listen(options.liveReloadPort, options.liveReloadHost, resolve);
});
}
displayHost(specifiedHost) {
return specifiedHost || 'localhost';
}
writeSkipBanner(filePath) {
this.ui.writeLine(`Skipping livereload for: ${filePath}`);
}
getDirectoryEntries(directory) {
return walkSync.entries(directory);
}
shouldTriggerReload(options) {
let result = true;
if (this.project.liveReloadFilterPatterns.length > 0) {
let filePath = path.relative(this.project.root, options.filePath || '');
result = this.project.liveReloadFilterPatterns
.every(pattern => pattern.test(filePath) === false);
if (result === false) {
this.writeSkipBanner(filePath);
}
}
return result;
}
didChange(results) {
let previousTree = this.tree;
let files;
if (results.stack) {
this._hasCompileError = true;
files = ['LiveReload due to compile error'];
} else if (this._hasCompileError) {
this._hasCompileError = false;
files = ['LiveReload due to resolved compile error'];
} else if (results.directory) {
this.tree = new FSTree.fromEntries(this.getDirectoryEntries(results.directory), { sortAndExpand: true });
files = previousTree.calculatePatch(this.tree)
.filter(isNotRemoved)
.filter(isNotDirectory)
.map(relativePath)
.filter(isNotSourceMapFile);
} else {
files = ['LiveReload files'];
}
logger.info('files %a', files);
if (this.shouldTriggerReload(results)) {
this.liveReloadServer.changed({
body: {
files,
},
});
this.analytics.track({
name: 'broccoli watcher',
message: 'live-reload',
});
}
}
didRestart() {
this.liveReloadServer.changed({
body: {
files: ['LiveReload files'],
},
});
this.analytics.track({
name: 'express server',
message: 'live-reload',
});
}
};