-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
107 lines (81 loc) · 2.66 KB
/
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
'use strict';
var _ = require('highland');
var http = require('http');
var path = require('path');
var serveStatic = require('serve-static');
var finalhandler = require('finalhandler');
var debug = require('diagnostics')('bc:server');
var Primus = require('primus');
var PrimusResponder = require('primus-responder');
module.exports.start = function start(config, replStream, callback) {
var useCache = !!(config.client && config.client.useCache);
var indexFile = (useCache ? 'cache.html' : 'index.html');
debug('Using indexFile: %s', indexFile);
var staticRoot = path.join(__dirname, 'public');
var serve = serveStatic(staticRoot, { 'index': [ indexFile ] });
var server = http.createServer(function (req, res) {
serve(req, res, finalhandler(req, res));
});
var engine = (
config &&
config.websocket &&
typeof config.websocket.engine === 'string'
) ? config.websocket.engine : 'websockets';
var primus = new Primus(server, { transformer: engine });
primus.use('responder', PrimusResponder);
var dataStream = createDataStream(primus, replStream);
server.listen(config.port, function (err) {
callback(err, primus, dataStream);
});
};
function createDataStream(primus, replStream) {
return _(function (push) {
var connStream = _('connection', primus).take(1);
var isTerminated = false;
var terminate = function terminate(spark) {
if (!isTerminated) {
debug('primus-terminate');
isTerminated = true;
connStream.destroy();
if (spark.replStream) {
try {
spark.replStream.destroy();
} catch (e) {
// the REPL may have been destroyed already
}
}
spark.end();
primus.destroy();
push(null, _.nil);
}
};
primus.on('disconnection', terminate);
connStream.toArray(function (sparks) {
var spark = sparks.shift();
debug('spark-connected: %s', spark.id);
spark.replStream = replStream.fork()
.each(function (inp) {
spark.writeAndWait({ request: inp.data }, function (res) {
if (typeof res === 'object') {
if (res.error) {
// window.onerror
inp.print(res.error);
} else if (res.response) {
inp.print(res.response.error, res.response.result);
}
}
});
}).done(function () {
terminate(spark);
});
spark.on('data', function (data) {
debug('spark-data', data);
push(null, data);
});
spark.on('end', function (data) {
debug('spark-end');
terminate(spark);
});
});
});
}