documentation.
 */
const EventSourceActor = ActorClassWithSpec(eventSourceSpec, {
  initialize(conn, targetActor) {
    Actor.prototype.initialize.call(this, conn);

    this.targetActor = targetActor;
    this.innerWindowID = null;

    // Register for backend events.
    this.onWindowReady = this.onWindowReady.bind(this);
    this.targetActor.on("window-ready", this.onWindowReady);
  },

  onWindowReady({ isTopLevel }) {
    if (isTopLevel) {
      this.startListening();
    }
  },

  destroy: function() {
    this.targetActor.off("window-ready", this.onWindowReady);

    this.stopListening();
    Actor.prototype.destroy.call(this);
  },

  // Actor API.

  startListening: function() {
    this.stopListening();
    this.innerWindowID = this.targetActor.window.windowUtils.currentInnerWindowID;
    eventSourceEventService.addListener(this.innerWindowID, this);
  },

  stopListening() {
    if (!this.innerWindowID) {
      return;
    }
    if (eventSourceEventService.hasListenerFor(this.innerWindowID)) {
      eventSourceEventService.removeListener(this.innerWindowID, this);
    }

    this.innerWindowID = null;
  },

  // Implement functions of nsIEventSourceEventService.

  eventSourceConnectionOpened(httpChannelId) {
    this.emit("serverEventSourceConnectionOpened", httpChannelId);
  },

  eventSourceConnectionClosed(httpChannelId) {
    this.emit("serverEventSourceConnectionClosed", httpChannelId);
  },

  eventReceived(httpChannelId, eventName, lastEventId, data, retry, timeStamp) {
    let payload = new LongStringActor(this.conn, data);
    this.manage(payload);
    payload = payload.form();
    this.emit("serverEventReceived", httpChannelId, {
      payload,
      eventName,
      lastEventId,
      retry,
      timeStamp,
    });
  },
});

exports.EventSourceActor = EventSourceActor;
PK