ner) {
    this.observers.add(listener);
  }

  removeParentListener(listener) {
    this.observers.delete(listener);
  }

  receiveMessage({ name, data }) {
    switch (name) {
      case "UpdateAdminState":
      case "ClearProviders": {
        this.observers.forEach(listener => {
          let result = Cu.cloneInto(
            {
              type: name,
              data,
            },
            this.contentWindow
          );
          listener(result);
        });
        break;
      }
    }
  }

  wrapPromise(promise) {
    return new this.contentWindow.Promise((resolve, reject) =>
      promise.then(resolve, reject)
    );
  }

  sendQuery(aName, aData = null) {
    return this.wrapPromise(
      new Promise(resolve => {
        super.sendQuery(aName, aData).then(result => {
          resolve(Cu.cloneInto(result, this.contentWindow));
        });
      })
    );
  }

  asRouterMessage({ type, data }) {
    // Some legacy privileged addons send this message, but it got removed from
    // VALID_TYPES in bug 1715158. Thankfully, these addons don't appear to
    // require any actions from this message - just a Promise that resolves.
    if (type === "NEWTAB_MESSAGE_REQUEST") {
      return this.wrapPromise(Promise.resolve());
    }

    if (VALID_TYPES.has(type)) {
      switch (type) {
        case msg.DISABLE_PROVIDER:
        case msg.ENABLE_PROVIDER:
        case msg.EXPIRE_QUERY_CACHE:
        case msg.FORCE_PRIVATE_BROWSING_WINDOW:
        case msg.IMPRESSION:
        case msg.RESET_PROVIDER_PREF:
        case msg.SET_PROVIDER_USER_PREF:
        case msg.USER_ACTION: {
          return this.sendAsyncMessage(type, data);
        }
        default: {
          // these messages need a response
          return this.sendQuery(type, data);
        }
      }
    }
    throw new Error(`Unexpected type "${type}"`);
  }
}
PK