-
Notifications
You must be signed in to change notification settings - Fork 30
/
browser.js
373 lines (299 loc) · 9.46 KB
/
browser.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
var debug = require("local-debug")('browser');
var http = require("http");
var browserify = require("browserify");
var routeMap = require("route-map");
var fs = require("fs");
var path = require("path");
var resumer = require("resumer");
var format = require("stream-format");
var formatText = require("format-text");
var concat = require("concat-stream");
var glob = require("glob").sync;
var parseUserAgent = require("user-agent-parser");
var prettifyError = require("prettify-error");
var WebSocket = require("faye-websocket");
var mime = require("mime");
var request = require("request");
var setContentType = require("set-content-type");
var url = require("url");
var execFirst = require("./exec-first");
var nodeTemplate = require("./node-template");
var nodeReporter = require("./node-reporter");
var transforms = require('./browserify-transforms');
var passTemplate = nodeTemplate('browser-passed-result');
var failTemplate = nodeTemplate('browser-failed-result');
var browserTemplate = nodeTemplate('browser-error-browser');
var errorTemplate = nodeTemplate('browser-error');
var errorNoStackTemplate = nodeTemplate('browser-error-no-stack');
var consoleTemplate = nodeTemplate('browser-console');
var testTemplate = nodeTemplate('browser-test');
var instructionsTemplate = nodeTemplate('browser-instructions');
var onSourceCodeChange = require("pubsub")();
var customFrameURL, matchURL, read;
var routes = {
'/assets/app.js': app,
'/assets/run.js': run,
'/assets/:file': provaAsset,
'/run': frame,
'/': index
};
var templates = glob(provaPath('../../templates/*.html')).map(function (f) {
return { name: path.basename(f, '.html'), filename: f };
});
module.exports = beforeStart;
function beforeStart (files, command) {
if (!command.exec) return start(files, command);
execFirst(command.exec, function () {
start(files, command);
});
}
function start (files, command) {
var http = require('http');
var server = http.createServer(route).listen(command.port, command.host);
var restartNotification = JSON.stringify({ restart: true });
var sockets = [];
read = transforms(files, command);
read.on('update', onSourceCodeChange.publish);
var customFrameFilename;
var customFrameRoute;
if (command.frame) {
customFrameURL = path.join('/assets/in', command.frame);
customFrameFilename = url.parse(command.frame).pathname;
customFrameRoute = path.join('/assets/in', customFrameFilename);
routes[customFrameRoute] = customFrame(customFrameFilename);
}
routes['/assets/in/:filename([\\w\\.\\/-]+)'] = localAsset;
routes['/restart'] = restart;
if (command['http-proxy']) {
createProxy(routes, command['http-proxy']);
}
matchURL = routeMap(routes);
server.on('upgrade', function(request, socket, body) {
var ws;
var ind;
if (WebSocket.isWebSocket(request)) {
ws = new WebSocket(request, socket, body);
ind = sockets.push(ws) - 1;
onSourceCodeChange.subscribe(notify);
ws.send(JSON.stringify({ start: true, url: customFrameURL || '/run' }));
ws.on('message', onMessage);
ws.on('close', function(event) {
ws = null;
sockets[ind] = undefined;
onSourceCodeChange.unsubscribe(notify);
});
}
function notify () {
ws.send(restartNotification);
}
});
//var grep = command.grep ? '/#grep:' + command.grep : '';
//debug('Visit %s%s:%s%s with a browser to start running the tests.', 'http://', command.host, command.port, grep);
outputInstructions(command);
function onMessage (msg) {
msg = JSON.parse(msg.data);
var args = [];
var key;
if (msg.console && !command['no-console']) {
outputConsole(msg.method, msg.params);
}
if (msg.test && command['progress']) {
outputTest(msg.test, msg.userAgent);
}
if (msg.result) {
outputResult(msg);
if (command.quit) process.exit(msg.result.failed);
return;
}
if (msg.fail) return outputError(msg);
}
function restart (request, response) {
response.write('restartiiiinnnnggg....\n');
var i = 0;
sockets.forEach(function (ws) {
if (!ws) return;
ws.send(restartNotification);
i++;
response.write(i + '\n');
});
response.end('done\n');
}
}
function route (req, res) {
var match = matchURL(req.url);
if (!match) return notfound().pipe(res);
match.fn(req, res, match);
};
function provaFile (file) {
return fs.createReadStream(provaPath('../../app/' + file));
}
function provaAsset (req, res, match) {
setContentType(req, res);
provaFile(match.params.file).on('error', function (error) {
notfound().pipe(res);
}).pipe(res);
}
function localAsset (req, res, match) {
var filename = match.params.filename;
setContentType(req, res);
localFile(filename).on('error', function (error) {
notfound().pipe(res);
}).pipe(res);
}
function localFile (filename) {
return fs.createReadStream(filename);
}
function index (req, res) {
var waiting = format({
message: 'loading'
});
fs.createReadStream(provaPath('../../templates/waiting.html'))
.pipe(waiting);
var render = format({
layout: waiting
});
provaFile('index.html').pipe(render);
render.pipe(res);
}
function build (filename) {
var b = browserify({ debug: true });
b.add(filename);
return b;
}
function app (req, res) {
convertTemplates();
setContentType(req, res);
build(provaPath('../../app/index.js')).bundle().pipe(res);
}
function run (req, res) {
var sourcemaps;
var ind;
var write = concat(function (build) {
var str = build.toString();
ind = str.indexOf('//# sourceMappingURL');
str = str.slice(0, ind) + '\n\nwindow.__source_code = window.parent.__source_code = ' + JSON.stringify(str.slice(0, ind)) + ';\n\n' + str.slice(ind);
setContentType(req, res);
res.end(str);
});
read.bundle().on('error', function (error) {
debug('Failed to browserify the source code. We\'re probably missing a module required. The error was:');
process.stderr.write('\n ');
console.error(prettifyError(error, 0) || error);
}).pipe(write);
}
function notfound () {
return resumer().queue('Not Found').end();
}
function frame (req, res) {
provaFile('frame.html').pipe(res);
}
function convertTemplates () {
var content = templates.map(function (template) {
return {
name: template.name,
html: fs.readFileSync(template.filename).toString()
};
});
content = content.map(function (template) {
return 'exports["' + template.name + '"] = ' + JSON.stringify(template.html);
});
fs.writeFileSync(provaPath('../../app/templates.js'), content.join('\n'));
}
function provaPath (p) {
return path.join(__filename, p);
}
process.on('uncaughtException', function (error) {
console.error('\n', prettifyError(error) || error);
});
function outputConsole (method, params) {
console.log(formatText(consoleTemplate, {
'method': method,
'message': params.join(' ')
}).replace('\n', ''));
}
function outputError (msg) {
var fail = msg.fail;
var error = {
message: fail.name,
stack: fail.stack
};
console.log(formatText(error.stack ? errorTemplate : errorNoStackTemplate, {
browser: formatUserAgent(msg.userAgent),
title: fail.test,
diff: diff(fail),
error: nodeReporter.tab(prettifyError(error, undefined, fail.source) || '', ' ')
}));
}
function outputTest (name, userAgent) {
console.log(formatText(testTemplate, {
name: name,
userAgent: formatUserAgent(userAgent)
}).replace('\n', ''));
}
function outputResult (msg) {
var failed = msg.result.failed;
var template = failed ? failTemplate : passTemplate;
console.log(formatText(template, msg.result) + ' ' + formatUserAgent(msg.userAgent));
}
function outputInstructions (command) {
var params = '';
if (command.grep) {
params = '/#grep:' + command.grep;
}
console.log(formatText(instructionsTemplate, {
host: command.host,
port: command.port,
params: params
}));
}
function formatUserAgent (rawUserAgent) {
var userAgent = parseUserAgent(rawUserAgent);
return formatText(browserTemplate, {
browser: userAgent.browser.name || '?',
browserVersion: userAgent.browser.major || '?',
engine: userAgent.engine.name || '?',
engineVersion: userAgent.engine.version || '?',
os: userAgent.os.name || '?',
osVersion: userAgent.os.version || '?'
})
}
function diff (fail) {
return nodeReporter.diff(fail).slice(1).split('\n').map(function (line) {
return line.slice(4);
}).join('\n');
}
function customFrame (filename) {
return function (req, res) {
fs.readFile(filename, function (error, bf) {
if (error) {
debug('Error: Failed to read %s, specified as custom frame.', filename);
console.error(error);
return;
};
var html = bf.toString();
html += '<script type="text/javascript" src="/assets/run.js"></script>';
setContentType(req, res);
res.end(html);
});
};
}
function createProxy (routes, param) {
var options = param.split('=');
var pattern = options[0];
var target = options[1];
routes[pattern] = onProxyRequest
routes[pattern + '/'] = onProxyRequest
routes[pattern + '/:filename([\\w\\.\\/-]+)'] = onProxyRequest
function onProxyRequest (req, res, match) {
var url = req.url.replace(pattern, '');
var method = req.method.toLowerCase()
if (url[0] != '/') {
url = '/' + url;
}
var proxy = request[method](target + url)
req.pipe(proxy)
proxy.pipe(res).on('error', function (error) {
res.end(error.message);
});
};
}