import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _asyncIterator(r) { var n, t, o, e = 2; for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) { if (t && null != (n = r[t])) return n.call(r); if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r)); t = "@@asyncIterator", o = "@@iterator"; } throw new TypeError("Object is not async iterable"); }
function AsyncFromSyncIterator(r) { function AsyncFromSyncIteratorContinuation(r) { if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); var n = r.done; return Promise.resolve(r.value).then(function (r) { return { value: r, done: n }; }); } return AsyncFromSyncIterator = function AsyncFromSyncIterator(r) { this.s = r, this.n = r.next; }, AsyncFromSyncIterator.prototype = { s: null, n: null, next: function next() { return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); }, return: function _return(r) { var n = this.s.return; return void 0 === n ? Promise.resolve({ value: r, done: !0 }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); }, throw: function _throw(r) { var n = this.s.return; return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); } }, new AsyncFromSyncIterator(r); }
/*
Copyright 2022 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { WidgetApiToWidgetAction, MatrixCapabilities } from "matrix-widget-api";
import { MatrixEvent, EventStatus } from "./models/event.js";
import { EventType } from "./@types/event.js";
import { logger } from "./logger.js";
import { MatrixClient, ClientEvent, UNSTABLE_MSC4140_DELAYED_EVENTS } from "./client.js";
import { SyncApi, SyncState } from "./sync.js";
import { SlidingSyncSdk } from "./sliding-sync-sdk.js";
import { User } from "./models/user.js";
import { MapWithDefault, recursiveMapToObject } from "./utils.js";
/**
 * A MatrixClient that routes its requests through the widget API instead of the
 * real CS API.
 * @experimental This class is considered unstable!
 */
export class RoomWidgetClient extends MatrixClient {
  /**
   *
   * @param widgetApi - The widget api to use for communication.
   * @param capabilities - The capabilities the widget client will request.
   * @param roomId - The room id the widget is associated with.
   * @param opts - The configuration options for this client.
   * @param sendContentLoaded - Whether to send a content loaded widget action immediately after initial setup.
   *   Set to `false` if the widget uses `waitForIFrameLoad=true` (in this case the client does not expect a content loaded action at all),
   *   or if the the widget wants to send the `ContentLoaded` action at a later point in time after the initial setup.
   */
  constructor(widgetApi, capabilities, roomId, opts, sendContentLoaded) {
    var _this, _capabilities$sendEve, _capabilities$receive, _capabilities$sendSta, _capabilities$receive2, _capabilities$sendEve2, _capabilities$receive3, _capabilities$sendSta2, _capabilities$receive4, _capabilities$sendToD, _capabilities$receive5, _capabilities$sendEve3, _capabilities$sendSta3;
    super(opts);
    _this = this;
    this.widgetApi = widgetApi;
    this.capabilities = capabilities;
    this.roomId = roomId;
    _defineProperty(this, "room", void 0);
    _defineProperty(this, "widgetApiReady", void 0);
    _defineProperty(this, "lifecycle", void 0);
    _defineProperty(this, "syncState", null);
    _defineProperty(this, "onEvent", /*#__PURE__*/function () {
      var _ref = _asyncToGenerator(function* (ev) {
        ev.preventDefault();

        // Verify the room ID matches, since it's possible for the client to
        // send us events from other rooms if this widget is always on screen
        if (ev.detail.data.room_id === _this.roomId) {
          var _event = new MatrixEvent(ev.detail.data);
          yield _this.syncApi.injectRoomEvents(_this.room, [], [_event]);
          _this.emit(ClientEvent.Event, _event);
          _this.setSyncState(SyncState.Syncing);
          logger.info("Received event ".concat(_event.getId(), " ").concat(_event.getType(), " ").concat(_event.getStateKey()));
        } else {
          var {
            event_id: eventId,
            room_id: _roomId
          } = ev.detail.data;
          logger.info("Received event ".concat(eventId, " for a different room ").concat(_roomId, "; discarding"));
        }
        yield _this.ack(ev);
      });
      return function (_x) {
        return _ref.apply(this, arguments);
      };
    }());
    _defineProperty(this, "onToDevice", /*#__PURE__*/function () {
      var _ref2 = _asyncToGenerator(function* (ev) {
        ev.preventDefault();
        var event = new MatrixEvent({
          type: ev.detail.data.type,
          sender: ev.detail.data.sender,
          content: ev.detail.data.content
        });
        // Mark the event as encrypted if it was, using fake contents and keys since those are unknown to us
        if (ev.detail.data.encrypted) event.makeEncrypted(EventType.RoomMessageEncrypted, {}, "", "");
        _this.emit(ClientEvent.ToDeviceEvent, event);
        _this.setSyncState(SyncState.Syncing);
        yield _this.ack(ev);
      });
      return function (_x2) {
        return _ref2.apply(this, arguments);
      };
    }());
    this.widgetApiReady = new Promise(resolve => this.widgetApi.once("ready", resolve));

    // Request capabilities for the functionality this client needs to support
    if ((_capabilities$sendEve = capabilities.sendEvent) !== null && _capabilities$sendEve !== void 0 && _capabilities$sendEve.length || (_capabilities$receive = capabilities.receiveEvent) !== null && _capabilities$receive !== void 0 && _capabilities$receive.length || capabilities.sendMessage === true || Array.isArray(capabilities.sendMessage) && capabilities.sendMessage.length || capabilities.receiveMessage === true || Array.isArray(capabilities.receiveMessage) && capabilities.receiveMessage.length || (_capabilities$sendSta = capabilities.sendState) !== null && _capabilities$sendSta !== void 0 && _capabilities$sendSta.length || (_capabilities$receive2 = capabilities.receiveState) !== null && _capabilities$receive2 !== void 0 && _capabilities$receive2.length) {
      widgetApi.requestCapabilityForRoomTimeline(roomId);
    }
    (_capabilities$sendEve2 = capabilities.sendEvent) === null || _capabilities$sendEve2 === void 0 || _capabilities$sendEve2.forEach(eventType => widgetApi.requestCapabilityToSendEvent(eventType));
    (_capabilities$receive3 = capabilities.receiveEvent) === null || _capabilities$receive3 === void 0 || _capabilities$receive3.forEach(eventType => widgetApi.requestCapabilityToReceiveEvent(eventType));
    if (capabilities.sendMessage === true) {
      widgetApi.requestCapabilityToSendMessage();
    } else if (Array.isArray(capabilities.sendMessage)) {
      capabilities.sendMessage.forEach(msgType => widgetApi.requestCapabilityToSendMessage(msgType));
    }
    if (capabilities.receiveMessage === true) {
      widgetApi.requestCapabilityToReceiveMessage();
    } else if (Array.isArray(capabilities.receiveMessage)) {
      capabilities.receiveMessage.forEach(msgType => widgetApi.requestCapabilityToReceiveMessage(msgType));
    }
    (_capabilities$sendSta2 = capabilities.sendState) === null || _capabilities$sendSta2 === void 0 || _capabilities$sendSta2.forEach(_ref3 => {
      var {
        eventType,
        stateKey
      } = _ref3;
      return widgetApi.requestCapabilityToSendState(eventType, stateKey);
    });
    (_capabilities$receive4 = capabilities.receiveState) === null || _capabilities$receive4 === void 0 || _capabilities$receive4.forEach(_ref4 => {
      var {
        eventType,
        stateKey
      } = _ref4;
      return widgetApi.requestCapabilityToReceiveState(eventType, stateKey);
    });
    (_capabilities$sendToD = capabilities.sendToDevice) === null || _capabilities$sendToD === void 0 || _capabilities$sendToD.forEach(eventType => widgetApi.requestCapabilityToSendToDevice(eventType));
    (_capabilities$receive5 = capabilities.receiveToDevice) === null || _capabilities$receive5 === void 0 || _capabilities$receive5.forEach(eventType => widgetApi.requestCapabilityToReceiveToDevice(eventType));
    if (capabilities.sendDelayedEvents && ((_capabilities$sendEve3 = capabilities.sendEvent) !== null && _capabilities$sendEve3 !== void 0 && _capabilities$sendEve3.length || capabilities.sendMessage === true || Array.isArray(capabilities.sendMessage) && capabilities.sendMessage.length || (_capabilities$sendSta3 = capabilities.sendState) !== null && _capabilities$sendSta3 !== void 0 && _capabilities$sendSta3.length)) {
      widgetApi.requestCapability(MatrixCapabilities.MSC4157SendDelayedEvent);
    }
    if (capabilities.updateDelayedEvents) {
      widgetApi.requestCapability(MatrixCapabilities.MSC4157UpdateDelayedEvent);
    }
    if (capabilities.turnServers) {
      widgetApi.requestCapability(MatrixCapabilities.MSC3846TurnServers);
    }
    widgetApi.on("action:".concat(WidgetApiToWidgetAction.SendEvent), this.onEvent);
    widgetApi.on("action:".concat(WidgetApiToWidgetAction.SendToDevice), this.onToDevice);

    // Open communication with the host
    widgetApi.start();
    // Send a content loaded event now we've started the widget API
    // Note that element-web currently does not use waitForIFrameLoad=false and so
    // does *not* (yes, that is the right way around) wait for this event. Let's
    // start sending this, then once this has rolled out, we can change element-web to
    // use waitForIFrameLoad=false and have a widget API that's less racy.
    if (sendContentLoaded) widgetApi.sendContentLoaded();
  }
  startClient() {
    var _arguments = arguments,
      _this2 = this;
    return _asyncToGenerator(function* () {
      var _this2$capabilities$r, _this2$capabilities$r2;
      var opts = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : {};
      _this2.lifecycle = new AbortController();

      // Create our own user object artificially (instead of waiting for sync)
      // so it's always available, even if the user is not in any rooms etc.
      var userId = _this2.getUserId();
      if (userId) {
        _this2.store.storeUser(new User(userId));
      }

      // Even though we have no access token and cannot sync, the sync class
      // still has some valuable helper methods that we make use of, so we
      // instantiate it anyways
      if (opts.slidingSync) {
        _this2.syncApi = new SlidingSyncSdk(opts.slidingSync, _this2, opts, _this2.buildSyncApiOptions());
      } else {
        _this2.syncApi = new SyncApi(_this2, opts, _this2.buildSyncApiOptions());
      }
      _this2.room = _this2.syncApi.createRoom(_this2.roomId);
      _this2.store.storeRoom(_this2.room);
      yield _this2.widgetApiReady;

      // Backfill the requested events
      // We only get the most recent event for every type + state key combo,
      // so it doesn't really matter what order we inject them in
      yield Promise.all((_this2$capabilities$r = (_this2$capabilities$r2 = _this2.capabilities.receiveState) === null || _this2$capabilities$r2 === void 0 ? void 0 : _this2$capabilities$r2.map(/*#__PURE__*/function () {
        var _ref6 = _asyncToGenerator(function* (_ref5) {
          var {
            eventType,
            stateKey
          } = _ref5;
          var rawEvents = yield _this2.widgetApi.readStateEvents(eventType, undefined, stateKey, [_this2.roomId]);
          var events = rawEvents.map(rawEvent => new MatrixEvent(rawEvent));
          yield _this2.syncApi.injectRoomEvents(_this2.room, [], events);
          events.forEach(event => {
            _this2.emit(ClientEvent.Event, event);
            logger.info("Backfilled event ".concat(event.getId(), " ").concat(event.getType(), " ").concat(event.getStateKey()));
          });
        });
        return function (_x3) {
          return _ref6.apply(this, arguments);
        };
      }())) !== null && _this2$capabilities$r !== void 0 ? _this2$capabilities$r : []);
      if (opts.clientWellKnownPollPeriod !== undefined) {
        _this2.clientWellKnownIntervalID = setInterval(() => {
          _this2.fetchClientWellKnown();
        }, 1000 * opts.clientWellKnownPollPeriod);
        _this2.fetchClientWellKnown();
      }
      _this2.setSyncState(SyncState.Syncing);
      logger.info("Finished backfilling events");
      _this2.matrixRTC.start();

      // Watch for TURN servers, if requested
      if (_this2.capabilities.turnServers) _this2.watchTurnServers();
    })();
  }
  stopClient() {
    this.widgetApi.off("action:".concat(WidgetApiToWidgetAction.SendEvent), this.onEvent);
    this.widgetApi.off("action:".concat(WidgetApiToWidgetAction.SendToDevice), this.onToDevice);
    super.stopClient();
    this.lifecycle.abort(); // Signal to other async tasks that the client has stopped
  }
  joinRoom(roomIdOrAlias) {
    var _this3 = this;
    return _asyncToGenerator(function* () {
      if (roomIdOrAlias === _this3.roomId) return _this3.room;
      throw new Error("Unknown room: ".concat(roomIdOrAlias));
    })();
  }
  encryptAndSendEvent(room, event, delayOpts) {
    var _this4 = this;
    return _asyncToGenerator(function* () {
      // We need to extend the content with the redacts parameter
      // The js sdk uses event.redacts but the widget api uses event.content.redacts
      // This will be converted back to event.redacts in the widget driver.
      var content = event.event.redacts ? _objectSpread(_objectSpread({}, event.getContent()), {}, {
        redacts: event.event.redacts
      }) : event.getContent();
      if (delayOpts) {
        // TODO: updatePendingEvent for delayed events?
        var _response = yield _this4.widgetApi.sendRoomEvent(event.getType(), content, room.roomId, "delay" in delayOpts ? delayOpts.delay : undefined, "parent_delay_id" in delayOpts ? delayOpts.parent_delay_id : undefined);
        return _this4.validateSendDelayedEventResponse(_response);
      }
      var response;
      try {
        response = yield _this4.widgetApi.sendRoomEvent(event.getType(), content, room.roomId);
      } catch (e) {
        _this4.updatePendingEventStatus(room, event, EventStatus.NOT_SENT);
        throw e;
      }

      // This also checks for an event id on the response
      room.updatePendingEvent(event, EventStatus.SENT, response.event_id);
      return {
        event_id: response.event_id
      };
    })();
  }
  sendStateEvent(roomId, eventType, content) {
    var _arguments2 = arguments,
      _this5 = this;
    return _asyncToGenerator(function* () {
      var stateKey = _arguments2.length > 3 && _arguments2[3] !== undefined ? _arguments2[3] : "";
      var response = yield _this5.widgetApi.sendStateEvent(eventType, stateKey, content, roomId);
      if (response.event_id === undefined) {
        throw new Error("'event_id' absent from response to an event request");
      }
      return {
        event_id: response.event_id
      };
    })();
  }

  /**
   * @experimental This currently relies on an unstable MSC (MSC4140).
   */
  // eslint-disable-next-line
  _unstable_sendDelayedStateEvent(roomId, delayOpts, eventType, content) {
    var _arguments3 = arguments,
      _this6 = this;
    return _asyncToGenerator(function* () {
      var stateKey = _arguments3.length > 4 && _arguments3[4] !== undefined ? _arguments3[4] : "";
      if (!(yield _this6.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {
        throw Error("Server does not support the delayed events API");
      }
      var response = yield _this6.widgetApi.sendStateEvent(eventType, stateKey, content, roomId, "delay" in delayOpts ? delayOpts.delay : undefined, "parent_delay_id" in delayOpts ? delayOpts.parent_delay_id : undefined);
      return _this6.validateSendDelayedEventResponse(response);
    })();
  }
  validateSendDelayedEventResponse(response) {
    if (response.delay_id === undefined) {
      throw new Error("'delay_id' absent from response to a delayed event request");
    }
    return {
      delay_id: response.delay_id
    };
  }

  /**
   * @experimental This currently relies on an unstable MSC (MSC4140).
   */
  // eslint-disable-next-line
  _unstable_updateDelayedEvent(delayId, action) {
    var _this7 = this;
    return _asyncToGenerator(function* () {
      if (!(yield _this7.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {
        throw Error("Server does not support the delayed events API");
      }
      return yield _this7.widgetApi.updateDelayedEvent(delayId, action);
    })();
  }
  sendToDevice(eventType, contentMap) {
    var _this8 = this;
    return _asyncToGenerator(function* () {
      yield _this8.widgetApi.sendToDevice(eventType, false, recursiveMapToObject(contentMap));
      return {};
    })();
  }
  getOpenIdToken() {
    var _this9 = this;
    return _asyncToGenerator(function* () {
      var token = yield _this9.widgetApi.requestOpenIDConnectToken();
      // the IOpenIDCredentials from the widget-api and IOpenIDToken form the matrix-js-sdk are compatible.
      // we still recreate the token to make this transparent and catch'able by the linter in case the types change in the future.
      return {
        access_token: token.access_token,
        expires_in: token.expires_in,
        matrix_server_name: token.matrix_server_name,
        token_type: token.token_type
      };
    })();
  }
  queueToDevice(_ref7) {
    var _this10 = this;
    return _asyncToGenerator(function* () {
      var {
        eventType,
        batch
      } = _ref7;
      // map: user Id → device Id → payload
      var contentMap = new MapWithDefault(() => new Map());
      for (var {
        userId,
        deviceId,
        payload
      } of batch) {
        contentMap.getOrCreate(userId).set(deviceId, payload);
      }
      yield _this10.widgetApi.sendToDevice(eventType, false, recursiveMapToObject(contentMap));
    })();
  }
  encryptAndSendToDevices(userDeviceInfoArr, payload) {
    var _this11 = this;
    return _asyncToGenerator(function* () {
      // map: user Id → device Id → payload
      var contentMap = new MapWithDefault(() => new Map());
      for (var {
        userId,
        deviceInfo: {
          deviceId
        }
      } of userDeviceInfoArr) {
        contentMap.getOrCreate(userId).set(deviceId, payload);
      }
      yield _this11.widgetApi.sendToDevice(payload.type, true, recursiveMapToObject(contentMap));
    })();
  }

  // Overridden since we get TURN servers automatically over the widget API,
  // and this method would otherwise complain about missing an access token
  checkTurnServers() {
    var _this12 = this;
    return _asyncToGenerator(function* () {
      return _this12.turnServers.length > 0;
    })();
  }

  // Overridden since we 'sync' manually without the sync API
  getSyncState() {
    return this.syncState;
  }
  setSyncState(state) {
    var oldState = this.syncState;
    this.syncState = state;
    this.emit(ClientEvent.Sync, state, oldState);
  }
  ack(ev) {
    var _this13 = this;
    return _asyncToGenerator(function* () {
      yield _this13.widgetApi.transport.reply(ev.detail, {});
    })();
  }
  watchTurnServers() {
    var _this14 = this;
    return _asyncToGenerator(function* () {
      var servers = _this14.widgetApi.getTurnServers();
      var onClientStopped = () => {
        servers.return(undefined);
      };
      _this14.lifecycle.signal.addEventListener("abort", onClientStopped);
      try {
        var _iteratorAbruptCompletion = false;
        var _didIteratorError = false;
        var _iteratorError;
        try {
          for (var _iterator = _asyncIterator(servers), _step; _iteratorAbruptCompletion = !(_step = yield _iterator.next()).done; _iteratorAbruptCompletion = false) {
            var server = _step.value;
            {
              _this14.turnServers = [{
                urls: server.uris,
                username: server.username,
                credential: server.password
              }];
              _this14.emit(ClientEvent.TurnServers, _this14.turnServers);
              logger.log("Received TURN server: ".concat(server.uris));
            }
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (_iteratorAbruptCompletion && _iterator.return != null) {
              yield _iterator.return();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }
      } catch (e) {
        logger.warn("Error watching TURN servers", e);
      } finally {
        _this14.lifecycle.signal.removeEventListener("abort", onClientStopped);
      }
    })();
  }
}
//# sourceMappingURL=embedded.js.map