sockets.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.init = exports.plugin = void 0;
  4. const socket_io_1 = require("socket.io");
  5. const utils = require("./server/utils");
  6. /**
  7. * Plugin interface
  8. * @returns {*|function(this:exports)}
  9. */
  10. function plugin(server, clientEvents, bs) {
  11. return exports.init(server, clientEvents, bs);
  12. }
  13. exports.plugin = plugin;
  14. /**
  15. * @param {http.Server} server
  16. * @param clientEvents
  17. * @param {BrowserSync} bs
  18. */
  19. function init(server, clientEvents, bs) {
  20. var emitter = bs.events;
  21. var socketConfig = bs.options.get("socket").toJS();
  22. if (bs.options.get("mode") === "proxy" &&
  23. bs.options.getIn(["proxy", "ws"])) {
  24. server = utils.getServer(null, bs.options).server;
  25. server.listen(bs.options.getIn(["socket", "port"]));
  26. bs.registerCleanupTask(function () {
  27. server.close();
  28. });
  29. }
  30. var socketIoConfig = socketConfig.socketIoOptions;
  31. socketIoConfig.path = socketConfig.path;
  32. const io = new socket_io_1.Server();
  33. io.attach(server, Object.assign(Object.assign({}, socketIoConfig), { pingTimeout: socketConfig.clients.heartbeatTimeout, cors: {
  34. credentials: true,
  35. "origin": (origin, cb) => {
  36. return cb(null, origin);
  37. },
  38. } }));
  39. io.of(socketConfig.namespace).on('connection', (socket) => {
  40. handleConnection(socket);
  41. });
  42. /**
  43. * Handle each new connection
  44. * @param {Object} client
  45. */
  46. function handleConnection(client) {
  47. // set ghostmode callbacks
  48. if (bs.options.get("ghostMode")) {
  49. addGhostMode(client);
  50. }
  51. client.emit("connection", bs.options.toJS()); //todo - trim the amount of options sent to clients
  52. emitter.emit("client:connected", {
  53. ua: client.handshake.headers["user-agent"]
  54. });
  55. }
  56. /**
  57. * @param client
  58. */
  59. function addGhostMode(client) {
  60. clientEvents.forEach(addEvent);
  61. function addEvent(event) {
  62. client.on(event, data => {
  63. client.broadcast.emit(event, data);
  64. });
  65. }
  66. }
  67. // @ts-ignore
  68. io.sockets = io.of(socketConfig.namespace);
  69. return io;
  70. }
  71. exports.init = init;
  72. //# sourceMappingURL=sockets.js.map