debug-server.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. var http = require('http'),
  2. EventEmitter = require('events').EventEmitter,
  3. inherits = require('util').inherits,
  4. extend = require('util')._extend,
  5. path = require('path'),
  6. express = require('express'),
  7. WebSocketServer = require('ws').Server,
  8. Session = require('./session'),
  9. buildUrl = require('../index.js').buildInspectorUrl,
  10. WEBROOT = path.join(__dirname, '../front-end');
  11. function debugAction(req, res) {
  12. res.sendfile(path.join(WEBROOT, 'inspector.html'));
  13. }
  14. function overridesAction(req, res) {
  15. res.sendfile(path.join(__dirname, '../front-end-node/Overrides.js'));
  16. }
  17. function handleWebSocketConnection(socket) {
  18. var debugPort = this._getDebuggerPort(socket.upgradeReq.url);
  19. this._createSession(debugPort).join(socket);
  20. }
  21. function handleServerListening() {
  22. this.emit('listening');
  23. }
  24. function handleServerError(err) {
  25. if (err._handledByInspector) return;
  26. err._handledByInspector = true;
  27. this.emit('error', err);
  28. }
  29. function DebugServer() {}
  30. inherits(DebugServer, EventEmitter);
  31. DebugServer.prototype.start = function(options) {
  32. this._config = extend({}, options);
  33. var app = express();
  34. var httpServer = http.createServer(app);
  35. this._httpServer = httpServer;
  36. app.get('/debug', debugAction.bind(this));
  37. app.get('/node/Overrides.js', overridesAction);
  38. app.use(express.static(WEBROOT));
  39. this.wsServer = new WebSocketServer({
  40. server: httpServer
  41. });
  42. this.wsServer.on('connection', handleWebSocketConnection.bind(this));
  43. this.wsServer.on('error', handleServerError.bind(this));
  44. httpServer.on('listening', handleServerListening.bind(this));
  45. httpServer.on('error', handleServerError.bind(this));
  46. httpServer.listen(this._config.webPort, this._config.webHost);
  47. };
  48. DebugServer.prototype._getDebuggerPort = function(url) {
  49. return parseInt((/\?port=(\d+)/.exec(url) || [null, this._config.debugPort])[1], 10);
  50. };
  51. DebugServer.prototype._createSession = function(debugPort) {
  52. return Session.create(debugPort, this._config);
  53. };
  54. DebugServer.prototype.close = function() {
  55. if (this.wsServer) {
  56. this.wsServer.close();
  57. this.emit('close');
  58. }
  59. };
  60. DebugServer.prototype.address = function() {
  61. var address = this._httpServer.address();
  62. var config = this._config;
  63. address.url = buildUrl(config.webHost, address.port, config.debugPort);
  64. return address;
  65. };
  66. exports.DebugServer = DebugServer;