-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
108 lines (92 loc) · 2.48 KB
/
main.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
var WebSocketServer = require("ws").Server;
var http = require("http");
var liveReload = require("steal-tools/lib/stream/live");
var path = require("path");
var fs = require("fs");
var asap = require("pdenodeify");
var spawn = require("child_process").spawn;
var main, args;
var flag = process.argv[2];
if(flag === "--main") {
main = process.argv[3];
} else if(flag === "--cmd") {
args = process.argv.slice(3);
}
// An array of functions that when called will reset the state
var resets = {};
var messageTypes = {
put: function(msg, ws){
var address = path.join(process.cwd(), msg.address);
var oldContent = fs.readFileSync(address, "utf8");
asap(fs.writeFile)(address, msg.content, "utf8").then(function(){
ws.send(JSON.stringify({put:true}));
});
if(!resets[address]) {
resets[address] = function(){
return asap(fs.writeFile)(address, oldContent, "utf8");
};
}
},
command: function(msg){
},
reset: function(msg, ws){
var fns = Object.keys(resets).map(function(address){
return resets[address]();
});
resets = {};
Promise.all(fns).then(function(){
ws.send(JSON.stringify({reset: true}));
});
},
install: function(msg, ws){
var packageName = msg.package;
var flags = msg.flags || "";
var oldPackage = fs.readFileSync("package.json", "utf8");
var args = ["install", packageName];
if(flags) args.push(flags);
var child = spawn("npm", args);
child.on("exit", function(code){
ws.send(JSON.stringify({install: true, error: code}));
});
var key = packageName + args.join(" ");
if(!resets[key]) {
resets[key] = function(){
return asap(fs.writeFile)("package.json", oldPackage, "utf8");
};
}
}
};
function startServer(options, graphStream){
var port = options.liveReloadPort || 8015;
var server = http.createServer().listen(port);
var wss = new WebSocketServer({ server: server });
wss.on("connection", function(ws){
ws.on("message", function(data){
var msg = JSON.parse(data);
var handler = messageTypes[msg.type];
if(!handler) {
console.error("no handler for type:", msg.type);
process.exit(1);
}
handler(msg, ws);
});
});
return wss;
};
var system = {
config: process.cwd() + "/package.json!npm"
};
if(main) {
system.main = main;
}
var graphStream = liveReload(system, {});
graphStream.once("data", function(){
startServer({}, graphStream);
if(args) {
var cmd = args.shift();
var child = spawn(cmd, args, { stdio: "inherit" });
child.on("exit", function(code){
process.exit(code);
});
}
});