{"version":3,"file":"IndexedDBWorker-Dgn5IQFp.js","sources":["../node_modules/@babel/runtime/helpers/esm/typeof.js","../node_modules/@babel/runtime/helpers/esm/toPrimitive.js","../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js","../node_modules/@babel/runtime/helpers/esm/defineProperty.js","../node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js","../node_modules/loglevel/lib/loglevel.js","../node_modules/matrix-js-sdk/lib/logger.js","../node_modules/unhomoglyph/index.js","../node_modules/is-network-error/index.js","../node_modules/p-retry/index.js","../node_modules/matrix-js-sdk/lib/NamespacedValue.js","../node_modules/matrix-js-sdk/lib/@types/location.js","../node_modules/matrix-js-sdk/lib/@types/read_receipts.js","../node_modules/matrix-js-sdk/lib/utils.js","../node_modules/matrix-events-sdk/lib/NamespacedMap.js","../node_modules/matrix-events-sdk/lib/InvalidEventError.js","../node_modules/matrix-events-sdk/lib/events/ExtensibleEvent.js","../node_modules/matrix-events-sdk/lib/types.js","../node_modules/matrix-events-sdk/lib/NamespacedValue.js","../node_modules/matrix-events-sdk/lib/events/message_types.js","../node_modules/matrix-events-sdk/lib/utility/events.js","../node_modules/matrix-events-sdk/lib/events/MessageEvent.js","../node_modules/matrix-events-sdk/lib/events/NoticeEvent.js","../node_modules/matrix-events-sdk/lib/events/EmoteEvent.js","../node_modules/matrix-events-sdk/lib/interpreters/legacy/MRoomMessage.js","../node_modules/matrix-events-sdk/lib/interpreters/modern/MMessage.js","../node_modules/matrix-events-sdk/lib/events/poll_types.js","../node_modules/matrix-events-sdk/lib/events/PollStartEvent.js","../node_modules/matrix-events-sdk/lib/events/relationship_types.js","../node_modules/matrix-events-sdk/lib/events/PollResponseEvent.js","../node_modules/matrix-events-sdk/lib/events/PollEndEvent.js","../node_modules/matrix-events-sdk/lib/interpreters/modern/MPoll.js","../node_modules/matrix-events-sdk/lib/ExtensibleEvents.js","../node_modules/matrix-events-sdk/lib/IPartialEvent.js","../node_modules/matrix-events-sdk/lib/utility/MessageMatchers.js","../node_modules/matrix-events-sdk/lib/index.js","../node_modules/matrix-js-sdk/lib/@types/event.js","../node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js","../node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js","../node_modules/events/events.js","../node_modules/matrix-js-sdk/lib/models/typed-event-emitter.js","../node_modules/matrix-js-sdk/lib/models/user.js","../node_modules/matrix-js-sdk/lib/content-repo.js","../node_modules/matrix-js-sdk/lib/@types/membership.js","../node_modules/matrix-js-sdk/lib/models/room-member.js","../node_modules/matrix-js-sdk/lib/@types/partials.js","../node_modules/matrix-js-sdk/lib/extensible_events_v1/utilities.js","../node_modules/matrix-js-sdk/lib/@types/extensible_events.js","../node_modules/matrix-js-sdk/lib/@types/topic.js","../node_modules/matrix-js-sdk/lib/content-helpers.js","../node_modules/matrix-js-sdk/lib/models/beacon.js","../node_modules/matrix-js-sdk/lib/ReEmitter.js","../node_modules/matrix-js-sdk/lib/@types/beacon.js","../node_modules/matrix-js-sdk/lib/utils/roomVersion.js","../node_modules/matrix-js-sdk/lib/models/room-state.js","../node_modules/matrix-js-sdk/lib/models/event-timeline.js","../node_modules/matrix-js-sdk/lib/models/relations.js","../node_modules/matrix-js-sdk/lib/models/relations-container.js","../node_modules/matrix-js-sdk/lib/models/event-timeline-set.js","../node_modules/matrix-js-sdk/lib/models/event-status.js","../node_modules/matrix-js-sdk/lib/models/room-summary.js","../node_modules/matrix-js-sdk/lib/@types/sync.js","../node_modules/matrix-js-sdk/lib/filter-component.js","../node_modules/matrix-js-sdk/lib/filter.js","../node_modules/matrix-js-sdk/lib/models/read-receipt.js","../node_modules/matrix-js-sdk/lib/@types/polls.js","../node_modules/matrix-js-sdk/lib/models/poll.js","../node_modules/matrix-js-sdk/lib/models/room-receipts.js","../node_modules/matrix-js-sdk/lib/models/compare-event-ordering.js","../node_modules/matrix-js-sdk/lib/http-api/method.js","../node_modules/matrix-js-sdk/lib/http-api/errors.js","../node_modules/matrix-js-sdk/lib/http-api/interface.js","../node_modules/content-type/index.js","../node_modules/matrix-js-sdk/lib/http-api/utils.js","../node_modules/matrix-js-sdk/lib/http-api/refresh.js","../node_modules/matrix-js-sdk/lib/http-api/fetch.js","../node_modules/matrix-js-sdk/lib/http-api/prefix.js","../node_modules/matrix-js-sdk/lib/realtime-callbacks.js","../node_modules/matrix-js-sdk/lib/http-api/index.js","../node_modules/matrix-js-sdk/lib/serverCapabilities.js","../node_modules/matrix-js-sdk/lib/models/room-sticky-events.js","../node_modules/matrix-js-sdk/lib/models/room.js","../node_modules/matrix-js-sdk/lib/feature.js","../node_modules/matrix-js-sdk/lib/sync.js","../node_modules/matrix-js-sdk/lib/store/stub.js","../node_modules/uuid/dist/stringify.js","../node_modules/uuid/dist/rng.js","../node_modules/uuid/dist/native.js","../node_modules/uuid/dist/v4.js","../node_modules/sdp-transform/lib/grammar.js","../node_modules/sdp-transform/lib/parser.js","../node_modules/sdp-transform/lib/writer.js","../node_modules/sdp-transform/lib/index.js","../node_modules/matrix-js-sdk/lib/base64.js","../node_modules/matrix-js-sdk/lib/randomstring.js","../node_modules/matrix-js-sdk/lib/webrtc/callEventTypes.js","../node_modules/matrix-js-sdk/lib/webrtc/audioContext.js","../node_modules/matrix-js-sdk/lib/webrtc/callFeed.js","../node_modules/matrix-js-sdk/lib/webrtc/callEventHandler.js","../node_modules/matrix-js-sdk/lib/webrtc/groupCallEventHandler.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/connectionStats.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/connectionStatsBuilder.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/transportStatsBuilder.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/media/mediaSsrcHandler.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/media/mediaTrackHandler.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/media/mediaTrackStats.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/media/mediaTrackStatsHandler.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/valueFormatter.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/trackStatsBuilder.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/connectionStatsReportBuilder.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/callFeedStatsReporter.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/callStatsReportGatherer.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/statsReport.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/statsReportEmitter.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/summaryStatsReportGatherer.js","../node_modules/matrix-js-sdk/lib/webrtc/stats/groupCallStats.js","../node_modules/matrix-js-sdk/lib/webrtc/groupCall.js","../node_modules/matrix-js-sdk/lib/webrtc/call.js","../node_modules/matrix-js-sdk/lib/@types/PushRules.js","../node_modules/matrix-js-sdk/lib/pushprocessor.js","../node_modules/matrix-js-sdk/lib/version-support.js","../node_modules/matrix-js-sdk/lib/autodiscovery.js","../node_modules/matrix-js-sdk/lib/service-types.js","../node_modules/matrix-js-sdk/lib/models/event-context.js","../node_modules/matrix-js-sdk/lib/models/search-result.js","../node_modules/matrix-js-sdk/lib/@types/requests.js","../node_modules/matrix-js-sdk/lib/event-mapper.js","../node_modules/matrix-js-sdk/lib/models/MSC3089Branch.js","../node_modules/matrix-js-sdk/lib/models/MSC3089TreeSpace.js","../node_modules/matrix-js-sdk/lib/@types/search.js","../node_modules/matrix-js-sdk/lib/webrtc/mediaHandler.js","../node_modules/matrix-js-sdk/lib/sliding-sync.js","../node_modules/matrix-js-sdk/lib/sliding-sync-sdk.js","../node_modules/matrix-js-sdk/lib/scheduler.js","../node_modules/matrix-js-sdk/lib/ToDeviceMessageQueue.js","../node_modules/matrix-js-sdk/lib/models/invites-ignorer-types.js","../node_modules/matrix-js-sdk/lib/models/invites-ignorer.js","../node_modules/matrix-js-sdk/lib/rust-crypto/constants.js","../node_modules/base-x/src/esm/index.js","../node_modules/bs58/src/esm/index.js","../node_modules/matrix-js-sdk/lib/crypto-api/CryptoEvent.js","../node_modules/matrix-js-sdk/lib/crypto-api/index.js","../node_modules/matrix-js-sdk/lib/utils/internal/deriveKeys.js","../node_modules/matrix-js-sdk/lib/utils/encryptAESSecretStorageItem.js","../node_modules/matrix-js-sdk/lib/utils/decryptAESSecretStorageItem.js","../node_modules/matrix-js-sdk/lib/secret-storage.js","../node_modules/matrix-js-sdk/lib/digest.js","../node_modules/matrix-js-sdk/lib/matrixrtc/CallMembership.js","../node_modules/matrix-js-sdk/lib/matrixrtc/types.js","../node_modules/matrix-js-sdk/lib/matrixrtc/MembershipManagerActionScheduler.js","../node_modules/matrix-js-sdk/lib/errors.js","../node_modules/matrix-js-sdk/lib/matrixrtc/IMembershipManager.js","../node_modules/matrix-js-sdk/lib/matrixrtc/MembershipManager.js","../node_modules/matrix-js-sdk/lib/matrixrtc/IKeyTransport.js","../node_modules/matrix-js-sdk/lib/matrixrtc/EncryptionManager.js","../node_modules/matrix-js-sdk/lib/matrixrtc/utils.js","../node_modules/matrix-js-sdk/lib/matrixrtc/RTCEncryptionManager.js","../node_modules/matrix-js-sdk/lib/matrixrtc/ToDeviceKeyTransport.js","../node_modules/matrix-js-sdk/lib/matrixrtc/RoomKeyTransport.js","../node_modules/matrix-js-sdk/lib/matrixrtc/MatrixRTCSession.js","../node_modules/matrix-js-sdk/lib/matrixrtc/MatrixRTCSessionManager.js","../node_modules/matrix-js-sdk/lib/thread-utils.js","../node_modules/jwt-decode/build/esm/index.js","../node_modules/oidc-client-ts/dist/esm/oidc-client-ts.js","../node_modules/matrix-js-sdk/lib/oidc/error.js","../node_modules/matrix-js-sdk/lib/oidc/validate.js","../node_modules/matrix-js-sdk/lib/oidc/discovery.js","../node_modules/matrix-js-sdk/lib/oidc/register.js","../node_modules/matrix-js-sdk/lib/client.js","../node_modules/matrix-js-sdk/lib/models/thread.js","../node_modules/matrix-js-sdk/lib/common-crypto/CryptoBackend.js","../node_modules/matrix-js-sdk/lib/models/event.js","../node_modules/matrix-js-sdk/lib/receipt-accumulator.js","../node_modules/matrix-js-sdk/lib/sync-accumulator.js","../node_modules/matrix-js-sdk/lib/indexeddb-helpers.js","../node_modules/matrix-js-sdk/lib/store/indexeddb-local-backend.js","../node_modules/matrix-js-sdk/lib/store/indexeddb-store-worker.js","../src/IndexedDBWorker.ts"],"sourcesContent":["function _typeof(o) {\n  \"@babel/helpers - typeof\";\n\n  return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n    return typeof o;\n  } : function (o) {\n    return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n  }, _typeof(o);\n}\nexport { _typeof as default };","import _typeof from \"./typeof.js\";\nfunction toPrimitive(t, r) {\n  if (\"object\" != _typeof(t) || !t) return t;\n  var e = t[Symbol.toPrimitive];\n  if (void 0 !== e) {\n    var i = e.call(t, r || \"default\");\n    if (\"object\" != _typeof(i)) return i;\n    throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n  }\n  return (\"string\" === r ? String : Number)(t);\n}\nexport { toPrimitive as default };","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nfunction toPropertyKey(t) {\n  var i = toPrimitive(t, \"string\");\n  return \"symbol\" == _typeof(i) ? i : i + \"\";\n}\nexport { toPropertyKey as default };","import toPropertyKey from \"./toPropertyKey.js\";\nfunction _defineProperty(e, r, t) {\n  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n    value: t,\n    enumerable: !0,\n    configurable: !0,\n    writable: !0\n  }) : e[r] = t, e;\n}\nexport { _defineProperty as default };","function asyncGeneratorStep(n, t, e, r, o, a, c) {\n  try {\n    var i = n[a](c),\n      u = i.value;\n  } catch (n) {\n    return void e(n);\n  }\n  i.done ? t(u) : Promise.resolve(u).then(r, o);\n}\nfunction _asyncToGenerator(n) {\n  return function () {\n    var t = this,\n      e = arguments;\n    return new Promise(function (r, o) {\n      var a = n.apply(t, e);\n      function _next(n) {\n        asyncGeneratorStep(a, r, o, _next, _throw, \"next\", n);\n      }\n      function _throw(n) {\n        asyncGeneratorStep(a, r, o, _next, _throw, \"throw\", n);\n      }\n      _next(void 0);\n    });\n  };\n}\nexport { _asyncToGenerator as default };","/*\n* loglevel - https://github.com/pimterry/loglevel\n*\n* Copyright (c) 2013 Tim Perry\n* Licensed under the MIT license.\n*/\n(function (root, definition) {\n    \"use strict\";\n    if (typeof define === 'function' && define.amd) {\n        define(definition);\n    } else if (typeof module === 'object' && module.exports) {\n        module.exports = definition();\n    } else {\n        root.log = definition();\n    }\n}(this, function () {\n    \"use strict\";\n\n    // Slightly dubious tricks to cut down minimized file size\n    var noop = function() {};\n    var undefinedType = \"undefined\";\n    var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (\n        /Trident\\/|MSIE /.test(window.navigator.userAgent)\n    );\n\n    var logMethods = [\n        \"trace\",\n        \"debug\",\n        \"info\",\n        \"warn\",\n        \"error\"\n    ];\n\n    var _loggersByName = {};\n    var defaultLogger = null;\n\n    // Cross-browser bind equivalent that works at least back to IE6\n    function bindMethod(obj, methodName) {\n        var method = obj[methodName];\n        if (typeof method.bind === 'function') {\n            return method.bind(obj);\n        } else {\n            try {\n                return Function.prototype.bind.call(method, obj);\n            } catch (e) {\n                // Missing bind shim or IE8 + Modernizr, fallback to wrapping\n                return function() {\n                    return Function.prototype.apply.apply(method, [obj, arguments]);\n                };\n            }\n        }\n    }\n\n    // Trace() doesn't print the message in IE, so for that case we need to wrap it\n    function traceForIE() {\n        if (console.log) {\n            if (console.log.apply) {\n                console.log.apply(console, arguments);\n            } else {\n                // In old IE, native console methods themselves don't have apply().\n                Function.prototype.apply.apply(console.log, [console, arguments]);\n            }\n        }\n        if (console.trace) console.trace();\n    }\n\n    // Build the best logging method possible for this env\n    // Wherever possible we want to bind, not wrap, to preserve stack traces\n    function realMethod(methodName) {\n        if (methodName === 'debug') {\n            methodName = 'log';\n        }\n\n        if (typeof console === undefinedType) {\n            return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives\n        } else if (methodName === 'trace' && isIE) {\n            return traceForIE;\n        } else if (console[methodName] !== undefined) {\n            return bindMethod(console, methodName);\n        } else if (console.log !== undefined) {\n            return bindMethod(console, 'log');\n        } else {\n            return noop;\n        }\n    }\n\n    // These private functions always need `this` to be set properly\n\n    function replaceLoggingMethods() {\n        /*jshint validthis:true */\n        var level = this.getLevel();\n\n        // Replace the actual methods.\n        for (var i = 0; i < logMethods.length; i++) {\n            var methodName = logMethods[i];\n            this[methodName] = (i < level) ?\n                noop :\n                this.methodFactory(methodName, level, this.name);\n        }\n\n        // Define log.log as an alias for log.debug\n        this.log = this.debug;\n\n        // Return any important warnings.\n        if (typeof console === undefinedType && level < this.levels.SILENT) {\n            return \"No console available for logging\";\n        }\n    }\n\n    // In old IE versions, the console isn't present until you first open it.\n    // We build realMethod() replacements here that regenerate logging methods\n    function enableLoggingWhenConsoleArrives(methodName) {\n        return function () {\n            if (typeof console !== undefinedType) {\n                replaceLoggingMethods.call(this);\n                this[methodName].apply(this, arguments);\n            }\n        };\n    }\n\n    // By default, we use closely bound real methods wherever possible, and\n    // otherwise we wait for a console to appear, and then try again.\n    function defaultMethodFactory(methodName, _level, _loggerName) {\n        /*jshint validthis:true */\n        return realMethod(methodName) ||\n               enableLoggingWhenConsoleArrives.apply(this, arguments);\n    }\n\n    function Logger(name, factory) {\n      // Private instance variables.\n      var self = this;\n      /**\n       * The level inherited from a parent logger (or a global default). We\n       * cache this here rather than delegating to the parent so that it stays\n       * in sync with the actual logging methods that we have installed (the\n       * parent could change levels but we might not have rebuilt the loggers\n       * in this child yet).\n       * @type {number}\n       */\n      var inheritedLevel;\n      /**\n       * The default level for this logger, if any. If set, this overrides\n       * `inheritedLevel`.\n       * @type {number|null}\n       */\n      var defaultLevel;\n      /**\n       * A user-specific level for this logger. If set, this overrides\n       * `defaultLevel`.\n       * @type {number|null}\n       */\n      var userLevel;\n\n      var storageKey = \"loglevel\";\n      if (typeof name === \"string\") {\n        storageKey += \":\" + name;\n      } else if (typeof name === \"symbol\") {\n        storageKey = undefined;\n      }\n\n      function persistLevelIfPossible(levelNum) {\n          var levelName = (logMethods[levelNum] || 'silent').toUpperCase();\n\n          if (typeof window === undefinedType || !storageKey) return;\n\n          // Use localStorage if available\n          try {\n              window.localStorage[storageKey] = levelName;\n              return;\n          } catch (ignore) {}\n\n          // Use session cookie as fallback\n          try {\n              window.document.cookie =\n                encodeURIComponent(storageKey) + \"=\" + levelName + \";\";\n          } catch (ignore) {}\n      }\n\n      function getPersistedLevel() {\n          var storedLevel;\n\n          if (typeof window === undefinedType || !storageKey) return;\n\n          try {\n              storedLevel = window.localStorage[storageKey];\n          } catch (ignore) {}\n\n          // Fallback to cookies if local storage gives us nothing\n          if (typeof storedLevel === undefinedType) {\n              try {\n                  var cookie = window.document.cookie;\n                  var cookieName = encodeURIComponent(storageKey);\n                  var location = cookie.indexOf(cookieName + \"=\");\n                  if (location !== -1) {\n                      storedLevel = /^([^;]+)/.exec(\n                          cookie.slice(location + cookieName.length + 1)\n                      )[1];\n                  }\n              } catch (ignore) {}\n          }\n\n          // If the stored level is not valid, treat it as if nothing was stored.\n          if (self.levels[storedLevel] === undefined) {\n              storedLevel = undefined;\n          }\n\n          return storedLevel;\n      }\n\n      function clearPersistedLevel() {\n          if (typeof window === undefinedType || !storageKey) return;\n\n          // Use localStorage if available\n          try {\n              window.localStorage.removeItem(storageKey);\n          } catch (ignore) {}\n\n          // Use session cookie as fallback\n          try {\n              window.document.cookie =\n                encodeURIComponent(storageKey) + \"=; expires=Thu, 01 Jan 1970 00:00:00 UTC\";\n          } catch (ignore) {}\n      }\n\n      function normalizeLevel(input) {\n          var level = input;\n          if (typeof level === \"string\" && self.levels[level.toUpperCase()] !== undefined) {\n              level = self.levels[level.toUpperCase()];\n          }\n          if (typeof level === \"number\" && level >= 0 && level <= self.levels.SILENT) {\n              return level;\n          } else {\n              throw new TypeError(\"log.setLevel() called with invalid level: \" + input);\n          }\n      }\n\n      /*\n       *\n       * Public logger API - see https://github.com/pimterry/loglevel for details\n       *\n       */\n\n      self.name = name;\n\n      self.levels = { \"TRACE\": 0, \"DEBUG\": 1, \"INFO\": 2, \"WARN\": 3,\n          \"ERROR\": 4, \"SILENT\": 5};\n\n      self.methodFactory = factory || defaultMethodFactory;\n\n      self.getLevel = function () {\n          if (userLevel != null) {\n            return userLevel;\n          } else if (defaultLevel != null) {\n            return defaultLevel;\n          } else {\n            return inheritedLevel;\n          }\n      };\n\n      self.setLevel = function (level, persist) {\n          userLevel = normalizeLevel(level);\n          if (persist !== false) {  // defaults to true\n              persistLevelIfPossible(userLevel);\n          }\n\n          // NOTE: in v2, this should call rebuild(), which updates children.\n          return replaceLoggingMethods.call(self);\n      };\n\n      self.setDefaultLevel = function (level) {\n          defaultLevel = normalizeLevel(level);\n          if (!getPersistedLevel()) {\n              self.setLevel(level, false);\n          }\n      };\n\n      self.resetLevel = function () {\n          userLevel = null;\n          clearPersistedLevel();\n          replaceLoggingMethods.call(self);\n      };\n\n      self.enableAll = function(persist) {\n          self.setLevel(self.levels.TRACE, persist);\n      };\n\n      self.disableAll = function(persist) {\n          self.setLevel(self.levels.SILENT, persist);\n      };\n\n      self.rebuild = function () {\n          if (defaultLogger !== self) {\n              inheritedLevel = normalizeLevel(defaultLogger.getLevel());\n          }\n          replaceLoggingMethods.call(self);\n\n          if (defaultLogger === self) {\n              for (var childName in _loggersByName) {\n                _loggersByName[childName].rebuild();\n              }\n          }\n      };\n\n      // Initialize all the internal levels.\n      inheritedLevel = normalizeLevel(\n          defaultLogger ? defaultLogger.getLevel() : \"WARN\"\n      );\n      var initialLevel = getPersistedLevel();\n      if (initialLevel != null) {\n          userLevel = normalizeLevel(initialLevel);\n      }\n      replaceLoggingMethods.call(self);\n    }\n\n    /*\n     *\n     * Top-level API\n     *\n     */\n\n    defaultLogger = new Logger();\n\n    defaultLogger.getLogger = function getLogger(name) {\n        if ((typeof name !== \"symbol\" && typeof name !== \"string\") || name === \"\") {\n            throw new TypeError(\"You must supply a name when creating a logger.\");\n        }\n\n        var logger = _loggersByName[name];\n        if (!logger) {\n            logger = _loggersByName[name] = new Logger(\n                name,\n                defaultLogger.methodFactory\n            );\n        }\n        return logger;\n    };\n\n    // Grab the current global log variable in case of overwrite\n    var _log = (typeof window !== undefinedType) ? window.log : undefined;\n    defaultLogger.noConflict = function() {\n        if (typeof window !== undefinedType &&\n               window.log === defaultLogger) {\n            window.log = _log;\n        }\n\n        return defaultLogger;\n    };\n\n    defaultLogger.getLoggers = function getLoggers() {\n        return _loggersByName;\n    };\n\n    // ES6 default export, for compatibility\n    defaultLogger['default'] = defaultLogger;\n\n    return defaultLogger;\n}));\n","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2018 André Jaenisch\nCopyright 2019-2025 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport loglevel from \"loglevel\";\n\n/** Backwards-compatibility hack to expose `log` to applications that might still be relying on it. */\n\n/** Logger interface used within the js-sdk codebase */\n\n/** The basic interface for a logger which doesn't support children */\n\n// This is to demonstrate, that you can use any namespace you want.\n// Namespaces allow you to turn on/off the logging for specific parts of the\n// application.\n// An idea would be to control this via an environment variable (on Node.js).\n// See https://www.npmjs.com/package/debug to see how this could be implemented\n// Part of #332 is introducing a logging library in the first place.\nvar DEFAULT_NAMESPACE = \"matrix\";\n\n// because rageshakes in react-sdk hijack the console log, also at module load time,\n// initializing the logger here races with the initialization of rageshakes.\n// to avoid the issue, we override the methodFactory of loglevel that binds to the\n// console methods at initialization time by a factory that looks up the console methods\n// when logging so we always get the current value of console methods.\nloglevel.methodFactory = function (methodName, logLevel, loggerName) {\n  return function () {\n    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n      args[_key] = arguments[_key];\n    }\n    /* eslint-disable @typescript-eslint/no-invalid-this */\n    if (this.prefix) {\n      args.unshift(this.prefix);\n    }\n    /* eslint-enable @typescript-eslint/no-invalid-this */\n    var supportedByConsole = methodName === \"error\" || methodName === \"warn\" || methodName === \"trace\" || methodName === \"info\" || methodName === \"debug\";\n    /* eslint-disable no-console */\n    if (supportedByConsole) {\n      return console[methodName](...args);\n    } else {\n      return console.log(...args);\n    }\n    /* eslint-enable no-console */\n  };\n};\n\n/**\n * Implementation of {@link Logger} based on `loglevel`.\n */\n\n/**\n * Internal utility function: gets a {@link Logger} based on `loglevel`.\n *\n * Child loggers produced by {@link Logger.getChild} add the name of the child logger as a prefix on each log line.\n *\n * @param prefix Prefix to add to each logged line. If undefined, no prefix will be added.\n */\nfunction getPrefixedLogger(prefix) {\n  var loggerName = DEFAULT_NAMESPACE + (prefix === undefined ? \"\" : \"-\".concat(prefix));\n  var prefixLogger = loglevel.getLogger(loggerName);\n  if (prefixLogger.getChild === undefined) {\n    // This is a new loglevel Logger which has not been turned into a PrefixedLogger yet.\n    prefixLogger.prefix = prefix;\n    prefixLogger.getChild = childPrefix => {\n      // create the new child logger\n      var childLogger = getPrefixedLogger((prefix !== null && prefix !== void 0 ? prefix : \"\") + childPrefix);\n      // Assign the methodFactory from the parent logger.\n      // This is useful if we add extensions to the parent logger that modifies\n      // its methodFactory. (An example extension is: storing each log to a rageshake db)\n      childLogger.methodFactory = prefixLogger.methodFactory;\n      // Rebuild the child logger with the new methodFactory.\n      childLogger.rebuild();\n      return childLogger;\n    };\n    prefixLogger.setLevel(loglevel.levels.DEBUG, false);\n  }\n  return prefixLogger;\n}\n\n/**\n * Drop-in replacement for `console` using {@link https://www.npmjs.com/package/loglevel|loglevel}.\n * Can be tailored down to specific use cases if needed.\n *\n * @deprecated avoid the use of this unless you are the constructor of `MatrixClient`: you should be using the logger\n *    associated with `MatrixClient`.\n */\nexport var logger = getPrefixedLogger();\n\n/**\n * A \"span\" for grouping related log lines together.\n *\n * The current implementation just adds the name at the start of each log line.\n *\n * This offers a lighter-weight alternative to 'child' loggers returned by {@link Logger#getChild}. In particular,\n * it's not possible to apply individual filters to the LogSpan such as setting the verbosity level. On the other hand,\n * no reference to the LogSpan is retained in the logging framework, so it is safe to make lots of them over the course\n * of an application's life and just drop references to them when the job is done.\n */\nexport class LogSpan {\n  constructor(parent, name) {\n    this.parent = parent;\n    _defineProperty(this, \"name\", void 0);\n    this.name = name + \":\";\n  }\n  trace() {\n    for (var _len2 = arguments.length, msg = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n      msg[_key2] = arguments[_key2];\n    }\n    this.parent.trace(this.name, ...msg);\n  }\n  debug() {\n    for (var _len3 = arguments.length, msg = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n      msg[_key3] = arguments[_key3];\n    }\n    this.parent.debug(this.name, ...msg);\n  }\n  info() {\n    for (var _len4 = arguments.length, msg = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n      msg[_key4] = arguments[_key4];\n    }\n    this.parent.info(this.name, ...msg);\n  }\n  warn() {\n    for (var _len5 = arguments.length, msg = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {\n      msg[_key5] = arguments[_key5];\n    }\n    this.parent.warn(this.name, ...msg);\n  }\n  error() {\n    for (var _len6 = arguments.length, msg = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {\n      msg[_key6] = arguments[_key6];\n    }\n    this.parent.error(this.name, ...msg);\n  }\n}\n\n/**\n * A simplification of the `Debugger` type exposed by the `debug` library. We reimplement the bits we need here\n * to avoid a dependency on `debug`.\n */\n\n/**\n * A `Logger` instance, suitable for use in {@link ICreateClientOpts.logger}, which will write to the `debug` library.\n *\n * @example\n * ```js\n *     import debug from \"debug\";\n *\n *     const client = createClient({\n *         baseUrl: homeserverUrl,\n *         userId: userId,\n *         accessToken: \"akjgkrgjs\",\n *         deviceId: \"xzcvb\",\n *         logger: new DebugLogger(debug(`matrix-js-sdk:${userId}`)),\n *     });\n * ```\n */\nexport class DebugLogger {\n  constructor(debugInstance) {\n    this.debugInstance = debugInstance;\n  }\n  trace() {\n    for (var _len7 = arguments.length, msg = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {\n      msg[_key7] = arguments[_key7];\n    }\n    this.debugWithPrefix(\"[TRACE]\", ...msg);\n  }\n  debug() {\n    for (var _len8 = arguments.length, msg = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {\n      msg[_key8] = arguments[_key8];\n    }\n    this.debugWithPrefix(\"[DEBUG]\", ...msg);\n  }\n  info() {\n    for (var _len9 = arguments.length, msg = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {\n      msg[_key9] = arguments[_key9];\n    }\n    this.debugWithPrefix(\"[INFO]\", ...msg);\n  }\n  warn() {\n    for (var _len0 = arguments.length, msg = new Array(_len0), _key0 = 0; _key0 < _len0; _key0++) {\n      msg[_key0] = arguments[_key0];\n    }\n    this.debugWithPrefix(\"[WARN]\", ...msg);\n  }\n  error() {\n    for (var _len1 = arguments.length, msg = new Array(_len1), _key1 = 0; _key1 < _len1; _key1++) {\n      msg[_key1] = arguments[_key1];\n    }\n    this.debugWithPrefix(\"[ERROR]\", ...msg);\n  }\n  getChild(namespace) {\n    return new DebugLogger(this.debugInstance.extend(namespace));\n  }\n  debugWithPrefix(prefix) {\n    var formatter;\n\n    // Convert the first argument to a string, so that we can safely add a prefix. This is much the same logic that\n    // `debug()` uses.\n    for (var _len10 = arguments.length, msg = new Array(_len10 > 1 ? _len10 - 1 : 0), _key10 = 1; _key10 < _len10; _key10++) {\n      msg[_key10 - 1] = arguments[_key10];\n    }\n    if (msg.length === 0) {\n      formatter = \"\";\n    } else if (msg[0] instanceof Error) {\n      var err = msg.shift();\n      formatter = err.stack || err.message;\n    } else if (typeof msg[0] == \"string\") {\n      formatter = msg.shift();\n    } else {\n      formatter = \"%O\";\n    }\n    this.debugInstance(prefix + \" \" + formatter, ...msg);\n  }\n}\n//# sourceMappingURL=logger.js.map","'use strict';\n\n\nvar data = require('./data.json');\n\nfunction escapeRegexp(str) {\n  return str.replace(/([.?*+^$[\\]\\\\(){}|-])/g, '\\\\$1');\n}\n\nvar REPLACE_RE = RegExp(Object.keys(data).map(escapeRegexp).join('|'), 'g');\n\nfunction replace_fn(match) {\n  return data[match];\n}\n\nfunction unhomoglyph(str) {\n  return str.replace(REPLACE_RE, replace_fn);\n}\n\nmodule.exports = unhomoglyph;\n","const objectToString = Object.prototype.toString;\n\nconst isError = value => objectToString.call(value) === '[object Error]';\n\nconst errorMessages = new Set([\n\t'network error', // Chrome\n\t'Failed to fetch', // Chrome\n\t'NetworkError when attempting to fetch resource.', // Firefox\n\t'The Internet connection appears to be offline.', // Safari 16\n\t'Network request failed', // `cross-fetch`\n\t'fetch failed', // Undici (Node.js)\n\t'terminated', // Undici (Node.js)\n\t' A network error occurred.', // Bun (WebKit)\n\t'Network connection lost', // Cloudflare Workers (fetch)\n]);\n\nexport default function isNetworkError(error) {\n\tconst isValid = error\n\t\t&& isError(error)\n\t\t&& error.name === 'TypeError'\n\t\t&& typeof error.message === 'string';\n\n\tif (!isValid) {\n\t\treturn false;\n\t}\n\n\tconst {message, stack} = error;\n\n\t// Safari 17+ has generic message but no stack for network errors\n\tif (message === 'Load failed') {\n\t\treturn stack === undefined\n\t\t\t// Sentry adds its own stack trace to the fetch error, so also check for that\n\t\t\t|| '__sentry_captured__' in error;\n\t}\n\n\t// Deno network errors start with specific text\n\tif (message.startsWith('error sending request for url')) {\n\t\treturn true;\n\t}\n\n\t// Standard network error messages\n\treturn errorMessages.has(message);\n}\n","import isNetworkError from 'is-network-error';\n\nfunction validateRetries(retries) {\n\tif (typeof retries === 'number') {\n\t\tif (retries < 0) {\n\t\t\tthrow new TypeError('Expected `retries` to be a non-negative number.');\n\t\t}\n\n\t\tif (Number.isNaN(retries)) {\n\t\t\tthrow new TypeError('Expected `retries` to be a valid number or Infinity, got NaN.');\n\t\t}\n\t} else if (retries !== undefined) {\n\t\tthrow new TypeError('Expected `retries` to be a number or Infinity.');\n\t}\n}\n\nfunction validateNumberOption(name, value, {min = 0, allowInfinity = false} = {}) {\n\tif (value === undefined) {\n\t\treturn;\n\t}\n\n\tif (typeof value !== 'number' || Number.isNaN(value)) {\n\t\tthrow new TypeError(`Expected \\`${name}\\` to be a number${allowInfinity ? ' or Infinity' : ''}.`);\n\t}\n\n\tif (!allowInfinity && !Number.isFinite(value)) {\n\t\tthrow new TypeError(`Expected \\`${name}\\` to be a finite number.`);\n\t}\n\n\tif (value < min) {\n\t\tthrow new TypeError(`Expected \\`${name}\\` to be \\u2265 ${min}.`);\n\t}\n}\n\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\n\t\tif (message instanceof Error) {\n\t\t\tthis.originalError = message;\n\t\t\t({message} = message);\n\t\t} else {\n\t\t\tthis.originalError = new Error(message);\n\t\t\tthis.originalError.stack = this.stack;\n\t\t}\n\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\nconst createRetryContext = (error, attemptNumber, options) => {\n\t// Minus 1 from attemptNumber because the first attempt does not count as a retry\n\tconst retriesLeft = options.retries - (attemptNumber - 1);\n\n\treturn Object.freeze({\n\t\terror,\n\t\tattemptNumber,\n\t\tretriesLeft,\n\t});\n};\n\nfunction calculateDelay(attempt, options) {\n\tconst random = options.randomize ? (Math.random() + 1) : 1;\n\n\tlet timeout = Math.round(random * Math.max(options.minTimeout, 1) * (options.factor ** (attempt - 1)));\n\ttimeout = Math.min(timeout, options.maxTimeout);\n\n\treturn timeout;\n}\n\nasync function onAttemptFailure(error, attemptNumber, options, startTime, maxRetryTime) {\n\tlet normalizedError = error;\n\n\tif (!(normalizedError instanceof Error)) {\n\t\tnormalizedError = new TypeError(`Non-error was thrown: \"${normalizedError}\". You should only throw errors.`);\n\t}\n\n\tif (normalizedError instanceof AbortError) {\n\t\tthrow normalizedError.originalError;\n\t}\n\n\tif (normalizedError instanceof TypeError && !isNetworkError(normalizedError)) {\n\t\tthrow normalizedError;\n\t}\n\n\tconst context = createRetryContext(normalizedError, attemptNumber, options);\n\n\t// Always call onFailedAttempt\n\tawait options.onFailedAttempt(context);\n\n\tconst currentTime = Date.now();\n\tif (\n\t\tcurrentTime - startTime >= maxRetryTime\n\t\t|| attemptNumber >= options.retries + 1\n\t\t|| !(await options.shouldRetry(context))\n\t) {\n\t\tthrow normalizedError; // Do not retry, throw the original error\n\t}\n\n\t// Calculate delay before next attempt\n\tconst delayTime = calculateDelay(attemptNumber, options);\n\n\t// Ensure that delay does not exceed maxRetryTime\n\tconst timeLeft = maxRetryTime - (currentTime - startTime);\n\tif (timeLeft <= 0) {\n\t\tthrow normalizedError; // Max retry time exceeded\n\t}\n\n\tconst finalDelay = Math.min(delayTime, timeLeft);\n\n\t// Introduce delay\n\tif (finalDelay > 0) {\n\t\tawait new Promise((resolve, reject) => {\n\t\t\tconst onAbort = () => {\n\t\t\t\tclearTimeout(timeoutToken);\n\t\t\t\toptions.signal?.removeEventListener('abort', onAbort);\n\t\t\t\treject(options.signal.reason);\n\t\t\t};\n\n\t\t\tconst timeoutToken = setTimeout(() => {\n\t\t\t\toptions.signal?.removeEventListener('abort', onAbort);\n\t\t\t\tresolve();\n\t\t\t}, finalDelay);\n\n\t\t\tif (options.unref) {\n\t\t\t\ttimeoutToken.unref?.();\n\t\t\t}\n\n\t\t\toptions.signal?.addEventListener('abort', onAbort, {once: true});\n\t\t});\n\t}\n\n\toptions.signal?.throwIfAborted();\n}\n\nexport default async function pRetry(input, options = {}) {\n\toptions = {...options};\n\n\tvalidateRetries(options.retries);\n\n\tif (Object.hasOwn(options, 'forever')) {\n\t\tthrow new Error('The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.');\n\t}\n\n\toptions.retries ??= 10;\n\toptions.factor ??= 2;\n\toptions.minTimeout ??= 1000;\n\toptions.maxTimeout ??= Number.POSITIVE_INFINITY;\n\toptions.randomize ??= false;\n\toptions.onFailedAttempt ??= () => {};\n\toptions.shouldRetry ??= () => true;\n\n\t// Validate numeric options and normalize edge cases\n\tvalidateNumberOption('factor', options.factor, {min: 0, allowInfinity: false});\n\tvalidateNumberOption('minTimeout', options.minTimeout, {min: 0, allowInfinity: false});\n\tvalidateNumberOption('maxTimeout', options.maxTimeout, {min: 0, allowInfinity: true});\n\tconst resolvedMaxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;\n\tvalidateNumberOption('maxRetryTime', resolvedMaxRetryTime, {min: 0, allowInfinity: true});\n\n\t// Treat non-positive factor as 1 to avoid zero backoff or negative behavior\n\tif (!(options.factor > 0)) {\n\t\toptions.factor = 1;\n\t}\n\n\toptions.signal?.throwIfAborted();\n\n\tlet attemptNumber = 0;\n\tconst startTime = Date.now();\n\n\t// Use validated local value\n\tconst maxRetryTime = resolvedMaxRetryTime;\n\n\twhile (attemptNumber < options.retries + 1) {\n\t\tattemptNumber++;\n\n\t\ttry {\n\t\t\toptions.signal?.throwIfAborted();\n\n\t\t\tconst result = await input(attemptNumber);\n\n\t\t\toptions.signal?.throwIfAborted();\n\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tawait onAttemptFailure(error, attemptNumber, options, startTime, maxRetryTime);\n\t\t}\n\t}\n\n\t// Should not reach here, but in case it does, throw an error\n\tthrow new Error('Retry attempts exhausted without throwing an error.');\n}\n\nexport function makeRetriable(function_, options) {\n\treturn function (...arguments_) {\n\t\treturn pRetry(() => function_.apply(this, arguments_), options);\n\t};\n}\n","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2021 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Represents a simple Matrix namespaced value. This will assume that if a stable prefix\n * is provided that the stable prefix should be used when representing the identifier.\n */\nexport class NamespacedValue {\n  // Stable is optional, but one of the two parameters is required, hence the weird-looking types.\n  // Goal is to to have developers explicitly say there is no stable value (if applicable).\n\n  constructor(stable, unstable) {\n    this.stable = stable;\n    this.unstable = unstable;\n    if (!this.unstable && !this.stable) {\n      throw new Error(\"One of stable or unstable values must be supplied\");\n    }\n  }\n  get name() {\n    if (this.stable) {\n      return this.stable;\n    }\n    return this.unstable;\n  }\n  get altName() {\n    if (!this.stable) {\n      return null;\n    }\n    return this.unstable;\n  }\n  get names() {\n    var names = [this.name];\n    var altName = this.altName;\n    if (altName) names.push(altName);\n    return names;\n  }\n  matches(val) {\n    return this.name === val || this.altName === val;\n  }\n\n  // this desperately wants https://github.com/microsoft/TypeScript/pull/26349 at the top level of the class\n  // so we can instantiate `NamespacedValue<string, _, _>` as a default type for that namespace.\n  findIn(obj) {\n    var val = undefined;\n    if (this.name) {\n      val = obj === null || obj === void 0 ? void 0 : obj[this.name];\n    }\n    if (!val && this.altName) {\n      val = obj === null || obj === void 0 ? void 0 : obj[this.altName];\n    }\n    return val;\n  }\n  includedIn(arr) {\n    var included = false;\n    if (this.name) {\n      included = arr.includes(this.name);\n    }\n    if (!included && this.altName) {\n      included = arr.includes(this.altName);\n    }\n    return included;\n  }\n}\nexport class ServerControlledNamespacedValue extends NamespacedValue {\n  constructor() {\n    super(...arguments);\n    _defineProperty(this, \"preferUnstable\", false);\n  }\n  setPreferUnstable(preferUnstable) {\n    this.preferUnstable = preferUnstable;\n  }\n  get name() {\n    if (this.stable && !this.preferUnstable) {\n      return this.stable;\n    }\n    return this.unstable;\n  }\n}\n\n/**\n * Represents a namespaced value which prioritizes the unstable value over the stable\n * value.\n */\nexport class UnstableValue extends NamespacedValue {\n  // Note: Constructor difference is that `unstable` is *required*.\n  constructor(stable, unstable) {\n    super(stable, unstable);\n    if (!this.unstable) {\n      throw new Error(\"Unstable value must be supplied\");\n    }\n  }\n  get name() {\n    return this.unstable;\n  }\n  get altName() {\n    return this.stable;\n  }\n}\n//# sourceMappingURL=NamespacedValue.js.map","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// Types for MSC3488 - m.location: Extending events with location data\n\nimport { UnstableValue } from \"../NamespacedValue.js\";\nexport var LocationAssetType = /*#__PURE__*/function (LocationAssetType) {\n  LocationAssetType[\"Self\"] = \"m.self\";\n  LocationAssetType[\"Pin\"] = \"m.pin\";\n  return LocationAssetType;\n}({});\nexport var M_ASSET = new UnstableValue(\"m.asset\", \"org.matrix.msc3488.asset\");\n\n/**\n * The event definition for an m.asset event (in content)\n */\n\nexport var M_TIMESTAMP = new UnstableValue(\"m.ts\", \"org.matrix.msc3488.ts\");\n/**\n * The event definition for an m.ts event (in content)\n */\n\nexport var M_LOCATION = new UnstableValue(\"m.location\", \"org.matrix.msc3488.location\");\n\n/* From the spec at:\n * https://github.com/matrix-org/matrix-doc/blob/matthew/location/proposals/3488-location.md\n{\n    \"type\": \"m.room.message\",\n    \"content\": {\n        \"body\": \"Matthew was at geo:51.5008,0.1247;u=35 as of Sat Nov 13 18:50:58 2021\",\n        \"msgtype\": \"m.location\",\n        \"geo_uri\": \"geo:51.5008,0.1247;u=35\",\n        \"m.location\": {\n            \"uri\": \"geo:51.5008,0.1247;u=35\",\n            \"description\": \"Matthew's whereabouts\",\n        },\n        \"m.asset\": {\n            \"type\": \"m.self\"\n        },\n        \"m.text\": \"Matthew was at geo:51.5008,0.1247;u=35 as of Sat Nov 13 18:50:58 2021\",\n        \"m.ts\": 1636829458432,\n    }\n}\n*/\n\n/**\n * The content for an m.location event\n */\n\n/**\n * Possible content for location events as sent over the wire\n */\n//# sourceMappingURL=location.js.map","/*\nCopyright 2022 Šimon Brandner <simon.bra.ag@gmail.com>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport var ReceiptType = /*#__PURE__*/function (ReceiptType) {\n  ReceiptType[\"Read\"] = \"m.read\";\n  ReceiptType[\"FullyRead\"] = \"m.fully_read\";\n  ReceiptType[\"ReadPrivate\"] = \"m.read.private\";\n  return ReceiptType;\n}({});\nexport var MAIN_ROOM_TIMELINE = \"main\";\n\n// We will only hold a synthetic receipt if we do not have a real receipt or the synthetic is newer.\n// map: receipt type → user Id → receipt\n//# sourceMappingURL=read_receipts.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2015, 2016, 2019, 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module.\n */\n\nimport unhomoglyph from \"unhomoglyph\";\nimport promiseRetry from \"p-retry\";\nimport { M_TIMESTAMP } from \"./@types/location.js\";\nimport { ReceiptType } from \"./@types/read_receipts.js\";\nvar interns = new Map();\n\n/**\n * Internalises a string, reusing a known pointer or storing the pointer\n * if needed for future strings.\n * @param str - The string to internalise.\n * @returns The internalised string.\n */\nexport function internaliseString(str) {\n  // Unwrap strings before entering the map, if we somehow got a wrapped\n  // string as our input. This should only happen from tests.\n  if (str instanceof String) {\n    str = str.toString();\n  }\n\n  // Check the map to see if we can store the value\n  if (!interns.has(str)) {\n    interns.set(str, str);\n  }\n\n  // Return any cached string reference\n  return interns.get(str);\n}\n\n/**\n * Encode a dictionary of query parameters.\n * Omits any undefined/null values.\n * @param params - A dict of key/values to encode e.g.\n * `{\"foo\": \"bar\", \"baz\": \"taz\"}`\n * @returns The encoded string e.g. foo=bar&baz=taz\n */\nexport function encodeParams(params, urlSearchParams) {\n  var searchParams = urlSearchParams !== null && urlSearchParams !== void 0 ? urlSearchParams : new URLSearchParams();\n  var _loop = function _loop(key) {\n    if (val !== undefined && val !== null) {\n      if (Array.isArray(val)) {\n        val.forEach(v => {\n          searchParams.append(key, String(v));\n        });\n      } else {\n        searchParams.append(key, String(val));\n      }\n    }\n  };\n  for (var [key, val] of Object.entries(params)) {\n    _loop(key);\n  }\n  return searchParams;\n}\n/**\n * Replace a stable parameter with the unstable naming for params\n */\nexport function replaceParam(stable, unstable, dict) {\n  var result = _objectSpread(_objectSpread({}, dict), {}, {\n    [unstable]: dict[stable]\n  });\n  delete result[stable];\n  return result;\n}\n\n/**\n * Decode a query string in `application/x-www-form-urlencoded` format.\n * @param query - A query string to decode e.g.\n * foo=bar&via=server1&server2\n * @returns The decoded object, if any keys occurred multiple times\n * then the value will be an array of strings, else it will be an array.\n * This behaviour matches Node's qs.parse but is built on URLSearchParams\n * for native web compatibility\n */\nexport function decodeParams(query) {\n  var o = {};\n  var params = new URLSearchParams(query);\n  for (var key of params.keys()) {\n    var val = params.getAll(key);\n    o[key] = val.length === 1 ? val[0] : val;\n  }\n  return o;\n}\n\n/**\n * Encodes a URI according to a set of template variables. Variables will be\n * passed through encodeURIComponent.\n * @param pathTemplate - The path with template variables e.g. '/foo/$bar'.\n * @param variables - The key/value pairs to replace the template\n * variables with. E.g. `{ \"$bar\": \"baz\" }`.\n * @returns The result of replacing all template variables e.g. '/foo/baz'.\n */\nexport function encodeUri(pathTemplate, variables) {\n  for (var key in variables) {\n    if (!variables.hasOwnProperty(key)) {\n      continue;\n    }\n    var value = variables[key];\n    if (value === undefined || value === null) {\n      continue;\n    }\n    pathTemplate = pathTemplate.replace(key, encodeURIComponent(value));\n  }\n  return pathTemplate;\n}\n\n/**\n * The removeElement() method removes the first element in the array that\n * satisfies (returns true) the provided testing function.\n * @param array - The array.\n * @param fn - Function to execute on each value in the array, with the\n * function signature `fn(element, index, array)`. Return true to\n * remove this element and break.\n * @param reverse - True to search in reverse order.\n * @returns True if an element was removed.\n */\nexport function removeElement(array, fn, reverse) {\n  var i;\n  if (reverse) {\n    for (i = array.length - 1; i >= 0; i--) {\n      if (fn(array[i], i, array)) {\n        array.splice(i, 1);\n        return true;\n      }\n    }\n  } else {\n    for (i = 0; i < array.length; i++) {\n      if (fn(array[i], i, array)) {\n        array.splice(i, 1);\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\n/**\n * Checks if the given thing is a function.\n * @param value - The thing to check.\n * @returns True if it is a function.\n */\nexport function isFunction(value) {\n  return Object.prototype.toString.call(value) === \"[object Function]\";\n}\n\n/**\n * Checks that the given object has the specified keys.\n * @param obj - The object to check.\n * @param keys - The list of keys that 'obj' must have.\n * @throws If the object is missing keys.\n */\n// note using 'keys' here would shadow the 'keys' function defined above\nexport function checkObjectHasKeys(obj, keys) {\n  for (var key of keys) {\n    if (!obj.hasOwnProperty(key)) {\n      throw new Error(\"Missing required key: \" + key);\n    }\n  }\n}\n\n/**\n * Deep copy the given object. The object MUST NOT have circular references and\n * MUST NOT have functions.\n * @param obj - The object to deep copy.\n * @returns A copy of the object without any references to the original.\n */\nexport function deepCopy(obj) {\n  return JSON.parse(JSON.stringify(obj));\n}\n\n/**\n * Compare two objects for equality. The objects MUST NOT have circular references.\n *\n * @param x - The first object to compare.\n * @param y - The second object to compare.\n *\n * @returns true if the two objects are equal\n */\nexport function deepCompare(x, y) {\n  // Inspired by\n  // http://stackoverflow.com/questions/1068834/object-comparison-in-javascript#1144249\n\n  // Compare primitives and functions.\n  // Also check if both arguments link to the same object.\n  if (x === y) {\n    return true;\n  }\n  if (typeof x !== typeof y) {\n    return false;\n  }\n\n  // special-case NaN (since NaN !== NaN)\n  if (typeof x === \"number\" && isNaN(x) && isNaN(y)) {\n    return true;\n  }\n\n  // special-case null (since typeof null == 'object', but null.constructor\n  // throws)\n  if (x === null || y === null) {\n    return x === y;\n  }\n\n  // everything else is either an unequal primitive, or an object\n  // XXX: this check has been temporarily tweaked due to issues in the jest test environment,\n  // this will be reverted as part of the migration to vitest\n  if (x.constructor.name !== \"Object\" && x.constructor.name !== \"RegExp\" && x.constructor.name !== \"Date\" && x.constructor.name !== \"Array\") {\n    return false;\n  }\n\n  // check they are the same type of object\n  // XXX: this check has been temporarily tweaked due to issues in the jest test environment,\n  // this will be reverted as part of the migration to vitest\n  if (x.prototype !== y.prototype) {\n    return false;\n  }\n\n  // special-casing for some special types of object\n  if (x instanceof RegExp || x instanceof Date) {\n    return x.toString() === y.toString();\n  }\n\n  // the object algorithm works for Array, but it's sub-optimal.\n  if (Array.isArray(x)) {\n    if (x.length !== y.length) {\n      return false;\n    }\n    for (var i = 0; i < x.length; i++) {\n      if (!deepCompare(x[i], y[i])) {\n        return false;\n      }\n    }\n  } else {\n    // check that all of y's direct keys are in x\n    for (var p in y) {\n      if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {\n        return false;\n      }\n    }\n\n    // finally, compare each of x's keys with y\n    for (var _p in x) {\n      if (y.hasOwnProperty(_p) !== x.hasOwnProperty(_p) || !deepCompare(x[_p], y[_p])) {\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\n// Dev note: This returns an array of tuples, but jsdoc doesn't like that. https://github.com/jsdoc/jsdoc/issues/1703\n/**\n * Creates an array of object properties/values (entries) then\n * sorts the result by key, recursively. The input object must\n * ensure it does not have loops. If the input is not an object\n * then it will be returned as-is.\n * @param obj - The object to get entries of\n * @returns The entries, sorted by key.\n */\nexport function deepSortedObjectEntries(obj) {\n  if (typeof obj !== \"object\") return obj;\n\n  // Apparently these are object types...\n  if (obj === null || obj === undefined || Array.isArray(obj)) return obj;\n  var pairs = [];\n  for (var [k, v] of Object.entries(obj)) {\n    pairs.push([k, deepSortedObjectEntries(v)]);\n  }\n\n  // lexicographicCompare is faster than localeCompare, so let's use that.\n  pairs.sort((a, b) => lexicographicCompare(a[0], b[0]));\n  return pairs;\n}\n\n/**\n * Returns whether the given value is a finite number without type-coercion\n *\n * @param value - the value to test\n * @returns whether or not value is a finite number without type-coercion\n */\nexport function isNumber(value) {\n  return typeof value === \"number\" && isFinite(value);\n}\n\n/**\n * Removes zero width chars, diacritics and whitespace from the string\n * Also applies an unhomoglyph on the string, to prevent similar looking chars\n * @param str - the string to remove hidden characters from\n * @returns a string with the hidden characters removed\n */\nexport function removeHiddenChars(str) {\n  if (typeof str === \"string\") {\n    return unhomoglyph(str.normalize(\"NFD\").replace(removeHiddenCharsRegex, \"\"));\n  }\n  return \"\";\n}\n\n/**\n * Removes the direction override characters from a string\n * @returns string with chars removed\n */\nexport function removeDirectionOverrideChars(str) {\n  if (typeof str === \"string\") {\n    return str.replace(/[\\u202d-\\u202e]/g, \"\");\n  }\n  return \"\";\n}\nexport function normalize(str) {\n  // Note: we have to match the filter with the removeHiddenChars() because the\n  // function strips spaces and other characters (M becomes RN for example, in lowercase).\n  return removeHiddenChars(str.toLowerCase())\n  // Strip all punctuation\n  .replace(/[\\\\'!\"#$%&()*+,\\-./:;<=>?@[\\]^_`{|}~\\u2000-\\u206f\\u2e00-\\u2e7f]/g, \"\")\n  // We also doubly convert to lowercase to work around oddities of the library.\n  .toLowerCase();\n}\n\n// Regex matching bunch of unicode control characters and otherwise misleading/invisible characters.\n// Includes:\n// various width spaces U+2000 - U+200D\n// LTR and RTL marks U+200E and U+200F\n// LTR/RTL and other directional formatting marks U+202A - U+202F\n// Arabic Letter RTL mark U+061C\n// Combining characters U+0300 - U+036F\n// Zero width no-break space (BOM) U+FEFF\n// Blank/invisible characters (U2800, U2062-U2063)\n// eslint-disable-next-line no-misleading-character-class\nvar removeHiddenCharsRegex = /[\\u2000-\\u200F\\u202A-\\u202F\\u0300-\\u036F\\uFEFF\\u061C\\u2800\\u2062-\\u2063\\s]/g;\nexport function escapeRegExp(string) {\n  return string.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Converts Matrix glob-style string to a regular expression\n * https://spec.matrix.org/v1.7/appendices/#glob-style-matching\n * @param glob - Matrix glob-style string\n * @returns regular expression\n */\nexport function globToRegexp(glob) {\n  return escapeRegExp(glob).replace(/\\\\\\*/g, \".*\").replace(/\\?/g, \".\");\n}\nexport function ensureNoTrailingSlash(url) {\n  if (url !== null && url !== void 0 && url.endsWith(\"/\")) {\n    return url.slice(0, -1);\n  } else {\n    return url;\n  }\n}\n\n/**\n * Returns a promise which resolves with a given value after the given number of ms\n */\nexport function sleep(ms, value) {\n  return new Promise(resolve => {\n    setTimeout(resolve, ms, value);\n  });\n}\n\n/**\n * Utility to log the duration of a promise.\n *\n * @param logger - The logger to log to.\n * @param name - The name of the operation.\n * @param block - The block to execute.\n */\nexport function logDuration(_x, _x2, _x3) {\n  return _logDuration.apply(this, arguments);\n}\n\n/**\n * Utility to log the duration of a synchronous block.\n *\n * @param logger - The logger to log to.\n * @param name - The name of the operation.\n * @param block - The block to execute.\n */\nfunction _logDuration() {\n  _logDuration = _asyncToGenerator(function* (logger, name, block) {\n    var start = Date.now();\n    try {\n      return yield block();\n    } finally {\n      var end = Date.now();\n      logger.debug(\"[Perf]: \".concat(name, \" took \").concat(end - start, \"ms\"));\n    }\n  });\n  return _logDuration.apply(this, arguments);\n}\nexport function logDurationSync(logger, name, block) {\n  var start = Date.now();\n  try {\n    return block();\n  } finally {\n    var end = Date.now();\n    logger.debug(\"[Perf]: \".concat(name, \" took \").concat(end - start, \"ms\"));\n  }\n}\n\n/**\n * Promise/async version of {@link setImmediate}.\n *\n * Implementation is based on `setTimeout` for wider compatibility.\n * @deprecated Use {@link sleep} instead.\n */\nexport function immediate() {\n  return new Promise(resolve => setTimeout(resolve));\n}\nexport function isNullOrUndefined(val) {\n  return val === null || val === undefined;\n}\nexport function promiseMapSeries(_x4, _x5) {\n  return _promiseMapSeries.apply(this, arguments);\n}\nfunction _promiseMapSeries() {\n  _promiseMapSeries = _asyncToGenerator(function* (promises, fn // if async we don't care about the type as we only await resolution\n  ) {\n    for (var o of promises) {\n      yield fn(yield o);\n    }\n  });\n  return _promiseMapSeries.apply(this, arguments);\n}\nexport function promiseTry(fn) {\n  return Promise.resolve(fn());\n}\n\n// Creates and awaits all promises, running no more than `chunkSize` at the same time\nexport function chunkPromises(_x6, _x7) {\n  return _chunkPromises.apply(this, arguments);\n}\n\n/**\n * Retries the function until it succeeds or is interrupted. The given function must return\n * a promise which throws/rejects on error, otherwise the retry will assume the request\n * succeeded. The promise chain returned will contain the successful promise. The given function\n * should always return a new promise.\n * @param promiseFn - The function to call to get a fresh promise instance. Takes an\n * attempt count as an argument, for logging/debugging purposes.\n * @param shouldRetry - Optional function which is called with the error the latest rejection from promiseFn,\n * retrying will ba aborted if this return false.\n * @returns The promise for the retried operation.\n */\nfunction _chunkPromises() {\n  _chunkPromises = _asyncToGenerator(function* (fns, chunkSize) {\n    var results = [];\n    for (var i = 0; i < fns.length; i += chunkSize) {\n      results.push(...(yield Promise.all(fns.slice(i, i + chunkSize).map(fn => fn()))));\n    }\n    return results;\n  });\n  return _chunkPromises.apply(this, arguments);\n}\nexport function simpleRetryOperation(promiseFn, shouldRetry) {\n  return promiseRetry(attempt => {\n    return promiseFn(attempt);\n  }, {\n    retries: Infinity,\n    shouldRetry: shouldRetry ? _ref => {\n      var {\n        error\n      } = _ref;\n      return shouldRetry(error);\n    } : undefined,\n    factor: 2,\n    minTimeout: 3000,\n    // ms\n    maxTimeout: 15000 // ms\n  });\n}\n\n// String averaging inspired by https://stackoverflow.com/a/2510816\n// Dev note: We make the alphabet a string because it's easier to write syntactically\n// than arrays. Thankfully, strings implement the useful parts of the Array interface\n// anyhow.\n\n/**\n * The default alphabet used by string averaging in this SDK. This matches\n * all usefully printable ASCII characters (0x20-0x7E, inclusive).\n */\nexport var DEFAULT_ALPHABET = (() => {\n  var str = \"\";\n  for (var c = 0x20; c <= 0x7e; c++) {\n    str += String.fromCharCode(c);\n  }\n  return str;\n})();\n\n/**\n * Pads a string using the given alphabet as a base. The returned string will be\n * padded at the end with the first character in the alphabet.\n *\n * This is intended for use with string averaging.\n * @param s - The string to pad.\n * @param n - The length to pad to.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The padded string.\n */\nexport function alphabetPad(s, n) {\n  var alphabet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_ALPHABET;\n  return s.padEnd(n, alphabet[0]);\n}\n\n/**\n * Converts a baseN number to a string, where N is the alphabet's length.\n *\n * This is intended for use with string averaging.\n * @param n - The baseN number.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The baseN number encoded as a string from the alphabet.\n */\nexport function baseToString(n) {\n  var alphabet = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ALPHABET;\n  // Developer note: the stringToBase() function offsets the character set by 1 so that repeated\n  // characters (ie: \"aaaaaa\" in a..z) don't come out as zero. We have to reverse this here as\n  // otherwise we'll be wrong in our conversion. Undoing a +1 before an exponent isn't very fun\n  // though, so we rely on a lengthy amount of `x - 1` and integer division rules to reach a\n  // sane state. This also means we have to do rollover detection: see below.\n\n  var len = BigInt(alphabet.length);\n  if (n <= len) {\n    var _alphabet;\n    return (_alphabet = alphabet[Number(n) - 1]) !== null && _alphabet !== void 0 ? _alphabet : \"\";\n  }\n  var d = n / len;\n  var r = Number(n % len) - 1;\n\n  // Rollover detection: if the remainder is negative, it means that the string needs\n  // to roll over by 1 character downwards (ie: in a..z, the previous to \"aaa\" would be\n  // \"zz\").\n  if (r < 0) {\n    d -= BigInt(Math.abs(r)); // abs() is just to be clear what we're doing. Could also `+= r`.\n    r = Number(len) - 1;\n  }\n  return baseToString(d, alphabet) + alphabet[r];\n}\n\n/**\n * Converts a string to a baseN number, where N is the alphabet's length.\n *\n * This is intended for use with string averaging.\n * @param s - The string to convert to a number.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The baseN number.\n */\nexport function stringToBase(s) {\n  var alphabet = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ALPHABET;\n  var len = BigInt(alphabet.length);\n\n  // In our conversion to baseN we do a couple performance optimizations to avoid using\n  // excess CPU and such. To create baseN numbers, the input string needs to be reversed\n  // so the exponents stack up appropriately, as the last character in the unreversed\n  // string has less impact than the first character (in \"abc\" the A is a lot more important\n  // for lexicographic sorts). We also do a trick with the character codes to optimize the\n  // alphabet lookup, avoiding an index scan of `alphabet.indexOf(reversedStr[i])` - we know\n  // that the alphabet and (theoretically) the input string are constrained on character sets\n  // and thus can do simple subtraction to end up with the same result.\n\n  // Developer caution: we carefully cast to BigInt here to avoid losing precision. We cannot\n  // rely on Math.pow() (for example) to be capable of handling our insane numbers.\n\n  var result = BigInt(0);\n  for (var i = s.length - 1, j = BigInt(0); i >= 0; i--, j++) {\n    var charIndex = s.charCodeAt(i) - alphabet.charCodeAt(0);\n\n    // We add 1 to the char index to offset the whole numbering scheme. We unpack this in\n    // the baseToString() function.\n    result += BigInt(1 + charIndex) * len ** j;\n  }\n  return result;\n}\n\n/**\n * Averages two strings, returning the midpoint between them. This is accomplished by\n * converting both to baseN numbers (where N is the alphabet's length) then averaging\n * those before re-encoding as a string.\n * @param a - The first string.\n * @param b - The second string.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The midpoint between the strings, as a string.\n */\nexport function averageBetweenStrings(a, b) {\n  var alphabet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_ALPHABET;\n  var padN = Math.max(a.length, b.length);\n  var baseA = stringToBase(alphabetPad(a, padN, alphabet), alphabet);\n  var baseB = stringToBase(alphabetPad(b, padN, alphabet), alphabet);\n  var avg = (baseA + baseB) / BigInt(2);\n\n  // Detect integer division conflicts. This happens when two numbers are divided too close so\n  // we lose a .5 precision. We need to add a padding character in these cases.\n  if (avg === baseA || avg == baseB) {\n    return baseToString(avg, alphabet) + alphabet[0];\n  }\n  return baseToString(avg, alphabet);\n}\n\n/**\n * Finds the next string using the alphabet provided. This is done by converting the\n * string to a baseN number, where N is the alphabet's length, then adding 1 before\n * converting back to a string.\n * @param s - The string to start at.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The string which follows the input string.\n */\nexport function nextString(s) {\n  var alphabet = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ALPHABET;\n  return baseToString(stringToBase(s, alphabet) + BigInt(1), alphabet);\n}\n\n/**\n * Finds the previous string using the alphabet provided. This is done by converting the\n * string to a baseN number, where N is the alphabet's length, then subtracting 1 before\n * converting back to a string.\n * @param s - The string to start at.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The string which precedes the input string.\n */\nexport function prevString(s) {\n  var alphabet = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ALPHABET;\n  return baseToString(stringToBase(s, alphabet) - BigInt(1), alphabet);\n}\n\n/**\n * Compares strings lexicographically as a sort-safe function.\n * @param a - The first (reference) string.\n * @param b - The second (compare) string.\n * @returns Negative if the reference string is before the compare string;\n * positive if the reference string is after; and zero if equal.\n */\nexport function lexicographicCompare(a, b) {\n  // Dev note: this exists because I'm sad that you can use math operators on strings, so I've\n  // hidden the operation in this function.\n  if (a < b) {\n    return -1;\n  } else if (a > b) {\n    return 1;\n  } else {\n    return 0;\n  }\n}\n\n/**\n * This function is similar to Object.assign() but it assigns recursively and\n * allows you to ignore nullish values from the source\n *\n * @returns the target object\n */\nexport function recursivelyAssign(target, source) {\n  var ignoreNullish = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n  for (var [sourceKey, sourceValue] of Object.entries(source)) {\n    if (target[sourceKey] instanceof Object && sourceValue) {\n      recursivelyAssign(target[sourceKey], sourceValue);\n      continue;\n    }\n    if (sourceValue !== null && sourceValue !== undefined || !ignoreNullish) {\n      safeSet(target, sourceKey, sourceValue);\n      continue;\n    }\n  }\n  return target;\n}\nfunction getContentTimestampWithFallback(event) {\n  var _M_TIMESTAMP$findIn;\n  return (_M_TIMESTAMP$findIn = M_TIMESTAMP.findIn(event.getContent())) !== null && _M_TIMESTAMP$findIn !== void 0 ? _M_TIMESTAMP$findIn : -1;\n}\n\n/**\n * Sort events by their content m.ts property\n * Latest timestamp first\n */\nexport function sortEventsByLatestContentTimestamp(left, right) {\n  return getContentTimestampWithFallback(right) - getContentTimestampWithFallback(left);\n}\nexport function isSupportedReceiptType(receiptType) {\n  return [ReceiptType.Read, ReceiptType.ReadPrivate].includes(receiptType);\n}\n\n/**\n * Determines whether two maps are equal.\n * @param eq - The equivalence relation to compare values by. Defaults to strict equality.\n */\nexport function mapsEqual(x, y) {\n  var eq = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : (v1, v2) => v1 === v2;\n  if (x.size !== y.size) return false;\n  for (var [k, v1] of x) {\n    var v2 = y.get(k);\n    if (v2 === undefined || !eq(v1, v2)) return false;\n  }\n  return true;\n}\nfunction processMapToObjectValue(value) {\n  if (value instanceof Map) {\n    // Value is a Map. Recursively map it to an object.\n    return recursiveMapToObject(value);\n  } else if (Array.isArray(value)) {\n    // Value is an Array. Recursively map the value (e.g. to cover Array of Arrays).\n    return value.map(v => processMapToObjectValue(v));\n  } else {\n    return value;\n  }\n}\n\n/**\n * Recursively converts Maps to plain objects.\n * Also supports sub-lists of Maps.\n */\nexport function recursiveMapToObject(map) {\n  var targetMap = new Map();\n  for (var [key, value] of map) {\n    targetMap.set(key, processMapToObjectValue(value));\n  }\n  return Object.fromEntries(targetMap.entries());\n}\nexport function unsafeProp(prop) {\n  return prop === \"__proto__\" || prop === \"prototype\" || prop === \"constructor\";\n}\nexport function safeSet(obj, prop, value) {\n  if (unsafeProp(prop)) {\n    throw new Error(\"Trying to modify prototype or constructor\");\n  }\n  obj[prop] = value;\n}\nexport function noUnsafeEventProps(event) {\n  return !(unsafeProp(event.room_id) || unsafeProp(event.sender) || unsafeProp(event.event_id));\n}\nexport class MapWithDefault extends Map {\n  constructor(createDefault) {\n    super();\n    this.createDefault = createDefault;\n  }\n\n  /**\n   * Returns the value if the key already exists.\n   * If not, it creates a new value under that key using the ctor callback and returns it.\n   */\n  getOrCreate(key) {\n    if (!this.has(key)) {\n      this.set(key, this.createDefault());\n    }\n    return this.get(key);\n  }\n}\n//# sourceMappingURL=utils.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.NamespacedMap = void 0;\n\nfunction _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it[\"return\"] != null) it[\"return\"](); } finally { if (didErr) throw err; } } }; }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/**\n * A `Map` implementation which accepts a NamespacedValue as a key, and arbitrary value. The\n * namespaced value must be a string type.\n */\nvar NamespacedMap = /*#__PURE__*/function () {\n  // protected to make tests happy for access\n\n  /**\n   * Creates a new map with optional seed data.\n   * @param {Array<[NS, V]>} initial The seed data.\n   */\n  function NamespacedMap(initial) {\n    _classCallCheck(this, NamespacedMap);\n\n    _defineProperty(this, \"internalMap\", new Map());\n\n    if (initial) {\n      var _iterator = _createForOfIteratorHelper(initial),\n          _step;\n\n      try {\n        for (_iterator.s(); !(_step = _iterator.n()).done;) {\n          var val = _step.value;\n          this.set(val[0], val[1]);\n        }\n      } catch (err) {\n        _iterator.e(err);\n      } finally {\n        _iterator.f();\n      }\n    }\n  }\n  /**\n   * Gets a value from the map. If the value does not exist under\n   * either namespace option, falsy is returned.\n   * @param {NS} key The key.\n   * @returns {Optional<V>} The value, or falsy.\n   */\n\n\n  _createClass(NamespacedMap, [{\n    key: \"get\",\n    value: function get(key) {\n      if (key.name && this.internalMap.has(key.name)) {\n        return this.internalMap.get(key.name);\n      }\n\n      if (key.altName && this.internalMap.has(key.altName)) {\n        return this.internalMap.get(key.altName);\n      }\n\n      return null;\n    }\n    /**\n     * Sets a value in the map.\n     * @param {NS} key The key.\n     * @param {V} val The value.\n     */\n\n  }, {\n    key: \"set\",\n    value: function set(key, val) {\n      if (key.name) {\n        this.internalMap.set(key.name, val);\n      }\n\n      if (key.altName) {\n        this.internalMap.set(key.altName, val);\n      }\n    }\n    /**\n     * Determines if any of the valid namespaced values are present\n     * in the map.\n     * @param {NS} key The key.\n     * @returns {boolean} True if present.\n     */\n\n  }, {\n    key: \"has\",\n    value: function has(key) {\n      return !!this.get(key);\n    }\n    /**\n     * Removes all the namespaced values from the map.\n     * @param {NS} key The key.\n     */\n\n  }, {\n    key: \"delete\",\n    value: function _delete(key) {\n      if (key.name) {\n        this.internalMap[\"delete\"](key.name);\n      }\n\n      if (key.altName) {\n        this.internalMap[\"delete\"](key.altName);\n      }\n    }\n    /**\n     * Determines if the map contains a specific namespaced value\n     * instead of the parent NS type.\n     * @param {string} key The key.\n     * @returns {boolean} True if present.\n     */\n\n  }, {\n    key: \"hasNamespaced\",\n    value: function hasNamespaced(key) {\n      return this.internalMap.has(key);\n    }\n    /**\n     * Gets a specific namespaced value from the map instead of the\n     * parent NS type. Returns falsy if not found.\n     * @param {string} key The key.\n     * @returns {Optional<V>} The value, or falsy.\n     */\n\n  }, {\n    key: \"getNamespaced\",\n    value: function getNamespaced(key) {\n      return this.internalMap.get(key);\n    }\n  }]);\n\n  return NamespacedMap;\n}();\n\nexports.NamespacedMap = NamespacedMap;","\"use strict\";\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.InvalidEventError = void 0;\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _wrapNativeSuper(Class) { var _cache = typeof Map === \"function\" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== \"function\") { throw new TypeError(\"Super expression must either be null or a function\"); } if (typeof _cache !== \"undefined\") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }\n\nfunction _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _isNativeFunction(fn) { return Function.toString.call(fn).indexOf(\"[native code]\") !== -1; }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Thrown when an event is unforgivably unparsable.\n */\nvar InvalidEventError = /*#__PURE__*/function (_Error) {\n  _inherits(InvalidEventError, _Error);\n\n  var _super = _createSuper(InvalidEventError);\n\n  function InvalidEventError(message) {\n    _classCallCheck(this, InvalidEventError);\n\n    return _super.call(this, message);\n  }\n\n  return _createClass(InvalidEventError);\n}( /*#__PURE__*/_wrapNativeSuper(Error));\n\nexports.InvalidEventError = InvalidEventError;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.ExtensibleEvent = void 0;\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\n/*\nCopyright 2021 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Represents an Extensible Event in Matrix.\n */\nvar ExtensibleEvent = /*#__PURE__*/function () {\n  function ExtensibleEvent(wireFormat) {\n    _classCallCheck(this, ExtensibleEvent);\n\n    this.wireFormat = wireFormat;\n  }\n  /**\n   * Shortcut to wireFormat.content\n   */\n\n\n  _createClass(ExtensibleEvent, [{\n    key: \"wireContent\",\n    get: function get() {\n      return this.wireFormat.content;\n    }\n    /**\n     * Serializes the event into a format which can be used to send the\n     * event to the room.\n     * @returns {IPartialEvent<object>} The serialized event.\n     */\n\n  }]);\n\n  return ExtensibleEvent;\n}();\n\nexports.ExtensibleEvent = ExtensibleEvent;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.isOptionalAString = isOptionalAString;\nexports.isProvided = isProvided;\n\n/*\nCopyright 2021 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Represents an optional type: can either be T or a falsy value.\n */\n\n/**\n * Determines if the given optional string is a defined string.\n * @param {Optional<string>} s The input string.\n * @returns {boolean} True if the input is a defined string.\n */\nfunction isOptionalAString(s) {\n  return isProvided(s) && typeof s === 'string';\n}\n/**\n * Determines if the given optional was provided a value.\n * @param {Optional<T>} s The optional to test.\n * @returns {boolean} True if the value is defined.\n */\n\n\nfunction isProvided(s) {\n  return s !== null && s !== undefined;\n}\n/**\n * Represents either just T1, just T2, or T1 and T2 mixed.\n */","\"use strict\";\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.UnstableValue = exports.NamespacedValue = void 0;\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\n/*\nCopyright 2021 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Represents a simple Matrix namespaced value. This will assume that if a stable prefix\n * is provided that the stable prefix should be used when representing the identifier.\n */\nvar NamespacedValue = /*#__PURE__*/function () {\n  // Stable is optional, but one of the two parameters is required, hence the weird-looking types.\n  // Goal is to have developers explicitly say there is no stable value (if applicable).\n  function NamespacedValue(stable, unstable) {\n    _classCallCheck(this, NamespacedValue);\n\n    this.stable = stable;\n    this.unstable = unstable;\n\n    if (!this.unstable && !this.stable) {\n      throw new Error(\"One of stable or unstable values must be supplied\");\n    }\n  }\n\n  _createClass(NamespacedValue, [{\n    key: \"name\",\n    get: function get() {\n      if (this.stable) {\n        return this.stable;\n      }\n\n      return this.unstable;\n    }\n  }, {\n    key: \"altName\",\n    get: function get() {\n      if (!this.stable) {\n        return null;\n      }\n\n      return this.unstable;\n    }\n  }, {\n    key: \"matches\",\n    value: function matches(val) {\n      return !!this.name && this.name === val || !!this.altName && this.altName === val;\n    } // this desperately wants https://github.com/microsoft/TypeScript/pull/26349 at the top level of the class\n    // so we can instantiate `NamespacedValue<string, _, _>` as a default type for that namespace.\n\n  }, {\n    key: \"findIn\",\n    value: function findIn(obj) {\n      var val;\n\n      if (this.name) {\n        val = obj === null || obj === void 0 ? void 0 : obj[this.name];\n      }\n\n      if (!val && this.altName) {\n        val = obj === null || obj === void 0 ? void 0 : obj[this.altName];\n      }\n\n      return val;\n    }\n  }, {\n    key: \"includedIn\",\n    value: function includedIn(arr) {\n      var included = false;\n\n      if (this.name) {\n        included = arr.includes(this.name);\n      }\n\n      if (!included && this.altName) {\n        included = arr.includes(this.altName);\n      }\n\n      return included;\n    }\n  }]);\n\n  return NamespacedValue;\n}();\n/**\n * Represents a namespaced value which prioritizes the unstable value over the stable\n * value.\n */\n\n\nexports.NamespacedValue = NamespacedValue;\n\nvar UnstableValue = /*#__PURE__*/function (_NamespacedValue) {\n  _inherits(UnstableValue, _NamespacedValue);\n\n  var _super = _createSuper(UnstableValue);\n\n  // Note: Constructor difference is that `unstable` is *required*.\n  function UnstableValue(stable, unstable) {\n    var _this;\n\n    _classCallCheck(this, UnstableValue);\n\n    _this = _super.call(this, stable, unstable);\n\n    if (!_this.unstable) {\n      throw new Error(\"Unstable value must be supplied\");\n    }\n\n    return _this;\n  }\n\n  _createClass(UnstableValue, [{\n    key: \"name\",\n    get: function get() {\n      return this.unstable;\n    }\n  }, {\n    key: \"altName\",\n    get: function get() {\n      return this.stable;\n    }\n  }]);\n\n  return UnstableValue;\n}(NamespacedValue);\n\nexports.UnstableValue = UnstableValue;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.M_TEXT = exports.M_NOTICE = exports.M_MESSAGE = exports.M_HTML = exports.M_EMOTE = void 0;\n\nvar _NamespacedValue = require(\"../NamespacedValue\");\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * The namespaced value for m.message\n */\nvar M_MESSAGE = new _NamespacedValue.UnstableValue(\"m.message\", \"org.matrix.msc1767.message\");\n/**\n * An m.message event rendering\n */\n\nexports.M_MESSAGE = M_MESSAGE;\n\n/**\n * The namespaced value for m.text\n */\nvar M_TEXT = new _NamespacedValue.UnstableValue(\"m.text\", \"org.matrix.msc1767.text\");\n/**\n * The content for an m.text event\n */\n\nexports.M_TEXT = M_TEXT;\n\n/**\n * The namespaced value for m.html\n */\nvar M_HTML = new _NamespacedValue.UnstableValue(\"m.html\", \"org.matrix.msc1767.html\");\n/**\n * The content for an m.html event\n */\n\nexports.M_HTML = M_HTML;\n\n/**\n * The namespaced value for m.emote\n */\nvar M_EMOTE = new _NamespacedValue.UnstableValue(\"m.emote\", \"org.matrix.msc1767.emote\");\n/**\n * The event definition for an m.emote event (in content)\n */\n\nexports.M_EMOTE = M_EMOTE;\n\n/**\n * The namespaced value for m.notice\n */\nvar M_NOTICE = new _NamespacedValue.UnstableValue(\"m.notice\", \"org.matrix.msc1767.notice\");\n/**\n * The event definition for an m.notice event (in content)\n */\n\nexports.M_NOTICE = M_NOTICE;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.isEventTypeSame = isEventTypeSame;\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Represents a potentially namespaced event type.\n */\n\n/**\n * Determines if two event types are the same, including namespaces.\n * @param {EventType} given The given event type. This will be compared\n * against the expected type.\n * @param {EventType} expected The expected event type.\n * @returns {boolean} True if the given type matches the expected type.\n */\nfunction isEventTypeSame(given, expected) {\n  if (typeof given === \"string\") {\n    if (typeof expected === \"string\") {\n      return expected === given;\n    } else {\n      return expected.matches(given);\n    }\n  } else {\n    if (typeof expected === \"string\") {\n      return given.matches(expected);\n    } else {\n      var expectedNs = expected;\n      var givenNs = given;\n      return expectedNs.matches(givenNs.name) || expectedNs.matches(givenNs.altName);\n    }\n  }\n}","\"use strict\";\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.MessageEvent = void 0;\n\nvar _ExtensibleEvent2 = require(\"./ExtensibleEvent\");\n\nvar _types = require(\"../types\");\n\nvar _InvalidEventError = require(\"../InvalidEventError\");\n\nvar _message_types = require(\"./message_types\");\n\nvar _events = require(\"../utility/events\");\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/**\n * Represents a message event. Message events are the simplest form of event with\n * just text (optionally of different mimetypes, like HTML).\n *\n * Message events can additionally be an Emote or Notice, though typically those\n * are represented as EmoteEvent and NoticeEvent respectively.\n */\nvar MessageEvent = /*#__PURE__*/function (_ExtensibleEvent) {\n  _inherits(MessageEvent, _ExtensibleEvent);\n\n  var _super = _createSuper(MessageEvent);\n\n  /**\n   * The default text for the event.\n   */\n\n  /**\n   * The default HTML for the event, if provided.\n   */\n\n  /**\n   * All the different renderings of the message. Note that this is the same\n   * format as an m.message body but may contain elements not found directly\n   * in the event content: this is because this is interpreted based off the\n   * other information available in the event.\n   */\n\n  /**\n   * Creates a new MessageEvent from a pure format. Note that the event is\n   * *not* parsed here: it will be treated as a literal m.message primary\n   * typed event.\n   * @param {IPartialEvent<M_MESSAGE_EVENT_CONTENT>} wireFormat The event.\n   */\n  function MessageEvent(wireFormat) {\n    var _this;\n\n    _classCallCheck(this, MessageEvent);\n\n    _this = _super.call(this, wireFormat);\n\n    _defineProperty(_assertThisInitialized(_this), \"text\", void 0);\n\n    _defineProperty(_assertThisInitialized(_this), \"html\", void 0);\n\n    _defineProperty(_assertThisInitialized(_this), \"renderings\", void 0);\n\n    var mmessage = _message_types.M_MESSAGE.findIn(_this.wireContent);\n\n    var mtext = _message_types.M_TEXT.findIn(_this.wireContent);\n\n    var mhtml = _message_types.M_HTML.findIn(_this.wireContent);\n\n    if ((0, _types.isProvided)(mmessage)) {\n      if (!Array.isArray(mmessage)) {\n        throw new _InvalidEventError.InvalidEventError(\"m.message contents must be an array\");\n      }\n\n      var text = mmessage.find(function (r) {\n        return !(0, _types.isProvided)(r.mimetype) || r.mimetype === \"text/plain\";\n      });\n      var html = mmessage.find(function (r) {\n        return r.mimetype === \"text/html\";\n      });\n      if (!text) throw new _InvalidEventError.InvalidEventError(\"m.message is missing a plain text representation\");\n      _this.text = text.body;\n      _this.html = html === null || html === void 0 ? void 0 : html.body;\n      _this.renderings = mmessage;\n    } else if ((0, _types.isOptionalAString)(mtext)) {\n      _this.text = mtext;\n      _this.html = mhtml;\n      _this.renderings = [{\n        body: mtext,\n        mimetype: \"text/plain\"\n      }];\n\n      if (_this.html) {\n        _this.renderings.push({\n          body: _this.html,\n          mimetype: \"text/html\"\n        });\n      }\n    } else {\n      throw new _InvalidEventError.InvalidEventError(\"Missing textual representation for event\");\n    }\n\n    return _this;\n  }\n  /**\n   * Gets whether this message is considered an \"emote\". Note that a message\n   * might be an emote and notice at the same time: while technically possible,\n   * the event should be interpreted as one or the other.\n   */\n\n\n  _createClass(MessageEvent, [{\n    key: \"isEmote\",\n    get: function get() {\n      return _message_types.M_EMOTE.matches(this.wireFormat.type) || (0, _types.isProvided)(_message_types.M_EMOTE.findIn(this.wireFormat.content));\n    }\n    /**\n     * Gets whether this message is considered a \"notice\". Note that a message\n     * might be an emote and notice at the same time: while technically possible,\n     * the event should be interpreted as one or the other.\n     */\n\n  }, {\n    key: \"isNotice\",\n    get: function get() {\n      return _message_types.M_NOTICE.matches(this.wireFormat.type) || (0, _types.isProvided)(_message_types.M_NOTICE.findIn(this.wireFormat.content));\n    }\n  }, {\n    key: \"isEquivalentTo\",\n    value: function isEquivalentTo(primaryEventType) {\n      return (0, _events.isEventTypeSame)(primaryEventType, _message_types.M_MESSAGE);\n    }\n  }, {\n    key: \"serializeMMessageOnly\",\n    value: function serializeMMessageOnly() {\n      var messageRendering = _defineProperty({}, _message_types.M_MESSAGE.name, this.renderings); // Use the shorthand if it's just a simple text event\n\n\n      if (this.renderings.length === 1) {\n        var mime = this.renderings[0].mimetype;\n\n        if (mime === undefined || mime === \"text/plain\") {\n          messageRendering = _defineProperty({}, _message_types.M_TEXT.name, this.renderings[0].body);\n        }\n      }\n\n      return messageRendering;\n    }\n  }, {\n    key: \"serialize\",\n    value: function serialize() {\n      var _this$html;\n\n      return {\n        type: \"m.room.message\",\n        content: _objectSpread(_objectSpread({}, this.serializeMMessageOnly()), {}, {\n          body: this.text,\n          msgtype: \"m.text\",\n          format: this.html ? \"org.matrix.custom.html\" : undefined,\n          formatted_body: (_this$html = this.html) !== null && _this$html !== void 0 ? _this$html : undefined\n        })\n      };\n    }\n    /**\n     * Creates a new MessageEvent from text and HTML.\n     * @param {string} text The text.\n     * @param {string} html Optional HTML.\n     * @returns {MessageEvent} The representative message event.\n     */\n\n  }], [{\n    key: \"from\",\n    value: function from(text, html) {\n      var _content;\n\n      return new MessageEvent({\n        type: _message_types.M_MESSAGE.name,\n        content: (_content = {}, _defineProperty(_content, _message_types.M_TEXT.name, text), _defineProperty(_content, _message_types.M_HTML.name, html), _content)\n      });\n    }\n  }]);\n\n  return MessageEvent;\n}(_ExtensibleEvent2.ExtensibleEvent);\n\nexports.MessageEvent = MessageEvent;","\"use strict\";\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.NoticeEvent = void 0;\n\nvar _MessageEvent2 = require(\"./MessageEvent\");\n\nvar _message_types = require(\"./message_types\");\n\nvar _events = require(\"../utility/events\");\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _get() { if (typeof Reflect !== \"undefined\" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); }\n\nfunction _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n// Notice events are just decorated message events\n\n/**\n * Represents a notice. This is essentially a MessageEvent with\n * notice characteristics considered.\n */\nvar NoticeEvent = /*#__PURE__*/function (_MessageEvent) {\n  _inherits(NoticeEvent, _MessageEvent);\n\n  var _super = _createSuper(NoticeEvent);\n\n  function NoticeEvent(wireFormat) {\n    _classCallCheck(this, NoticeEvent);\n\n    return _super.call(this, wireFormat);\n  }\n\n  _createClass(NoticeEvent, [{\n    key: \"isNotice\",\n    get: function get() {\n      return true; // override\n    }\n  }, {\n    key: \"isEquivalentTo\",\n    value: function isEquivalentTo(primaryEventType) {\n      return (0, _events.isEventTypeSame)(primaryEventType, _message_types.M_NOTICE) || _get(_getPrototypeOf(NoticeEvent.prototype), \"isEquivalentTo\", this).call(this, primaryEventType);\n    }\n  }, {\n    key: \"serialize\",\n    value: function serialize() {\n      var message = _get(_getPrototypeOf(NoticeEvent.prototype), \"serialize\", this).call(this);\n\n      message.content['msgtype'] = \"m.notice\";\n      return message;\n    }\n    /**\n     * Creates a new NoticeEvent from text and HTML.\n     * @param {string} text The text.\n     * @param {string} html Optional HTML.\n     * @returns {MessageEvent} The representative message event.\n     */\n\n  }], [{\n    key: \"from\",\n    value: function from(text, html) {\n      var _content;\n\n      return new NoticeEvent({\n        type: _message_types.M_NOTICE.name,\n        content: (_content = {}, _defineProperty(_content, _message_types.M_TEXT.name, text), _defineProperty(_content, _message_types.M_HTML.name, html), _content)\n      });\n    }\n  }]);\n\n  return NoticeEvent;\n}(_MessageEvent2.MessageEvent);\n\nexports.NoticeEvent = NoticeEvent;","\"use strict\";\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.EmoteEvent = void 0;\n\nvar _MessageEvent2 = require(\"./MessageEvent\");\n\nvar _message_types = require(\"./message_types\");\n\nvar _events = require(\"../utility/events\");\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _get() { if (typeof Reflect !== \"undefined\" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); }\n\nfunction _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n// Emote events are just decorated message events\n\n/**\n * Represents an emote. This is essentially a MessageEvent with\n * emote characteristics considered.\n */\nvar EmoteEvent = /*#__PURE__*/function (_MessageEvent) {\n  _inherits(EmoteEvent, _MessageEvent);\n\n  var _super = _createSuper(EmoteEvent);\n\n  function EmoteEvent(wireFormat) {\n    _classCallCheck(this, EmoteEvent);\n\n    return _super.call(this, wireFormat);\n  }\n\n  _createClass(EmoteEvent, [{\n    key: \"isEmote\",\n    get: function get() {\n      return true; // override\n    }\n  }, {\n    key: \"isEquivalentTo\",\n    value: function isEquivalentTo(primaryEventType) {\n      return (0, _events.isEventTypeSame)(primaryEventType, _message_types.M_EMOTE) || _get(_getPrototypeOf(EmoteEvent.prototype), \"isEquivalentTo\", this).call(this, primaryEventType);\n    }\n  }, {\n    key: \"serialize\",\n    value: function serialize() {\n      var message = _get(_getPrototypeOf(EmoteEvent.prototype), \"serialize\", this).call(this);\n\n      message.content['msgtype'] = \"m.emote\";\n      return message;\n    }\n    /**\n     * Creates a new EmoteEvent from text and HTML.\n     * @param {string} text The text.\n     * @param {string} html Optional HTML.\n     * @returns {MessageEvent} The representative message event.\n     */\n\n  }], [{\n    key: \"from\",\n    value: function from(text, html) {\n      var _content;\n\n      return new EmoteEvent({\n        type: _message_types.M_EMOTE.name,\n        content: (_content = {}, _defineProperty(_content, _message_types.M_TEXT.name, text), _defineProperty(_content, _message_types.M_HTML.name, html), _content)\n      });\n    }\n  }]);\n\n  return EmoteEvent;\n}(_MessageEvent2.MessageEvent);\n\nexports.EmoteEvent = EmoteEvent;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.LEGACY_M_ROOM_MESSAGE = void 0;\nexports.parseMRoomMessage = parseMRoomMessage;\n\nvar _MessageEvent = require(\"../../events/MessageEvent\");\n\nvar _NoticeEvent = require(\"../../events/NoticeEvent\");\n\nvar _EmoteEvent = require(\"../../events/EmoteEvent\");\n\nvar _NamespacedValue = require(\"../../NamespacedValue\");\n\nvar _message_types = require(\"../../events/message_types\");\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar LEGACY_M_ROOM_MESSAGE = new _NamespacedValue.NamespacedValue(\"m.room.message\");\nexports.LEGACY_M_ROOM_MESSAGE = LEGACY_M_ROOM_MESSAGE;\n\nfunction parseMRoomMessage(wireEvent) {\n  var _wireEvent$content, _wireEvent$content2, _wireEvent$content3;\n\n  if (_message_types.M_MESSAGE.findIn(wireEvent.content) || _message_types.M_TEXT.findIn(wireEvent.content)) {\n    // We know enough about the event to coerce it into the right type\n    return new _MessageEvent.MessageEvent(wireEvent);\n  }\n\n  var msgtype = (_wireEvent$content = wireEvent.content) === null || _wireEvent$content === void 0 ? void 0 : _wireEvent$content.msgtype;\n  var text = (_wireEvent$content2 = wireEvent.content) === null || _wireEvent$content2 === void 0 ? void 0 : _wireEvent$content2.body;\n  var html = ((_wireEvent$content3 = wireEvent.content) === null || _wireEvent$content3 === void 0 ? void 0 : _wireEvent$content3.format) === \"org.matrix.custom.html\" ? wireEvent.content.formatted_body : null;\n\n  if (msgtype === \"m.text\") {\n    var _objectSpread2;\n\n    return new _MessageEvent.MessageEvent(_objectSpread(_objectSpread({}, wireEvent), {}, {\n      content: _objectSpread(_objectSpread({}, wireEvent.content), {}, (_objectSpread2 = {}, _defineProperty(_objectSpread2, _message_types.M_TEXT.name, text), _defineProperty(_objectSpread2, _message_types.M_HTML.name, html), _objectSpread2))\n    }));\n  } else if (msgtype === \"m.notice\") {\n    var _objectSpread3;\n\n    return new _NoticeEvent.NoticeEvent(_objectSpread(_objectSpread({}, wireEvent), {}, {\n      content: _objectSpread(_objectSpread({}, wireEvent.content), {}, (_objectSpread3 = {}, _defineProperty(_objectSpread3, _message_types.M_TEXT.name, text), _defineProperty(_objectSpread3, _message_types.M_HTML.name, html), _objectSpread3))\n    }));\n  } else if (msgtype === \"m.emote\") {\n    var _objectSpread4;\n\n    return new _EmoteEvent.EmoteEvent(_objectSpread(_objectSpread({}, wireEvent), {}, {\n      content: _objectSpread(_objectSpread({}, wireEvent.content), {}, (_objectSpread4 = {}, _defineProperty(_objectSpread4, _message_types.M_TEXT.name, text), _defineProperty(_objectSpread4, _message_types.M_HTML.name, html), _objectSpread4))\n    }));\n  } else {\n    // TODO: Handle other types\n    return null;\n  }\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.parseMMessage = parseMMessage;\n\nvar _MessageEvent = require(\"../../events/MessageEvent\");\n\nvar _message_types = require(\"../../events/message_types\");\n\nvar _EmoteEvent = require(\"../../events/EmoteEvent\");\n\nvar _NoticeEvent = require(\"../../events/NoticeEvent\");\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nfunction parseMMessage(wireEvent) {\n  if (_message_types.M_EMOTE.matches(wireEvent.type)) {\n    return new _EmoteEvent.EmoteEvent(wireEvent);\n  } else if (_message_types.M_NOTICE.matches(wireEvent.type)) {\n    return new _NoticeEvent.NoticeEvent(wireEvent);\n  } // default: return a generic message\n\n\n  return new _MessageEvent.MessageEvent(wireEvent);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.M_POLL_START = exports.M_POLL_RESPONSE = exports.M_POLL_KIND_UNDISCLOSED = exports.M_POLL_KIND_DISCLOSED = exports.M_POLL_END = void 0;\n\nvar _NamespacedValue = require(\"../NamespacedValue\");\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Identifier for a disclosed poll.\n */\nvar M_POLL_KIND_DISCLOSED = new _NamespacedValue.UnstableValue(\"m.poll.disclosed\", \"org.matrix.msc3381.poll.disclosed\");\n/**\n * Identifier for an undisclosed poll.\n */\n\nexports.M_POLL_KIND_DISCLOSED = M_POLL_KIND_DISCLOSED;\nvar M_POLL_KIND_UNDISCLOSED = new _NamespacedValue.UnstableValue(\"m.poll.undisclosed\", \"org.matrix.msc3381.poll.undisclosed\");\n/**\n * Any poll kind.\n */\n\nexports.M_POLL_KIND_UNDISCLOSED = M_POLL_KIND_UNDISCLOSED;\n\n/**\n * The namespaced value for m.poll.start\n */\nvar M_POLL_START = new _NamespacedValue.UnstableValue(\"m.poll.start\", \"org.matrix.msc3381.poll.start\");\n/**\n * The m.poll.start type within event content\n */\n\nexports.M_POLL_START = M_POLL_START;\n\n/**\n * The namespaced value for m.poll.response\n */\nvar M_POLL_RESPONSE = new _NamespacedValue.UnstableValue(\"m.poll.response\", \"org.matrix.msc3381.poll.response\");\n/**\n * The m.poll.response type within event content\n */\n\nexports.M_POLL_RESPONSE = M_POLL_RESPONSE;\n\n/**\n * The namespaced value for m.poll.end\n */\nvar M_POLL_END = new _NamespacedValue.UnstableValue(\"m.poll.end\", \"org.matrix.msc3381.poll.end\");\n/**\n * The event definition for an m.poll.end event (in content)\n */\n\nexports.M_POLL_END = M_POLL_END;","\"use strict\";\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.PollStartEvent = exports.PollAnswerSubevent = void 0;\n\nvar _poll_types = require(\"./poll_types\");\n\nvar _MessageEvent2 = require(\"./MessageEvent\");\n\nvar _message_types = require(\"./message_types\");\n\nvar _InvalidEventError = require(\"../InvalidEventError\");\n\nvar _NamespacedValue = require(\"../NamespacedValue\");\n\nvar _events = require(\"../utility/events\");\n\nvar _ExtensibleEvent2 = require(\"./ExtensibleEvent\");\n\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/**\n * Represents a poll answer. Note that this is represented as a subtype and is\n * not registered as a parsable event - it is implied for usage exclusively\n * within the PollStartEvent parsing.\n */\nvar PollAnswerSubevent = /*#__PURE__*/function (_MessageEvent) {\n  _inherits(PollAnswerSubevent, _MessageEvent);\n\n  var _super = _createSuper(PollAnswerSubevent);\n\n  /**\n   * The answer ID.\n   */\n  function PollAnswerSubevent(wireFormat) {\n    var _this;\n\n    _classCallCheck(this, PollAnswerSubevent);\n\n    _this = _super.call(this, wireFormat);\n\n    _defineProperty(_assertThisInitialized(_this), \"id\", void 0);\n\n    var id = wireFormat.content.id;\n\n    if (!id || typeof id !== \"string\") {\n      throw new _InvalidEventError.InvalidEventError(\"Answer ID must be a non-empty string\");\n    }\n\n    _this.id = id;\n    return _this;\n  }\n\n  _createClass(PollAnswerSubevent, [{\n    key: \"serialize\",\n    value: function serialize() {\n      return {\n        type: \"org.matrix.sdk.poll.answer\",\n        content: _objectSpread({\n          id: this.id\n        }, this.serializeMMessageOnly())\n      };\n    }\n    /**\n     * Creates a new PollAnswerSubevent from ID and text.\n     * @param {string} id The answer ID (unique within the poll).\n     * @param {string} text The text.\n     * @returns {PollAnswerSubevent} The representative answer.\n     */\n\n  }], [{\n    key: \"from\",\n    value: function from(id, text) {\n      return new PollAnswerSubevent({\n        type: \"org.matrix.sdk.poll.answer\",\n        content: _defineProperty({\n          id: id\n        }, _message_types.M_TEXT.name, text)\n      });\n    }\n  }]);\n\n  return PollAnswerSubevent;\n}(_MessageEvent2.MessageEvent);\n/**\n * Represents a poll start event.\n */\n\n\nexports.PollAnswerSubevent = PollAnswerSubevent;\n\nvar PollStartEvent = /*#__PURE__*/function (_ExtensibleEvent) {\n  _inherits(PollStartEvent, _ExtensibleEvent);\n\n  var _super2 = _createSuper(PollStartEvent);\n\n  /**\n   * The question being asked, as a MessageEvent node.\n   */\n\n  /**\n   * The interpreted kind of poll. Note that this will infer a value that is known to the\n   * SDK rather than verbatim - this means unknown types will be represented as undisclosed\n   * polls.\n   *\n   * To get the raw kind, use rawKind.\n   */\n\n  /**\n   * The true kind as provided by the event sender. Might not be valid.\n   */\n\n  /**\n   * The maximum number of selections a user is allowed to make.\n   */\n\n  /**\n   * The possible answers for the poll.\n   */\n\n  /**\n   * Creates a new PollStartEvent from a pure format. Note that the event is *not*\n   * parsed here: it will be treated as a literal m.poll.start primary typed event.\n   * @param {IPartialEvent<M_POLL_START_EVENT_CONTENT>} wireFormat The event.\n   */\n  function PollStartEvent(wireFormat) {\n    var _this2;\n\n    _classCallCheck(this, PollStartEvent);\n\n    _this2 = _super2.call(this, wireFormat);\n\n    _defineProperty(_assertThisInitialized(_this2), \"question\", void 0);\n\n    _defineProperty(_assertThisInitialized(_this2), \"kind\", void 0);\n\n    _defineProperty(_assertThisInitialized(_this2), \"rawKind\", void 0);\n\n    _defineProperty(_assertThisInitialized(_this2), \"maxSelections\", void 0);\n\n    _defineProperty(_assertThisInitialized(_this2), \"answers\", void 0);\n\n    var poll = _poll_types.M_POLL_START.findIn(_this2.wireContent);\n\n    if (!poll.question) {\n      throw new _InvalidEventError.InvalidEventError(\"A question is required\");\n    }\n\n    _this2.question = new _MessageEvent2.MessageEvent({\n      type: \"org.matrix.sdk.poll.question\",\n      content: poll.question\n    });\n    _this2.rawKind = poll.kind;\n\n    if (_poll_types.M_POLL_KIND_DISCLOSED.matches(_this2.rawKind)) {\n      _this2.kind = _poll_types.M_POLL_KIND_DISCLOSED;\n    } else {\n      _this2.kind = _poll_types.M_POLL_KIND_UNDISCLOSED; // default & assumed value\n    }\n\n    _this2.maxSelections = Number.isFinite(poll.max_selections) && poll.max_selections > 0 ? poll.max_selections : 1;\n\n    if (!Array.isArray(poll.answers)) {\n      throw new _InvalidEventError.InvalidEventError(\"Poll answers must be an array\");\n    }\n\n    var answers = poll.answers.slice(0, 20).map(function (a) {\n      return new PollAnswerSubevent({\n        type: \"org.matrix.sdk.poll.answer\",\n        content: a\n      });\n    });\n\n    if (answers.length <= 0) {\n      throw new _InvalidEventError.InvalidEventError(\"No answers available\");\n    }\n\n    _this2.answers = answers;\n    return _this2;\n  }\n\n  _createClass(PollStartEvent, [{\n    key: \"isEquivalentTo\",\n    value: function isEquivalentTo(primaryEventType) {\n      return (0, _events.isEventTypeSame)(primaryEventType, _poll_types.M_POLL_START);\n    }\n  }, {\n    key: \"serialize\",\n    value: function serialize() {\n      var _content2;\n\n      return {\n        type: _poll_types.M_POLL_START.name,\n        content: (_content2 = {}, _defineProperty(_content2, _poll_types.M_POLL_START.name, {\n          question: this.question.serialize().content,\n          kind: this.rawKind,\n          max_selections: this.maxSelections,\n          answers: this.answers.map(function (a) {\n            return a.serialize().content;\n          })\n        }), _defineProperty(_content2, _message_types.M_TEXT.name, \"\".concat(this.question.text, \"\\n\").concat(this.answers.map(function (a, i) {\n          return \"\".concat(i + 1, \". \").concat(a.text);\n        }).join(\"\\n\"))), _content2)\n      };\n    }\n    /**\n     * Creates a new PollStartEvent from question, answers, and metadata.\n     * @param {string} question The question to ask.\n     * @param {string} answers The answers. Should be unique within each other.\n     * @param {KNOWN_POLL_KIND|string} kind The kind of poll.\n     * @param {number} maxSelections The maximum number of selections. Must be 1 or higher.\n     * @returns {PollStartEvent} The representative poll start event.\n     */\n\n  }], [{\n    key: \"from\",\n    value: function from(question, answers, kind) {\n      var _content3;\n\n      var maxSelections = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;\n      return new PollStartEvent({\n        type: _poll_types.M_POLL_START.name,\n        content: (_content3 = {}, _defineProperty(_content3, _message_types.M_TEXT.name, question), _defineProperty(_content3, _poll_types.M_POLL_START.name, {\n          question: _defineProperty({}, _message_types.M_TEXT.name, question),\n          kind: kind instanceof _NamespacedValue.NamespacedValue ? kind.name : kind,\n          max_selections: maxSelections,\n          answers: answers.map(function (a) {\n            return _defineProperty({\n              id: makeId()\n            }, _message_types.M_TEXT.name, a);\n          })\n        }), _content3)\n      });\n    }\n  }]);\n\n  return PollStartEvent;\n}(_ExtensibleEvent2.ExtensibleEvent);\n\nexports.PollStartEvent = PollStartEvent;\nvar LETTERS = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n\nfunction makeId() {\n  return _toConsumableArray(Array(16)).map(function () {\n    return LETTERS.charAt(Math.floor(Math.random() * LETTERS.length));\n  }).join('');\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.REFERENCE_RELATION = void 0;\n\nvar _NamespacedValue = require(\"../NamespacedValue\");\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * The namespaced value for an m.reference relation\n */\nvar REFERENCE_RELATION = new _NamespacedValue.NamespacedValue(\"m.reference\");\n/**\n * Represents any relation type\n */\n\nexports.REFERENCE_RELATION = REFERENCE_RELATION;","\"use strict\";\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.PollResponseEvent = void 0;\n\nvar _ExtensibleEvent2 = require(\"./ExtensibleEvent\");\n\nvar _poll_types = require(\"./poll_types\");\n\nvar _InvalidEventError = require(\"../InvalidEventError\");\n\nvar _relationship_types = require(\"./relationship_types\");\n\nvar _events = require(\"../utility/events\");\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/**\n * Represents a poll response event.\n */\nvar PollResponseEvent = /*#__PURE__*/function (_ExtensibleEvent) {\n  _inherits(PollResponseEvent, _ExtensibleEvent);\n\n  var _super = _createSuper(PollResponseEvent);\n\n  /**\n   * Creates a new PollResponseEvent from a pure format. Note that the event is *not*\n   * parsed here: it will be treated as a literal m.poll.response primary typed event.\n   *\n   * To validate the response against a poll, call `validateAgainst` after creation.\n   * @param {IPartialEvent<M_POLL_RESPONSE_EVENT_CONTENT>} wireFormat The event.\n   */\n  function PollResponseEvent(wireFormat) {\n    var _this;\n\n    _classCallCheck(this, PollResponseEvent);\n\n    _this = _super.call(this, wireFormat);\n\n    _defineProperty(_assertThisInitialized(_this), \"internalAnswerIds\", void 0);\n\n    _defineProperty(_assertThisInitialized(_this), \"internalSpoiled\", void 0);\n\n    _defineProperty(_assertThisInitialized(_this), \"pollEventId\", void 0);\n\n    var rel = _this.wireContent[\"m.relates_to\"];\n\n    if (!_relationship_types.REFERENCE_RELATION.matches(rel === null || rel === void 0 ? void 0 : rel.rel_type) || typeof (rel === null || rel === void 0 ? void 0 : rel.event_id) !== \"string\") {\n      throw new _InvalidEventError.InvalidEventError(\"Relationship must be a reference to an event\");\n    }\n\n    _this.pollEventId = rel.event_id;\n\n    _this.validateAgainst(null);\n\n    return _this;\n  }\n  /**\n   * Validates the poll response using the poll start event as a frame of reference. This\n   * is used to determine if the vote is spoiled, whether the answers are valid, etc.\n   * @param {PollStartEvent} poll The poll start event.\n   */\n\n\n  _createClass(PollResponseEvent, [{\n    key: \"answerIds\",\n    get:\n    /**\n     * The provided answers for the poll. Note that this may be falsy/unpredictable if\n     * the `spoiled` property is true.\n     */\n    function get() {\n      return this.internalAnswerIds;\n    }\n    /**\n     * The poll start event ID referenced by the response.\n     */\n\n  }, {\n    key: \"spoiled\",\n    get:\n    /**\n     * Whether the vote is spoiled.\n     */\n    function get() {\n      return this.internalSpoiled;\n    }\n  }, {\n    key: \"validateAgainst\",\n    value: function validateAgainst(poll) {\n      var response = _poll_types.M_POLL_RESPONSE.findIn(this.wireContent);\n\n      if (!Array.isArray(response === null || response === void 0 ? void 0 : response.answers)) {\n        this.internalSpoiled = true;\n        this.internalAnswerIds = [];\n        return;\n      }\n\n      var answers = response.answers;\n\n      if (answers.some(function (a) {\n        return typeof a !== \"string\";\n      }) || answers.length === 0) {\n        this.internalSpoiled = true;\n        this.internalAnswerIds = [];\n        return;\n      }\n\n      if (poll) {\n        if (answers.some(function (a) {\n          return !poll.answers.some(function (pa) {\n            return pa.id === a;\n          });\n        })) {\n          this.internalSpoiled = true;\n          this.internalAnswerIds = [];\n          return;\n        }\n\n        answers = answers.slice(0, poll.maxSelections);\n      }\n\n      this.internalAnswerIds = answers;\n      this.internalSpoiled = false;\n    }\n  }, {\n    key: \"isEquivalentTo\",\n    value: function isEquivalentTo(primaryEventType) {\n      return (0, _events.isEventTypeSame)(primaryEventType, _poll_types.M_POLL_RESPONSE);\n    }\n  }, {\n    key: \"serialize\",\n    value: function serialize() {\n      return {\n        type: _poll_types.M_POLL_RESPONSE.name,\n        content: _defineProperty({\n          \"m.relates_to\": {\n            rel_type: _relationship_types.REFERENCE_RELATION.name,\n            event_id: this.pollEventId\n          }\n        }, _poll_types.M_POLL_RESPONSE.name, {\n          answers: this.spoiled ? undefined : this.answerIds\n        })\n      };\n    }\n    /**\n     * Creates a new PollResponseEvent from a set of answers. To spoil the vote, pass an empty\n     * answers array.\n     * @param {string} answers The user's answers. Should be valid from a poll's answer IDs.\n     * @param {string} pollEventId The poll start event ID.\n     * @returns {PollStartEvent} The representative poll response event.\n     */\n\n  }], [{\n    key: \"from\",\n    value: function from(answers, pollEventId) {\n      return new PollResponseEvent({\n        type: _poll_types.M_POLL_RESPONSE.name,\n        content: _defineProperty({\n          \"m.relates_to\": {\n            rel_type: _relationship_types.REFERENCE_RELATION.name,\n            event_id: pollEventId\n          }\n        }, _poll_types.M_POLL_RESPONSE.name, {\n          answers: answers\n        })\n      });\n    }\n  }]);\n\n  return PollResponseEvent;\n}(_ExtensibleEvent2.ExtensibleEvent);\n\nexports.PollResponseEvent = PollResponseEvent;","\"use strict\";\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.PollEndEvent = void 0;\n\nvar _poll_types = require(\"./poll_types\");\n\nvar _InvalidEventError = require(\"../InvalidEventError\");\n\nvar _relationship_types = require(\"./relationship_types\");\n\nvar _MessageEvent = require(\"./MessageEvent\");\n\nvar _message_types = require(\"./message_types\");\n\nvar _events = require(\"../utility/events\");\n\nvar _ExtensibleEvent2 = require(\"./ExtensibleEvent\");\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/**\n * Represents a poll end/closure event.\n */\nvar PollEndEvent = /*#__PURE__*/function (_ExtensibleEvent) {\n  _inherits(PollEndEvent, _ExtensibleEvent);\n\n  var _super = _createSuper(PollEndEvent);\n\n  /**\n   * The poll start event ID referenced by the response.\n   */\n\n  /**\n   * The closing message for the event.\n   */\n\n  /**\n   * Creates a new PollEndEvent from a pure format. Note that the event is *not*\n   * parsed here: it will be treated as a literal m.poll.response primary typed event.\n   * @param {IPartialEvent<M_POLL_END_EVENT_CONTENT>} wireFormat The event.\n   */\n  function PollEndEvent(wireFormat) {\n    var _this;\n\n    _classCallCheck(this, PollEndEvent);\n\n    _this = _super.call(this, wireFormat);\n\n    _defineProperty(_assertThisInitialized(_this), \"pollEventId\", void 0);\n\n    _defineProperty(_assertThisInitialized(_this), \"closingMessage\", void 0);\n\n    var rel = _this.wireContent[\"m.relates_to\"];\n\n    if (!_relationship_types.REFERENCE_RELATION.matches(rel === null || rel === void 0 ? void 0 : rel.rel_type) || typeof (rel === null || rel === void 0 ? void 0 : rel.event_id) !== \"string\") {\n      throw new _InvalidEventError.InvalidEventError(\"Relationship must be a reference to an event\");\n    }\n\n    _this.pollEventId = rel.event_id;\n    _this.closingMessage = new _MessageEvent.MessageEvent(_this.wireFormat);\n    return _this;\n  }\n\n  _createClass(PollEndEvent, [{\n    key: \"isEquivalentTo\",\n    value: function isEquivalentTo(primaryEventType) {\n      return (0, _events.isEventTypeSame)(primaryEventType, _poll_types.M_POLL_END);\n    }\n  }, {\n    key: \"serialize\",\n    value: function serialize() {\n      return {\n        type: _poll_types.M_POLL_END.name,\n        content: _objectSpread(_defineProperty({\n          \"m.relates_to\": {\n            rel_type: _relationship_types.REFERENCE_RELATION.name,\n            event_id: this.pollEventId\n          }\n        }, _poll_types.M_POLL_END.name, {}), this.closingMessage.serialize().content)\n      };\n    }\n    /**\n     * Creates a new PollEndEvent from a poll event ID.\n     * @param {string} pollEventId The poll start event ID.\n     * @param {string} message A closing message, typically revealing the top answer.\n     * @returns {PollStartEvent} The representative poll closure event.\n     */\n\n  }], [{\n    key: \"from\",\n    value: function from(pollEventId, message) {\n      var _content;\n\n      return new PollEndEvent({\n        type: _poll_types.M_POLL_END.name,\n        content: (_content = {\n          \"m.relates_to\": {\n            rel_type: _relationship_types.REFERENCE_RELATION.name,\n            event_id: pollEventId\n          }\n        }, _defineProperty(_content, _poll_types.M_POLL_END.name, {}), _defineProperty(_content, _message_types.M_TEXT.name, message), _content)\n      });\n    }\n  }]);\n\n  return PollEndEvent;\n}(_ExtensibleEvent2.ExtensibleEvent);\n\nexports.PollEndEvent = PollEndEvent;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.parseMPoll = parseMPoll;\n\nvar _poll_types = require(\"../../events/poll_types\");\n\nvar _PollStartEvent = require(\"../../events/PollStartEvent\");\n\nvar _PollResponseEvent = require(\"../../events/PollResponseEvent\");\n\nvar _PollEndEvent = require(\"../../events/PollEndEvent\");\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nfunction parseMPoll(wireEvent) {\n  if (_poll_types.M_POLL_START.matches(wireEvent.type)) {\n    return new _PollStartEvent.PollStartEvent(wireEvent);\n  } else if (_poll_types.M_POLL_RESPONSE.matches(wireEvent.type)) {\n    return new _PollResponseEvent.PollResponseEvent(wireEvent);\n  } else if (_poll_types.M_POLL_END.matches(wireEvent.type)) {\n    return new _PollEndEvent.PollEndEvent(wireEvent);\n  }\n\n  return null; // not a poll event\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.ExtensibleEvents = void 0;\n\nvar _NamespacedMap = require(\"./NamespacedMap\");\n\nvar _InvalidEventError = require(\"./InvalidEventError\");\n\nvar _MRoomMessage = require(\"./interpreters/legacy/MRoomMessage\");\n\nvar _MMessage = require(\"./interpreters/modern/MMessage\");\n\nvar _message_types = require(\"./events/message_types\");\n\nvar _poll_types = require(\"./events/poll_types\");\n\nvar _MPoll = require(\"./interpreters/modern/MPoll\");\n\nfunction _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it[\"return\"] != null) it[\"return\"](); } finally { if (didErr) throw err; } } }; }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/**\n * Utility class for parsing and identifying event types in a renderable form. An\n * instance of this class can be created to change rendering preference depending\n * on use-case.\n */\nvar ExtensibleEvents = /*#__PURE__*/function () {\n  function ExtensibleEvents() {\n    _classCallCheck(this, ExtensibleEvents);\n\n    _defineProperty(this, \"interpreters\", new _NamespacedMap.NamespacedMap([// Remember to add your unit test when adding to this! (\"known events\" test description)\n    [_MRoomMessage.LEGACY_M_ROOM_MESSAGE, _MRoomMessage.parseMRoomMessage], [_message_types.M_MESSAGE, _MMessage.parseMMessage], [_message_types.M_EMOTE, _MMessage.parseMMessage], [_message_types.M_NOTICE, _MMessage.parseMMessage], [_poll_types.M_POLL_START, _MPoll.parseMPoll], [_poll_types.M_POLL_RESPONSE, _MPoll.parseMPoll], [_poll_types.M_POLL_END, _MPoll.parseMPoll]]));\n\n    _defineProperty(this, \"_unknownInterpretOrder\", [_message_types.M_MESSAGE]);\n  }\n  /**\n   * Gets the default instance for all extensible event parsing.\n   */\n\n\n  _createClass(ExtensibleEvents, [{\n    key: \"unknownInterpretOrder\",\n    get:\n    /**\n     * Gets the order the internal processor will use for unknown primary\n     * event types.\n     */\n    function get() {\n      var _this$_unknownInterpr;\n\n      return (_this$_unknownInterpr = this._unknownInterpretOrder) !== null && _this$_unknownInterpr !== void 0 ? _this$_unknownInterpr : [];\n    }\n    /**\n     * Sets the order the internal processor will use for unknown primary\n     * event types.\n     * @param {NamespacedValue<string, string>[]} val The parsing order.\n     */\n    ,\n    set: function set(val) {\n      this._unknownInterpretOrder = val;\n    }\n    /**\n     * Gets the order the internal processor will use for unknown primary\n     * event types.\n     */\n\n  }, {\n    key: \"registerInterpreter\",\n    value:\n    /**\n     * Registers a primary event type interpreter. Note that the interpreter might be\n     * called with non-primary events if the event is being parsed as a fallback.\n     * @param {NamespacedValue<string, string>} wireEventType The event type.\n     * @param {EventInterpreter} interpreter The interpreter.\n     */\n    function registerInterpreter(wireEventType, interpreter) {\n      this.interpreters.set(wireEventType, interpreter);\n    }\n    /**\n     * Registers a primary event type interpreter. Note that the interpreter might be\n     * called with non-primary events if the event is being parsed as a fallback.\n     * @param {NamespacedValue<string, string>} wireEventType The event type.\n     * @param {EventInterpreter} interpreter The interpreter.\n     */\n\n  }, {\n    key: \"parse\",\n    value:\n    /**\n     * Parses an event, trying the primary event type first. If the primary type is not known\n     * then the content will be inspected to find the most suitable fallback.\n     *\n     * If the parsing failed or was a completely unknown type, this will return falsy.\n     * @param {IPartialEvent<object>} wireFormat The event to parse.\n     * @returns {Optional<ExtensibleEvent>} The parsed extensible event.\n     */\n    function parse(wireFormat) {\n      try {\n        if (this.interpreters.hasNamespaced(wireFormat.type)) {\n          return this.interpreters.getNamespaced(wireFormat.type)(wireFormat);\n        }\n\n        var _iterator = _createForOfIteratorHelper(this.unknownInterpretOrder),\n            _step;\n\n        try {\n          for (_iterator.s(); !(_step = _iterator.n()).done;) {\n            var tryType = _step.value;\n\n            if (this.interpreters.has(tryType)) {\n              var val = this.interpreters.get(tryType)(wireFormat);\n              if (val) return val;\n            }\n          }\n        } catch (err) {\n          _iterator.e(err);\n        } finally {\n          _iterator.f();\n        }\n\n        return null; // cannot be parsed\n      } catch (e) {\n        if (e instanceof _InvalidEventError.InvalidEventError) {\n          return null; // fail parsing and move on\n        }\n\n        throw e; // re-throw everything else\n      }\n    }\n    /**\n     * Parses an event, trying the primary event type first. If the primary type is not known\n     * then the content will be inspected to find the most suitable fallback.\n     *\n     * If the parsing failed or was a completely unknown type, this will return falsy.\n     * @param {IPartialEvent<object>} wireFormat The event to parse.\n     * @returns {Optional<ExtensibleEvent>} The parsed extensible event.\n     */\n\n  }], [{\n    key: \"defaultInstance\",\n    get: function get() {\n      return ExtensibleEvents._defaultInstance;\n    }\n  }, {\n    key: \"unknownInterpretOrder\",\n    get: function get() {\n      return ExtensibleEvents.defaultInstance.unknownInterpretOrder;\n    }\n    /**\n     * Sets the order the internal processor will use for unknown primary\n     * event types.\n     * @param {NamespacedValue<string, string>[]} val The parsing order.\n     */\n    ,\n    set: function set(val) {\n      ExtensibleEvents.defaultInstance.unknownInterpretOrder = val;\n    }\n  }, {\n    key: \"registerInterpreter\",\n    value: function registerInterpreter(wireEventType, interpreter) {\n      ExtensibleEvents.defaultInstance.registerInterpreter(wireEventType, interpreter);\n    }\n  }, {\n    key: \"parse\",\n    value: function parse(wireFormat) {\n      return ExtensibleEvents.defaultInstance.parse(wireFormat);\n    }\n  }]);\n\n  return ExtensibleEvents;\n}();\n\nexports.ExtensibleEvents = ExtensibleEvents;\n\n_defineProperty(ExtensibleEvents, \"_defaultInstance\", new ExtensibleEvents());","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.LegacyMsgType = void 0;\nexports.isEventLike = isEventLike;\n\nvar _message_types = require(\"../events/message_types\");\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Represents a legacy m.room.message msgtype\n */\nvar LegacyMsgType;\n/**\n * Determines if the given partial event looks similar enough to the given legacy msgtype\n * to count as that message type.\n * @param {IPartialEvent<EitherAnd<IPartialLegacyContent, M_MESSAGE_EVENT_CONTENT>>} event The event.\n * @param {LegacyMsgType} msgtype The message type to compare for.\n * @returns {boolean} True if the event appears to look similar enough to the msgtype.\n */\n\nexports.LegacyMsgType = LegacyMsgType;\n\n(function (LegacyMsgType) {\n  LegacyMsgType[\"Text\"] = \"m.text\";\n  LegacyMsgType[\"Notice\"] = \"m.notice\";\n  LegacyMsgType[\"Emote\"] = \"m.emote\";\n})(LegacyMsgType || (exports.LegacyMsgType = LegacyMsgType = {}));\n\nfunction isEventLike(event, msgtype) {\n  var content = event.content;\n\n  if (msgtype === LegacyMsgType.Text) {\n    return _message_types.M_MESSAGE.matches(event.type) || event.type === \"m.room.message\" && (content === null || content === void 0 ? void 0 : content['msgtype']) === \"m.text\";\n  } else if (msgtype === LegacyMsgType.Emote) {\n    return _message_types.M_EMOTE.matches(event.type) || event.type === \"m.room.message\" && (content === null || content === void 0 ? void 0 : content['msgtype']) === \"m.emote\";\n  } else if (msgtype === LegacyMsgType.Notice) {\n    return _message_types.M_NOTICE.matches(event.type) || event.type === \"m.room.message\" && (content === null || content === void 0 ? void 0 : content['msgtype']) === \"m.notice\";\n  }\n\n  return false;\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\n\nvar _ExtensibleEvents = require(\"./ExtensibleEvents\");\n\nObject.keys(_ExtensibleEvents).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _ExtensibleEvents[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _ExtensibleEvents[key];\n    }\n  });\n});\n\nvar _IPartialEvent = require(\"./IPartialEvent\");\n\nObject.keys(_IPartialEvent).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _IPartialEvent[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _IPartialEvent[key];\n    }\n  });\n});\n\nvar _InvalidEventError = require(\"./InvalidEventError\");\n\nObject.keys(_InvalidEventError).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _InvalidEventError[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _InvalidEventError[key];\n    }\n  });\n});\n\nvar _NamespacedValue = require(\"./NamespacedValue\");\n\nObject.keys(_NamespacedValue).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _NamespacedValue[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _NamespacedValue[key];\n    }\n  });\n});\n\nvar _NamespacedMap = require(\"./NamespacedMap\");\n\nObject.keys(_NamespacedMap).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _NamespacedMap[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _NamespacedMap[key];\n    }\n  });\n});\n\nvar _types = require(\"./types\");\n\nObject.keys(_types).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _types[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _types[key];\n    }\n  });\n});\n\nvar _MessageMatchers = require(\"./utility/MessageMatchers\");\n\nObject.keys(_MessageMatchers).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _MessageMatchers[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _MessageMatchers[key];\n    }\n  });\n});\n\nvar _events = require(\"./utility/events\");\n\nObject.keys(_events).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _events[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _events[key];\n    }\n  });\n});\n\nvar _MRoomMessage = require(\"./interpreters/legacy/MRoomMessage\");\n\nObject.keys(_MRoomMessage).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _MRoomMessage[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _MRoomMessage[key];\n    }\n  });\n});\n\nvar _MMessage = require(\"./interpreters/modern/MMessage\");\n\nObject.keys(_MMessage).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _MMessage[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _MMessage[key];\n    }\n  });\n});\n\nvar _MPoll = require(\"./interpreters/modern/MPoll\");\n\nObject.keys(_MPoll).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _MPoll[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _MPoll[key];\n    }\n  });\n});\n\nvar _relationship_types = require(\"./events/relationship_types\");\n\nObject.keys(_relationship_types).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _relationship_types[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _relationship_types[key];\n    }\n  });\n});\n\nvar _ExtensibleEvent = require(\"./events/ExtensibleEvent\");\n\nObject.keys(_ExtensibleEvent).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _ExtensibleEvent[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _ExtensibleEvent[key];\n    }\n  });\n});\n\nvar _message_types = require(\"./events/message_types\");\n\nObject.keys(_message_types).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _message_types[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _message_types[key];\n    }\n  });\n});\n\nvar _MessageEvent = require(\"./events/MessageEvent\");\n\nObject.keys(_MessageEvent).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _MessageEvent[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _MessageEvent[key];\n    }\n  });\n});\n\nvar _EmoteEvent = require(\"./events/EmoteEvent\");\n\nObject.keys(_EmoteEvent).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _EmoteEvent[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _EmoteEvent[key];\n    }\n  });\n});\n\nvar _NoticeEvent = require(\"./events/NoticeEvent\");\n\nObject.keys(_NoticeEvent).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _NoticeEvent[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _NoticeEvent[key];\n    }\n  });\n});\n\nvar _poll_types = require(\"./events/poll_types\");\n\nObject.keys(_poll_types).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _poll_types[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _poll_types[key];\n    }\n  });\n});\n\nvar _PollStartEvent = require(\"./events/PollStartEvent\");\n\nObject.keys(_PollStartEvent).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _PollStartEvent[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _PollStartEvent[key];\n    }\n  });\n});\n\nvar _PollResponseEvent = require(\"./events/PollResponseEvent\");\n\nObject.keys(_PollResponseEvent).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _PollResponseEvent[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _PollResponseEvent[key];\n    }\n  });\n});\n\nvar _PollEndEvent = require(\"./events/PollEndEvent\");\n\nObject.keys(_PollEndEvent).forEach(function (key) {\n  if (key === \"default\" || key === \"__esModule\") return;\n  if (key in exports && exports[key] === _PollEndEvent[key]) return;\n  Object.defineProperty(exports, key, {\n    enumerable: true,\n    get: function get() {\n      return _PollEndEvent[key];\n    }\n  });\n});","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { NamespacedValue, UnstableValue } from \"../NamespacedValue.js\";\nexport var EventType = /*#__PURE__*/function (EventType) {\n  // Room state events\n  EventType[\"RoomCanonicalAlias\"] = \"m.room.canonical_alias\";\n  EventType[\"RoomCreate\"] = \"m.room.create\";\n  EventType[\"RoomJoinRules\"] = \"m.room.join_rules\";\n  EventType[\"RoomMember\"] = \"m.room.member\";\n  EventType[\"RoomThirdPartyInvite\"] = \"m.room.third_party_invite\";\n  EventType[\"RoomPowerLevels\"] = \"m.room.power_levels\";\n  EventType[\"RoomName\"] = \"m.room.name\";\n  EventType[\"RoomTopic\"] = \"m.room.topic\";\n  EventType[\"RoomAvatar\"] = \"m.room.avatar\";\n  EventType[\"RoomPinnedEvents\"] = \"m.room.pinned_events\";\n  EventType[\"RoomEncryption\"] = \"m.room.encryption\";\n  EventType[\"RoomHistoryVisibility\"] = \"m.room.history_visibility\";\n  EventType[\"RoomGuestAccess\"] = \"m.room.guest_access\";\n  EventType[\"RoomServerAcl\"] = \"m.room.server_acl\";\n  EventType[\"RoomTombstone\"] = \"m.room.tombstone\";\n  EventType[\"RoomPredecessor\"] = \"org.matrix.msc3946.room_predecessor\";\n  // Moderation policy lists\n  EventType[\"PolicyRuleUser\"] = \"m.policy.rule.user\";\n  EventType[\"PolicyRuleRoom\"] = \"m.policy.rule.room\";\n  EventType[\"PolicyRuleServer\"] = \"m.policy.rule.server\";\n  EventType[\"SpaceChild\"] = \"m.space.child\";\n  EventType[\"SpaceParent\"] = \"m.space.parent\";\n  // Room timeline events\n  EventType[\"RoomRedaction\"] = \"m.room.redaction\";\n  EventType[\"RoomMessage\"] = \"m.room.message\";\n  EventType[\"RoomMessageEncrypted\"] = \"m.room.encrypted\";\n  EventType[\"Sticker\"] = \"m.sticker\";\n  EventType[\"CallInvite\"] = \"m.call.invite\";\n  EventType[\"CallCandidates\"] = \"m.call.candidates\";\n  EventType[\"CallAnswer\"] = \"m.call.answer\";\n  EventType[\"CallHangup\"] = \"m.call.hangup\";\n  EventType[\"CallReject\"] = \"m.call.reject\";\n  EventType[\"CallSelectAnswer\"] = \"m.call.select_answer\";\n  EventType[\"CallNegotiate\"] = \"m.call.negotiate\";\n  EventType[\"CallSDPStreamMetadataChanged\"] = \"m.call.sdp_stream_metadata_changed\";\n  EventType[\"CallSDPStreamMetadataChangedPrefix\"] = \"org.matrix.call.sdp_stream_metadata_changed\";\n  EventType[\"CallReplaces\"] = \"m.call.replaces\";\n  EventType[\"CallAssertedIdentity\"] = \"m.call.asserted_identity\";\n  EventType[\"CallAssertedIdentityPrefix\"] = \"org.matrix.call.asserted_identity\";\n  EventType[\"CallEncryptionKeysPrefix\"] = \"io.element.call.encryption_keys\";\n  EventType[\"KeyVerificationRequest\"] = \"m.key.verification.request\";\n  EventType[\"KeyVerificationStart\"] = \"m.key.verification.start\";\n  EventType[\"KeyVerificationCancel\"] = \"m.key.verification.cancel\";\n  EventType[\"KeyVerificationMac\"] = \"m.key.verification.mac\";\n  EventType[\"KeyVerificationDone\"] = \"m.key.verification.done\";\n  EventType[\"KeyVerificationKey\"] = \"m.key.verification.key\";\n  EventType[\"KeyVerificationAccept\"] = \"m.key.verification.accept\";\n  // Not used directly - see READY_TYPE in VerificationRequest.\n  EventType[\"KeyVerificationReady\"] = \"m.key.verification.ready\";\n  // use of this is discouraged https://matrix.org/docs/spec/client_server/r0.6.1#m-room-message-feedback\n  EventType[\"RoomMessageFeedback\"] = \"m.room.message.feedback\";\n  EventType[\"Reaction\"] = \"m.reaction\";\n  EventType[\"PollStart\"] = \"org.matrix.msc3381.poll.start\";\n  // Room ephemeral events\n  EventType[\"Typing\"] = \"m.typing\";\n  EventType[\"Receipt\"] = \"m.receipt\";\n  EventType[\"Presence\"] = \"m.presence\";\n  // Room account_data events\n  EventType[\"FullyRead\"] = \"m.fully_read\";\n  EventType[\"Tag\"] = \"m.tag\";\n  EventType[\"SpaceOrder\"] = \"org.matrix.msc3230.space_order\";\n  // MSC3230\n  // User account_data events\n  EventType[\"PushRules\"] = \"m.push_rules\";\n  EventType[\"Direct\"] = \"m.direct\";\n  EventType[\"IgnoredUserList\"] = \"m.ignored_user_list\";\n  EventType[\"InvitePermissionConfig\"] = \"m.invite_permission_config\";\n  // MSC4380\n  // to_device events\n  EventType[\"RoomKey\"] = \"m.room_key\";\n  EventType[\"RoomKeyRequest\"] = \"m.room_key_request\";\n  EventType[\"ForwardedRoomKey\"] = \"m.forwarded_room_key\";\n  EventType[\"Dummy\"] = \"m.dummy\";\n  EventType[\"SecretRequest\"] = \"m.secret.request\";\n  EventType[\"SecretSend\"] = \"m.secret.send\";\n  // Group call events\n  EventType[\"GroupCallPrefix\"] = \"org.matrix.msc3401.call\";\n  EventType[\"GroupCallMemberPrefix\"] = \"org.matrix.msc3401.call.member\";\n  // MatrixRTC events\n  EventType[\"RTCMembership\"] = \"org.matrix.msc4143.rtc.member\";\n  EventType[\"CallNotify\"] = \"org.matrix.msc4075.call.notify\";\n  EventType[\"RTCNotification\"] = \"org.matrix.msc4075.rtc.notification\";\n  EventType[\"RTCDecline\"] = \"org.matrix.msc4310.rtc.decline\";\n  // Policy servers\n  EventType[\"RoomPolicy\"] = \"org.matrix.msc4284.policy\";\n  return EventType;\n}({});\nexport var RelationType = /*#__PURE__*/function (RelationType) {\n  RelationType[\"Annotation\"] = \"m.annotation\";\n  RelationType[\"Replace\"] = \"m.replace\";\n  RelationType[\"Reference\"] = \"m.reference\";\n  // Don't use this yet: it's only the stable version. The code still assumes we support the unstable prefix and,\n  // moreover, our tests currently use the unstable prefix. Use THREAD_RELATION_TYPE.name.\n  // Once we support *only* the stable prefix, THREAD_RELATION_TYPE can die and we can switch to this.\n  RelationType[\"Thread\"] = \"m.thread\";\n  return RelationType;\n}({});\nexport var MsgType = /*#__PURE__*/function (MsgType) {\n  MsgType[\"Text\"] = \"m.text\";\n  MsgType[\"Emote\"] = \"m.emote\";\n  MsgType[\"Notice\"] = \"m.notice\";\n  MsgType[\"Image\"] = \"m.image\";\n  MsgType[\"File\"] = \"m.file\";\n  MsgType[\"Audio\"] = \"m.audio\";\n  MsgType[\"Location\"] = \"m.location\";\n  MsgType[\"Video\"] = \"m.video\";\n  MsgType[\"KeyVerificationRequest\"] = \"m.key.verification.request\";\n  return MsgType;\n}({});\nexport var RoomCreateTypeField = \"type\";\nexport var RoomType = /*#__PURE__*/function (RoomType) {\n  RoomType[\"Space\"] = \"m.space\";\n  RoomType[\"UnstableCall\"] = \"org.matrix.msc3417.call\";\n  RoomType[\"ElementVideo\"] = \"io.element.video\";\n  return RoomType;\n}({});\nexport var ToDeviceMessageId = \"org.matrix.msgid\";\n\n/**\n * Identifier for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)\n * room purpose. Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport var UNSTABLE_MSC3088_PURPOSE = new UnstableValue(\"m.room.purpose\", \"org.matrix.msc3088.purpose\");\n\n/**\n * Enabled flag for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)\n * room purpose. Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport var UNSTABLE_MSC3088_ENABLED = new UnstableValue(\"m.enabled\", \"org.matrix.msc3088.enabled\");\n\n/**\n * Subtype for an [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room.\n * Note that this reference is UNSTABLE and subject to breaking changes, including its\n * eventual removal.\n */\nexport var UNSTABLE_MSC3089_TREE_SUBTYPE = new UnstableValue(\"m.data_tree\", \"org.matrix.msc3089.data_tree\");\n\n/**\n * Leaf type for an event in a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room.\n * Note that this reference is UNSTABLE and subject to breaking changes, including its\n * eventual removal.\n */\nexport var UNSTABLE_MSC3089_LEAF = new UnstableValue(\"m.leaf\", \"org.matrix.msc3089.leaf\");\n\n/**\n * Branch (Leaf Reference) type for the index approach in a\n * [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room. Note that this reference is\n * UNSTABLE and subject to breaking changes, including its eventual removal.\n */\nexport var UNSTABLE_MSC3089_BRANCH = new UnstableValue(\"m.branch\", \"org.matrix.msc3089.branch\");\n\n/**\n * Marker event type to point back at imported historical content in a room. See\n * [MSC2716](https://github.com/matrix-org/matrix-spec-proposals/pull/2716).\n * Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport var UNSTABLE_MSC2716_MARKER = new UnstableValue(\"m.room.marker\", \"org.matrix.msc2716.marker\");\n\n/**\n * Name of the request property for relation based redactions.\n * {@link https://github.com/matrix-org/matrix-spec-proposals/pull/3912}\n */\nexport var MSC3912_RELATION_BASED_REDACTIONS_PROP = new UnstableValue(\"with_rel_types\", \"org.matrix.msc3912.with_relations\");\n\n/**\n * Functional members type for declaring a purpose of room members (e.g. helpful bots).\n * Note that this reference is UNSTABLE and subject to breaking changes, including its\n * eventual removal.\n *\n * Schema (TypeScript):\n * ```\n * {\n *   service_members?: string[]\n * }\n * ```\n *\n * @example\n * ```\n * {\n *   \"service_members\": [\n *     \"@helperbot:localhost\",\n *     \"@reminderbot:alice.tdl\"\n *   ]\n * }\n * ```\n */\nexport var UNSTABLE_ELEMENT_FUNCTIONAL_USERS = new UnstableValue(\"io.element.functional_members\", \"io.element.functional_members\");\n\n/**\n * A type of message that affects visibility of a message,\n * as per https://github.com/matrix-org/matrix-doc/pull/3531\n *\n * @experimental\n */\nexport var EVENT_VISIBILITY_CHANGE_TYPE = new UnstableValue(\"m.visibility\", \"org.matrix.msc3531.visibility\");\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3881\n *\n * @experimental\n */\nexport var PUSHER_ENABLED = new UnstableValue(\"enabled\", \"org.matrix.msc3881.enabled\");\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3881\n *\n * @experimental\n */\nexport var PUSHER_DEVICE_ID = new UnstableValue(\"device_id\", \"org.matrix.msc3881.device_id\");\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3890\n *\n * @experimental\n */\nexport var LOCAL_NOTIFICATION_SETTINGS_PREFIX = new UnstableValue(\"m.local_notification_settings\", \"org.matrix.msc3890.local_notification_settings\");\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/4023\n *\n * @experimental\n */\nexport var UNSIGNED_THREAD_ID_FIELD = new UnstableValue(\"thread_id\", \"org.matrix.msc4023.thread_id\");\n\n/**\n * https://github.com/matrix-org/matrix-spec-proposals/pull/4115\n *\n * @experimental\n */\nexport var UNSIGNED_MEMBERSHIP_FIELD = new NamespacedValue(\"membership\", \"io.element.msc4115.membership\");\n\n/**\n * Mapped type from event type to content type for all specified non-state room events.\n */\n\n/**\n * Mapped type from event type to content type for all specified room state events.\n */\n\n/**\n * Mapped type from event type to content type for all specified global account_data events.\n */\n\n/**\n * Mapped type from event type to content type for all specified global events encrypted by secret storage.\n *\n * See https://spec.matrix.org/v1.13/client-server-api/#msecret_storagev1aes-hmac-sha2-1\n */\n//# sourceMappingURL=event.js.map","function _objectWithoutPropertiesLoose(r, e) {\n  if (null == r) return {};\n  var t = {};\n  for (var n in r) if ({}.hasOwnProperty.call(r, n)) {\n    if (e.includes(n)) continue;\n    t[n] = r[n];\n  }\n  return t;\n}\nexport { _objectWithoutPropertiesLoose as default };","import objectWithoutPropertiesLoose from \"./objectWithoutPropertiesLoose.js\";\nfunction _objectWithoutProperties(e, t) {\n  if (null == e) return {};\n  var o,\n    r,\n    i = objectWithoutPropertiesLoose(e, t);\n  if (Object.getOwnPropertySymbols) {\n    var s = Object.getOwnPropertySymbols(e);\n    for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);\n  }\n  return i;\n}\nexport { _objectWithoutProperties as default };","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n  ? R.apply\n  : function ReflectApply(target, receiver, args) {\n    return Function.prototype.apply.call(target, receiver, args);\n  }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n  ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n  ReflectOwnKeys = function ReflectOwnKeys(target) {\n    return Object.getOwnPropertyNames(target)\n      .concat(Object.getOwnPropertySymbols(target));\n  };\n} else {\n  ReflectOwnKeys = function ReflectOwnKeys(target) {\n    return Object.getOwnPropertyNames(target);\n  };\n}\n\nfunction ProcessEmitWarning(warning) {\n  if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n  return value !== value;\n}\n\nfunction EventEmitter() {\n  EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n  if (typeof listener !== 'function') {\n    throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n  }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n  enumerable: true,\n  get: function() {\n    return defaultMaxListeners;\n  },\n  set: function(arg) {\n    if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n      throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n    }\n    defaultMaxListeners = arg;\n  }\n});\n\nEventEmitter.init = function() {\n\n  if (this._events === undefined ||\n      this._events === Object.getPrototypeOf(this)._events) {\n    this._events = Object.create(null);\n    this._eventsCount = 0;\n  }\n\n  this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n  if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n    throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n  }\n  this._maxListeners = n;\n  return this;\n};\n\nfunction _getMaxListeners(that) {\n  if (that._maxListeners === undefined)\n    return EventEmitter.defaultMaxListeners;\n  return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n  return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n  var args = [];\n  for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n  var doError = (type === 'error');\n\n  var events = this._events;\n  if (events !== undefined)\n    doError = (doError && events.error === undefined);\n  else if (!doError)\n    return false;\n\n  // If there is no 'error' event listener then throw.\n  if (doError) {\n    var er;\n    if (args.length > 0)\n      er = args[0];\n    if (er instanceof Error) {\n      // Note: The comments on the `throw` lines are intentional, they show\n      // up in Node's output if this results in an unhandled exception.\n      throw er; // Unhandled 'error' event\n    }\n    // At least give some kind of context to the user\n    var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n    err.context = er;\n    throw err; // Unhandled 'error' event\n  }\n\n  var handler = events[type];\n\n  if (handler === undefined)\n    return false;\n\n  if (typeof handler === 'function') {\n    ReflectApply(handler, this, args);\n  } else {\n    var len = handler.length;\n    var listeners = arrayClone(handler, len);\n    for (var i = 0; i < len; ++i)\n      ReflectApply(listeners[i], this, args);\n  }\n\n  return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n  var m;\n  var events;\n  var existing;\n\n  checkListener(listener);\n\n  events = target._events;\n  if (events === undefined) {\n    events = target._events = Object.create(null);\n    target._eventsCount = 0;\n  } else {\n    // To avoid recursion in the case that type === \"newListener\"! Before\n    // adding it to the listeners, first emit \"newListener\".\n    if (events.newListener !== undefined) {\n      target.emit('newListener', type,\n                  listener.listener ? listener.listener : listener);\n\n      // Re-assign `events` because a newListener handler could have caused the\n      // this._events to be assigned to a new object\n      events = target._events;\n    }\n    existing = events[type];\n  }\n\n  if (existing === undefined) {\n    // Optimize the case of one listener. Don't need the extra array object.\n    existing = events[type] = listener;\n    ++target._eventsCount;\n  } else {\n    if (typeof existing === 'function') {\n      // Adding the second element, need to change to array.\n      existing = events[type] =\n        prepend ? [listener, existing] : [existing, listener];\n      // If we've already got an array, just append.\n    } else if (prepend) {\n      existing.unshift(listener);\n    } else {\n      existing.push(listener);\n    }\n\n    // Check for listener leak\n    m = _getMaxListeners(target);\n    if (m > 0 && existing.length > m && !existing.warned) {\n      existing.warned = true;\n      // No error code for this since it is a Warning\n      // eslint-disable-next-line no-restricted-syntax\n      var w = new Error('Possible EventEmitter memory leak detected. ' +\n                          existing.length + ' ' + String(type) + ' listeners ' +\n                          'added. Use emitter.setMaxListeners() to ' +\n                          'increase limit');\n      w.name = 'MaxListenersExceededWarning';\n      w.emitter = target;\n      w.type = type;\n      w.count = existing.length;\n      ProcessEmitWarning(w);\n    }\n  }\n\n  return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n  return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n    function prependListener(type, listener) {\n      return _addListener(this, type, listener, true);\n    };\n\nfunction onceWrapper() {\n  if (!this.fired) {\n    this.target.removeListener(this.type, this.wrapFn);\n    this.fired = true;\n    if (arguments.length === 0)\n      return this.listener.call(this.target);\n    return this.listener.apply(this.target, arguments);\n  }\n}\n\nfunction _onceWrap(target, type, listener) {\n  var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n  var wrapped = onceWrapper.bind(state);\n  wrapped.listener = listener;\n  state.wrapFn = wrapped;\n  return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n  checkListener(listener);\n  this.on(type, _onceWrap(this, type, listener));\n  return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n    function prependOnceListener(type, listener) {\n      checkListener(listener);\n      this.prependListener(type, _onceWrap(this, type, listener));\n      return this;\n    };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n    function removeListener(type, listener) {\n      var list, events, position, i, originalListener;\n\n      checkListener(listener);\n\n      events = this._events;\n      if (events === undefined)\n        return this;\n\n      list = events[type];\n      if (list === undefined)\n        return this;\n\n      if (list === listener || list.listener === listener) {\n        if (--this._eventsCount === 0)\n          this._events = Object.create(null);\n        else {\n          delete events[type];\n          if (events.removeListener)\n            this.emit('removeListener', type, list.listener || listener);\n        }\n      } else if (typeof list !== 'function') {\n        position = -1;\n\n        for (i = list.length - 1; i >= 0; i--) {\n          if (list[i] === listener || list[i].listener === listener) {\n            originalListener = list[i].listener;\n            position = i;\n            break;\n          }\n        }\n\n        if (position < 0)\n          return this;\n\n        if (position === 0)\n          list.shift();\n        else {\n          spliceOne(list, position);\n        }\n\n        if (list.length === 1)\n          events[type] = list[0];\n\n        if (events.removeListener !== undefined)\n          this.emit('removeListener', type, originalListener || listener);\n      }\n\n      return this;\n    };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n    function removeAllListeners(type) {\n      var listeners, events, i;\n\n      events = this._events;\n      if (events === undefined)\n        return this;\n\n      // not listening for removeListener, no need to emit\n      if (events.removeListener === undefined) {\n        if (arguments.length === 0) {\n          this._events = Object.create(null);\n          this._eventsCount = 0;\n        } else if (events[type] !== undefined) {\n          if (--this._eventsCount === 0)\n            this._events = Object.create(null);\n          else\n            delete events[type];\n        }\n        return this;\n      }\n\n      // emit removeListener for all listeners on all events\n      if (arguments.length === 0) {\n        var keys = Object.keys(events);\n        var key;\n        for (i = 0; i < keys.length; ++i) {\n          key = keys[i];\n          if (key === 'removeListener') continue;\n          this.removeAllListeners(key);\n        }\n        this.removeAllListeners('removeListener');\n        this._events = Object.create(null);\n        this._eventsCount = 0;\n        return this;\n      }\n\n      listeners = events[type];\n\n      if (typeof listeners === 'function') {\n        this.removeListener(type, listeners);\n      } else if (listeners !== undefined) {\n        // LIFO order\n        for (i = listeners.length - 1; i >= 0; i--) {\n          this.removeListener(type, listeners[i]);\n        }\n      }\n\n      return this;\n    };\n\nfunction _listeners(target, type, unwrap) {\n  var events = target._events;\n\n  if (events === undefined)\n    return [];\n\n  var evlistener = events[type];\n  if (evlistener === undefined)\n    return [];\n\n  if (typeof evlistener === 'function')\n    return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n  return unwrap ?\n    unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n  return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n  return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n  if (typeof emitter.listenerCount === 'function') {\n    return emitter.listenerCount(type);\n  } else {\n    return listenerCount.call(emitter, type);\n  }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n  var events = this._events;\n\n  if (events !== undefined) {\n    var evlistener = events[type];\n\n    if (typeof evlistener === 'function') {\n      return 1;\n    } else if (evlistener !== undefined) {\n      return evlistener.length;\n    }\n  }\n\n  return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n  return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n  var copy = new Array(n);\n  for (var i = 0; i < n; ++i)\n    copy[i] = arr[i];\n  return copy;\n}\n\nfunction spliceOne(list, index) {\n  for (; index + 1 < list.length; index++)\n    list[index] = list[index + 1];\n  list.pop();\n}\n\nfunction unwrapListeners(arr) {\n  var ret = new Array(arr.length);\n  for (var i = 0; i < ret.length; ++i) {\n    ret[i] = arr[i].listener || arr[i];\n  }\n  return ret;\n}\n\nfunction once(emitter, name) {\n  return new Promise(function (resolve, reject) {\n    function errorListener(err) {\n      emitter.removeListener(name, resolver);\n      reject(err);\n    }\n\n    function resolver() {\n      if (typeof emitter.removeListener === 'function') {\n        emitter.removeListener('error', errorListener);\n      }\n      resolve([].slice.call(arguments));\n    };\n\n    eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n    if (name !== 'error') {\n      addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n    }\n  });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n  if (typeof emitter.on === 'function') {\n    eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n  }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n  if (typeof emitter.on === 'function') {\n    if (flags.once) {\n      emitter.once(name, listener);\n    } else {\n      emitter.on(name, listener);\n    }\n  } else if (typeof emitter.addEventListener === 'function') {\n    // EventTarget does not have `error` event semantics like Node\n    // EventEmitters, we do not listen for `error` events here.\n    emitter.addEventListener(name, function wrapListener(arg) {\n      // IE does not have builtin `{ once: true }` support so we\n      // have to do it manually.\n      if (flags.once) {\n        emitter.removeEventListener(name, wrapListener);\n      }\n      listener(arg);\n    });\n  } else {\n    throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n  }\n}\n","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\n/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// eslint-disable-next-line no-restricted-imports\nimport { EventEmitter } from \"events\";\n\n/** Events emitted by EventEmitter itself */\nexport var EventEmitterEvents = /*#__PURE__*/function (EventEmitterEvents) {\n  EventEmitterEvents[\"NewListener\"] = \"newListener\";\n  EventEmitterEvents[\"RemoveListener\"] = \"removeListener\";\n  EventEmitterEvents[\"Error\"] = \"error\";\n  return EventEmitterEvents;\n}({});\n\n/** Base class for types mapping from event name to the type of listeners to that event */\n\n/**\n * The expected type of a listener function for a particular event.\n *\n * Type parameters:\n *   * `E` - List of all events emitted by the `TypedEventEmitter`. Normally an enum type.\n *   * `A` - A type providing mappings from event names to listener types.\n *   * `T` - The name of the actual event that this listener is for. Normally one of the types in `E` or\n *           {@link EventEmitterEvents}.\n */\n\n/**\n * Typed Event Emitter class which can act as a Base Model for all our model\n * and communication events.\n * This makes it much easier for us to distinguish between events, as we now need\n * to properly type this, so that our events are not stringly-based and prone\n * to silly typos.\n *\n * Type parameters:\n *  * `Events` - List of all events emitted by this `TypedEventEmitter`. Normally an enum type.\n *  * `Arguments` - A {@link ListenerMap} type providing mappings from event names to listener types.\n *  * `SuperclassArguments` - TODO: not really sure. Alternative listener mappings, I think? But only honoured for `.emit`?\n */\nexport class TypedEventEmitter extends EventEmitter {\n  /**\n   * Alias for {@link on}.\n   */\n  addListener(event, listener) {\n    return super.addListener(event, listener);\n  }\n\n  /**\n   * Synchronously calls each of the listeners registered for the event named\n   * `event`, in the order they were registered, passing the supplied arguments\n   * to each.\n   *\n   * @param event - The name of the event to emit\n   * @param args - Arguments to pass to the listener\n   * @returns `true` if the event had listeners, `false` otherwise.\n   */\n\n  emit(event) {\n    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n      args[_key - 1] = arguments[_key];\n    }\n    return super.emit(event, ...args);\n  }\n\n  /**\n   * Similar to `emit` but calls all listeners within a `Promise.all` and returns the promise chain\n   * @param event - The name of the event to emit\n   * @param args - Arguments to pass to the listener\n   * @returns `true` if the event had listeners, `false` otherwise.\n   */\n\n  emitPromised(event) {\n    var _arguments = arguments,\n      _this = this;\n    return _asyncToGenerator(function* () {\n      for (var _len2 = _arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n        args[_key2 - 1] = _arguments[_key2];\n      }\n      var listeners = _this.listeners(event);\n      return Promise.allSettled(listeners.map(l => l(...args))).then(() => {\n        return listeners.length > 0;\n      });\n    })();\n  }\n\n  /**\n   * Returns the number of listeners listening to the event named `event`.\n   *\n   * @param event - The name of the event being listened for\n   */\n  listenerCount(event) {\n    return super.listenerCount(event);\n  }\n\n  /**\n   * Returns a copy of the array of listeners for the event named `event`.\n   */\n  listeners(event) {\n    return super.listeners(event);\n  }\n\n  /**\n   * Alias for {@link removeListener}\n   */\n  off(event, listener) {\n    return super.off(event, listener);\n  }\n\n  /**\n   * Adds the `listener` function to the end of the listeners array for the\n   * event named `event`.\n   *\n   * No checks are made to see if the `listener` has already been added. Multiple calls\n   * passing the same combination of `event` and `listener` will result in the `listener`\n   * being added, and called, multiple times.\n   *\n   * By default, event listeners are invoked in the order they are added. The\n   * {@link prependListener} method can be used as an alternative to add the\n   * event listener to the beginning of the listeners array.\n   *\n   * @param event - The name of the event.\n   * @param listener - The callback function\n   *\n   * @returns a reference to the `EventEmitter`, so that calls can be chained.\n   */\n  on(event, listener) {\n    return super.on(event, listener);\n  }\n\n  /**\n   * Adds a **one-time** `listener` function for the event named `event`. The\n   * next time `event` is triggered, this listener is removed and then invoked.\n   *\n   * Returns a reference to the `EventEmitter`, so that calls can be chained.\n   *\n   * By default, event listeners are invoked in the order they are added.\n   * The {@link prependOnceListener} method can be used as an alternative to add the\n   * event listener to the beginning of the listeners array.\n   *\n   * @param event - The name of the event.\n   * @param listener - The callback function\n   *\n   * @returns a reference to the `EventEmitter`, so that calls can be chained.\n   */\n  once(event, listener) {\n    return super.once(event, listener);\n  }\n\n  /**\n   * Adds the `listener` function to the _beginning_ of the listeners array for the\n   * event named `event`.\n   *\n   * No checks are made to see if the `listener` has already been added. Multiple calls\n   * passing the same combination of `event` and `listener` will result in the `listener`\n   * being added, and called, multiple times.\n   *\n   * @param event - The name of the event.\n   * @param listener - The callback function\n   *\n   * @returns a reference to the `EventEmitter`, so that calls can be chained.\n   */\n  prependListener(event, listener) {\n    return super.prependListener(event, listener);\n  }\n\n  /**\n   * Adds a **one-time**`listener` function for the event named `event` to the _beginning_ of the listeners array.\n   * The next time `event` is triggered, this listener is removed, and then invoked.\n   *\n   * @param event - The name of the event.\n   * @param listener - The callback function\n   *\n   * @returns a reference to the `EventEmitter`, so that calls can be chained.\n   */\n  prependOnceListener(event, listener) {\n    return super.prependOnceListener(event, listener);\n  }\n\n  /**\n   * Removes all listeners, or those of the specified `event`.\n   *\n   * It is bad practice to remove listeners added elsewhere in the code,\n   * particularly when the `EventEmitter` instance was created by some other\n   * component or module (e.g. sockets or file streams).\n   *\n   * @param event - The name of the event. If undefined, all listeners everywhere are removed.\n   * @returns a reference to the `EventEmitter`, so that calls can be chained.\n   */\n  removeAllListeners(event) {\n    // EventEmitter::removeAllListeners uses `arguments.length` to determine undefined case\n    if (event === undefined) {\n      return super.removeAllListeners();\n    }\n    return super.removeAllListeners(event);\n  }\n\n  /**\n   * Removes the specified `listener` from the listener array for the event named `event`.\n   *\n   * @returns a reference to the `EventEmitter`, so that calls can be chained.\n   */\n  removeListener(event, listener) {\n    return super.removeListener(event, listener);\n  }\n\n  /**\n   * Returns a copy of the array of listeners for the event named `eventName`,\n   * including any wrappers (such as those created by `.once()`).\n   */\n  rawListeners(event) {\n    return super.rawListeners(event);\n  }\n}\n//# sourceMappingURL=typed-event-emitter.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { TypedEventEmitter } from \"./typed-event-emitter.js\";\nexport var UserEvent = /*#__PURE__*/function (UserEvent) {\n  UserEvent[\"DisplayName\"] = \"User.displayName\";\n  UserEvent[\"AvatarUrl\"] = \"User.avatarUrl\";\n  UserEvent[\"Presence\"] = \"User.presence\";\n  UserEvent[\"CurrentlyActive\"] = \"User.currentlyActive\";\n  UserEvent[\"LastPresenceTs\"] = \"User.lastPresenceTs\";\n  return UserEvent;\n}({});\nexport class User extends TypedEventEmitter {\n  /**\n   * Construct a new User. A User must have an ID and can optionally have extra information associated with it.\n   * @param userId - Required. The ID of this user.\n   * @deprecated use `User.createUser`\n   */\n  constructor(userId) {\n    super();\n    this.userId = userId;\n    _defineProperty(this, \"modified\", -1);\n    /**\n     * The 'displayname' of the user if known.\n     * @privateRemarks\n     * Should be read-only\n     */\n    _defineProperty(this, \"displayName\", void 0);\n    _defineProperty(this, \"rawDisplayName\", void 0);\n    /**\n     * The 'avatar_url' of the user if known.\n     * @privateRemarks\n     * Should be read-only\n     */\n    _defineProperty(this, \"avatarUrl\", void 0);\n    /**\n     * The presence status message if known.\n     * @privateRemarks\n     * Should be read-only\n     */\n    _defineProperty(this, \"presenceStatusMsg\", void 0);\n    /**\n     * The presence enum if known.\n     * @privateRemarks\n     * Should be read-only\n     */\n    _defineProperty(this, \"presence\", \"offline\");\n    /**\n     * Timestamp (ms since the epoch) for when we last received presence data for this user.\n     * We can subtract lastActiveAgo from this to approximate an absolute value for when a user was last active.\n     * @privateRemarks\n     * Should be read-only\n     */\n    _defineProperty(this, \"lastActiveAgo\", 0);\n    /**\n     * The time elapsed in ms since the user interacted proactively with the server,\n     * or we saw a message from the user\n     * @privateRemarks\n     * Should be read-only\n     */\n    _defineProperty(this, \"lastPresenceTs\", 0);\n    /**\n     * Whether we should consider lastActiveAgo to be an approximation\n     * and that the user should be seen as active 'now'\n     * @privateRemarks\n     * Should be read-only\n     */\n    _defineProperty(this, \"currentlyActive\", false);\n    /**\n     * The events describing this user.\n     * @privateRemarks\n     * Should be read-only\n     */\n    _defineProperty(this, \"events\", {});\n    this.displayName = userId;\n    this.rawDisplayName = userId;\n    this.updateModifiedTime();\n  }\n\n  /**\n   * Construct a new User whose events will also emit on MatrixClient.\n   * A User must have an ID and can optionally have extra information associated with it.\n   * @param userId - Required. The ID of this user.\n   * @param client - An instance of MatrixClient object\n   * @returns User object with reEmitter setup on client\n   */\n  static createUser(userId, client) {\n    var user = new User(userId);\n    client.reEmitter.reEmit(user, [UserEvent.AvatarUrl, UserEvent.DisplayName, UserEvent.Presence, UserEvent.CurrentlyActive, UserEvent.LastPresenceTs]);\n    return user;\n  }\n\n  /**\n   * Update this User with the given presence event. May fire \"User.presence\",\n   * \"User.avatarUrl\" and/or \"User.displayName\" if this event updates this user's\n   * properties.\n   * @param event - The `m.presence` event.\n   *\n   * @remarks\n   * Fires {@link UserEvent.Presence}\n   * Fires {@link UserEvent.DisplayName}\n   * Fires {@link UserEvent.AvatarUrl}\n   */\n  setPresenceEvent(event) {\n    if (event.getType() !== \"m.presence\") {\n      return;\n    }\n    var firstFire = this.events.presence === null;\n    this.events.presence = event;\n    var eventsToFire = [];\n    if (event.getContent().presence !== this.presence || firstFire) {\n      eventsToFire.push(UserEvent.Presence);\n    }\n    if (event.getContent().avatar_url && event.getContent().avatar_url !== this.avatarUrl) {\n      eventsToFire.push(UserEvent.AvatarUrl);\n    }\n    if (event.getContent().displayname && event.getContent().displayname !== this.displayName) {\n      eventsToFire.push(UserEvent.DisplayName);\n    }\n    if (event.getContent().currently_active !== undefined && event.getContent().currently_active !== this.currentlyActive) {\n      eventsToFire.push(UserEvent.CurrentlyActive);\n    }\n    this.presence = event.getContent().presence;\n    eventsToFire.push(UserEvent.LastPresenceTs);\n    if (event.getContent().status_msg) {\n      this.presenceStatusMsg = event.getContent().status_msg;\n    }\n    if (event.getContent().displayname) {\n      this.displayName = event.getContent().displayname;\n    }\n    if (event.getContent().avatar_url) {\n      this.avatarUrl = event.getContent().avatar_url;\n    }\n    this.lastActiveAgo = event.getContent().last_active_ago;\n    this.lastPresenceTs = Date.now();\n    this.currentlyActive = event.getContent().currently_active;\n    this.updateModifiedTime();\n    for (var eventToFire of eventsToFire) {\n      this.emit(eventToFire, event, this);\n    }\n  }\n\n  /**\n   * Manually set this user's display name. No event is emitted in response to this\n   * as there is no underlying MatrixEvent to emit with.\n   * @param name - The new display name.\n   */\n  setDisplayName(name) {\n    var oldName = this.displayName;\n    this.displayName = name;\n    if (name !== oldName) {\n      this.updateModifiedTime();\n    }\n  }\n\n  /**\n   * Manually set this user's non-disambiguated display name. No event is emitted\n   * in response to this as there is no underlying MatrixEvent to emit with.\n   * @param name - The new display name.\n   */\n  setRawDisplayName(name) {\n    this.rawDisplayName = name;\n  }\n\n  /**\n   * Manually set this user's avatar URL. No event is emitted in response to this\n   * as there is no underlying MatrixEvent to emit with.\n   * @param url - The new avatar URL.\n   */\n  setAvatarUrl(url) {\n    var oldUrl = this.avatarUrl;\n    this.avatarUrl = url;\n    if (url !== oldUrl) {\n      this.updateModifiedTime();\n    }\n  }\n\n  /**\n   * Update the last modified time to the current time.\n   */\n  updateModifiedTime() {\n    this.modified = Date.now();\n  }\n\n  /**\n   * Get the timestamp when this User was last updated. This timestamp is\n   * updated when this User receives a new Presence event which has updated a\n   * property on this object. It is updated <i>before</i> firing events.\n   * @returns The timestamp\n   */\n  getLastModifiedTime() {\n    return this.modified;\n  }\n\n  /**\n   * Get the absolute timestamp when this User was last known active on the server.\n   * It is *NOT* accurate if this.currentlyActive is true.\n   * @returns The timestamp\n   */\n  getLastActiveTs() {\n    return this.lastPresenceTs - this.lastActiveAgo;\n  }\n}\n//# sourceMappingURL=user.js.map","/*\nCopyright 2015 - 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// Validation based on https://spec.matrix.org/v1.12/appendices/#server-name\n// We do not use the validation described in https://spec.matrix.org/v1.12/client-server-api/#security-considerations-5\n// as it'd wrongly make all MXCs invalid due to not allowing `[].:` in server names.\nvar serverNameRegex = /^(?:(?:\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|(?:\\[[\\dA-Fa-f:.]{2,45}])|(?:[A-Za-z\\d\\-.]{1,255}))(?::\\d{1,5})?$/;\nfunction validateServerName(serverName) {\n  var matches = serverNameRegex.exec(serverName);\n  return (matches === null || matches === void 0 ? void 0 : matches[0]) === serverName;\n}\n\n// Validation based on https://spec.matrix.org/v1.12/client-server-api/#security-considerations-5\nvar mediaIdRegex = /^[\\w-]+$/;\nfunction validateMediaId(mediaId) {\n  var matches = mediaIdRegex.exec(mediaId);\n  return (matches === null || matches === void 0 ? void 0 : matches[0]) === mediaId;\n}\n\n/**\n * Get the HTTP URL for an MXC URI.\n * @param baseUrl - The base homeserver url which has a content repo.\n * @param mxc - The mxc:// URI.\n * @param width - The desired width of the thumbnail.\n * @param height - The desired height of the thumbnail.\n * @param resizeMethod - The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param allowDirectLinks - If true, return any non-mxc URLs\n * directly. Fetching such URLs will leak information about the user to\n * anyone they share a room with. If false, will return the emptry string\n * for such URLs.\n * @param allowRedirects - If true, the caller supports the URL being 307 or\n * 308 redirected to another resource upon request. If false, redirects\n * are not expected. Implied `true` when `useAuthentication` is `true`.\n * @param useAuthentication - If true, the caller supports authenticated\n * media and wants an authentication-required URL. Note that server support\n * for authenticated media will *not* be checked - it is the caller's responsibility\n * to do so before calling this function. Note also that `useAuthentication`\n * implies `allowRedirects`. Defaults to false (unauthenticated endpoints).\n * @returns The complete URL to the content, may be an empty string if the provided mxc is not valid.\n */\nexport function getHttpUriForMxc(baseUrl, mxc, width, height, resizeMethod) {\n  var allowDirectLinks = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;\n  var allowRedirects = arguments.length > 6 ? arguments[6] : undefined;\n  var useAuthentication = arguments.length > 7 ? arguments[7] : undefined;\n  if (typeof mxc !== \"string\" || !mxc) {\n    return \"\";\n  }\n  if (!mxc.startsWith(\"mxc://\")) {\n    if (allowDirectLinks) {\n      return mxc;\n    } else {\n      return \"\";\n    }\n  }\n  var [serverName, mediaId, ...rest] = mxc.slice(6).split(\"/\");\n  if (rest.length > 0 || !validateServerName(serverName) || !validateMediaId(mediaId)) {\n    return \"\";\n  }\n  if (useAuthentication) {\n    allowRedirects = true; // per docs (MSC3916 always expects redirects)\n\n    // Dev note: MSC3916 removes `allow_redirect` entirely, but\n    // for explicitness we set it here. This makes it slightly more obvious to\n    // callers, hopefully.\n  }\n  var prefix;\n  var isThumbnailRequest = !!width || !!height || !!resizeMethod;\n  var verb = isThumbnailRequest ? \"thumbnail\" : \"download\";\n  if (useAuthentication) {\n    prefix = \"/_matrix/client/v1/media/\".concat(verb);\n  } else {\n    prefix = \"/_matrix/media/v3/\".concat(verb);\n  }\n  var url = new URL(\"\".concat(prefix, \"/\").concat(serverName, \"/\").concat(mediaId), baseUrl);\n  if (width) {\n    url.searchParams.set(\"width\", Math.round(width).toString());\n  }\n  if (height) {\n    url.searchParams.set(\"height\", Math.round(height).toString());\n  }\n  if (resizeMethod) {\n    url.searchParams.set(\"method\", resizeMethod);\n  }\n  if (typeof allowRedirects === \"boolean\") {\n    // We add this after, so we don't convert everything to a thumbnail request.\n    url.searchParams.set(\"allow_redirect\", JSON.stringify(allowRedirects));\n  }\n  return url.href;\n}\n//# sourceMappingURL=content-repo.js.map","/*\nCopyright 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Well-known values (from the spec or MSCs) that are allowed in the\n * {@link Membership} type.\n */\nexport var KnownMembership = /*#__PURE__*/function (KnownMembership) {\n  /**\n   * The user has been banned from the room, and is no longer allowed to join\n   * it until they are un-banned from the room (by having their membership\n   * state set to a value other than ban).\n   */\n  KnownMembership[\"Ban\"] = \"ban\";\n  /**\n   * The user has been invited to join a room, but has not yet joined it.\n   * They may not participate in the room until they join.\n   * */\n  KnownMembership[\"Invite\"] = \"invite\";\n  /**\n   * The user has joined the room (possibly after accepting an invite), and\n   * may participate in it.\n   */\n  KnownMembership[\"Join\"] = \"join\";\n  /**\n   * The user has knocked on the room, requesting permission to participate.\n   * They may not participate in the room until they join.\n   */\n  KnownMembership[\"Knock\"] = \"knock\";\n  /**\n   * The user was once joined to the room, but has since left (possibly by\n   * choice, or possibly by being kicked).\n   */\n  KnownMembership[\"Leave\"] = \"leave\";\n  return KnownMembership;\n}({});\n\n/**\n * The membership state for a user in a room [1]. A value from\n * {@link KnownMembership} should be used where available, but all string values\n * are allowed to provide flexibility for upcoming spec changes or proposals.\n *\n * [1] https://spec.matrix.org/latest/client-server-api/#mroommember\n */\n//# sourceMappingURL=membership.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { getHttpUriForMxc } from \"../content-repo.js\";\nimport { removeDirectionOverrideChars, removeHiddenChars } from \"../utils.js\";\nimport { logger } from \"../logger.js\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.js\";\nimport { EventType } from \"../@types/event.js\";\nimport { KnownMembership } from \"../@types/membership.js\";\nexport var RoomMemberEvent = /*#__PURE__*/function (RoomMemberEvent) {\n  RoomMemberEvent[\"Membership\"] = \"RoomMember.membership\";\n  RoomMemberEvent[\"Name\"] = \"RoomMember.name\";\n  RoomMemberEvent[\"PowerLevel\"] = \"RoomMember.powerLevel\";\n  RoomMemberEvent[\"Typing\"] = \"RoomMember.typing\";\n  return RoomMemberEvent;\n}({});\nexport class RoomMember extends TypedEventEmitter {\n  /**\n   * Construct a new room member.\n   *\n   * @param roomId - The room ID of the member.\n   * @param userId - The user ID of the member.\n   */\n  constructor(roomId, userId) {\n    super();\n    this.roomId = roomId;\n    this.userId = userId;\n    _defineProperty(this, \"_isOutOfBand\", false);\n    _defineProperty(this, \"modified\", -1);\n    _defineProperty(this, \"requestedProfileInfo\", false);\n    // used by sync.ts\n    // XXX these should be read-only\n    /**\n     * True if the room member is currently typing.\n     */\n    _defineProperty(this, \"typing\", false);\n    /**\n     * The human-readable name for this room member. Similar to {@link rawDisplayName}, but\n     * disambiguated with a suffix of \" (\\@user_id:matrix.org)\" if another member shares the\n     * same displayname.\n     */\n    _defineProperty(this, \"name\", void 0);\n    /**\n     * The ambiguous displayname of this room member, with some preprocessing:\n     *\n     *  * Direction override characters (RTO and LRO) are removed.\n     *  * If the displayname is empty, or contains only blank, non-printing, or diacritcic characters, it is\n     *    replaced with the user ID.\n     */\n    _defineProperty(this, \"rawDisplayName\", void 0);\n    /**\n     * The power level for this room member.\n     */\n    _defineProperty(this, \"powerLevel\", 0);\n    /**\n     * The User object for this room member, if one exists.\n     */\n    _defineProperty(this, \"user\", void 0);\n    /**\n     * The membership state for this room member e.g. 'join'.\n     */\n    _defineProperty(this, \"membership\", void 0);\n    /**\n     * True if the member's name is disambiguated.\n     */\n    _defineProperty(this, \"disambiguate\", false);\n    /**\n     * The events describing this RoomMember.\n     */\n    _defineProperty(this, \"events\", {});\n    this.name = userId;\n    this.rawDisplayName = userId;\n    this.updateModifiedTime();\n  }\n\n  /**\n   * Mark the member as coming from a channel that is not sync\n   */\n  markOutOfBand() {\n    this._isOutOfBand = true;\n  }\n\n  /**\n   * @returns does the member come from a channel that is not sync?\n   * This is used to store the member seperately\n   * from the sync state so it available across browser sessions.\n   */\n  isOutOfBand() {\n    return this._isOutOfBand;\n  }\n\n  /**\n   * Update this room member's membership event. May fire \"RoomMember.name\" if\n   * this event updates this member's name.\n   * @param event - The `m.room.member` event\n   * @param roomState - Optional. The room state to take into account\n   * when calculating (e.g. for disambiguating users with the same name).\n   *\n   * @remarks\n   * Fires {@link RoomMemberEvent.Name}\n   * Fires {@link RoomMemberEvent.Membership}\n   */\n  setMembershipEvent(event, roomState) {\n    var _event$getDirectional, _event$getDirectional2;\n    var displayName = (_event$getDirectional = event.getDirectionalContent().displayname) !== null && _event$getDirectional !== void 0 ? _event$getDirectional : \"\";\n    if (event.getType() !== EventType.RoomMember) {\n      return;\n    }\n    this._isOutOfBand = false;\n    this.events.member = event;\n    var oldMembership = this.membership;\n    this.membership = event.getDirectionalContent().membership;\n    if (this.membership === undefined) {\n      // logging to diagnose https://github.com/vector-im/element-web/issues/20962\n      // (logs event content, although only of membership events)\n      logger.trace(\"membership event with membership undefined (forwardLooking: \".concat(event.forwardLooking, \")!\"), event.getContent(), \"prevcontent is \", event.getPrevContent());\n    }\n    this.disambiguate = shouldDisambiguate(this.userId, displayName, roomState);\n    var oldName = this.name;\n    this.name = calculateDisplayName(this.userId, displayName, this.disambiguate);\n\n    // not quite raw: we strip direction override chars so it can safely be inserted into\n    // blocks of text without breaking the text direction\n    this.rawDisplayName = removeDirectionOverrideChars((_event$getDirectional2 = event.getDirectionalContent().displayname) !== null && _event$getDirectional2 !== void 0 ? _event$getDirectional2 : \"\");\n    if (!this.rawDisplayName || !removeHiddenChars(this.rawDisplayName)) {\n      this.rawDisplayName = this.userId;\n    }\n    if (oldMembership !== this.membership) {\n      this.updateModifiedTime();\n      this.emit(RoomMemberEvent.Membership, event, this, oldMembership);\n    }\n    if (oldName !== this.name) {\n      this.updateModifiedTime();\n      this.emit(RoomMemberEvent.Name, event, this, oldName);\n    }\n  }\n\n  /**\n   * Update this room member's power level event. Will fire\n   * \"RoomMember.powerLevel\" if the new power level is different\n   * @param powerLevel - The power level of the room member.\n   *\n   * @remarks\n   * Fires {@link RoomMemberEvent.PowerLevel}\n   */\n  setPowerLevel(powerLevel, powerLevelEvent) {\n    var oldPowerLevel = this.powerLevel;\n    this.powerLevel = powerLevel;\n    if (oldPowerLevel !== this.powerLevel) {\n      this.updateModifiedTime();\n      this.emit(RoomMemberEvent.PowerLevel, powerLevelEvent, this);\n    }\n  }\n\n  /**\n   * Update this room member's typing event. May fire \"RoomMember.typing\" if\n   * this event changes this member's typing state.\n   * @param event - The typing event\n   *\n   * @remarks\n   * Fires {@link RoomMemberEvent.Typing}\n   */\n  setTypingEvent(event) {\n    if (event.getType() !== \"m.typing\") {\n      return;\n    }\n    var oldTyping = this.typing;\n    this.typing = false;\n    var typingList = event.getContent().user_ids;\n    if (!Array.isArray(typingList)) {\n      // malformed event :/ bail early. TODO: whine?\n      return;\n    }\n    if (typingList.indexOf(this.userId) !== -1) {\n      this.typing = true;\n    }\n    if (oldTyping !== this.typing) {\n      this.updateModifiedTime();\n      this.emit(RoomMemberEvent.Typing, event, this);\n    }\n  }\n\n  /**\n   * Update the last modified time to the current time.\n   */\n  updateModifiedTime() {\n    this.modified = Date.now();\n  }\n\n  /**\n   * Get the timestamp when this RoomMember was last updated. This timestamp is\n   * updated when properties on this RoomMember are updated.\n   * It is updated <i>before</i> firing events.\n   * @returns The timestamp\n   */\n  getLastModifiedTime() {\n    return this.modified;\n  }\n  isKicked() {\n    return this.membership === KnownMembership.Leave && this.events.member !== undefined && this.events.member.getSender() !== this.events.member.getStateKey();\n  }\n\n  /**\n   * If this member was invited with the is_direct flag set, return\n   * the user that invited this member\n   * @returns user id of the inviter\n   */\n  getDMInviter() {\n    // when not available because that room state hasn't been loaded in,\n    // we don't really know, but more likely to not be a direct chat\n    if (this.events.member) {\n      // TODO: persist the is_direct flag on the member as more member events\n      //       come in caused by displayName changes.\n\n      // the is_direct flag is set on the invite member event.\n      // This is copied on the prev_content section of the join member event\n      // when the invite is accepted.\n\n      var memberEvent = this.events.member;\n      var memberContent = memberEvent.getContent();\n      var inviteSender = memberEvent.getSender();\n      if (memberContent.membership === KnownMembership.Join) {\n        memberContent = memberEvent.getPrevContent();\n        inviteSender = memberEvent.getUnsigned().prev_sender;\n      }\n      if (memberContent.membership === KnownMembership.Invite && memberContent.is_direct) {\n        return inviteSender;\n      }\n    }\n  }\n\n  /**\n   * Get the avatar URL for a room member.\n   * @param baseUrl - The base homeserver URL See\n   * {@link MatrixClient#getHomeserverUrl}.\n   * @param width - The desired width of the thumbnail.\n   * @param height - The desired height of the thumbnail.\n   * @param resizeMethod - The thumbnail resize method to use, either\n   * \"crop\" or \"scale\".\n   * @param allowDefault - (optional) Passing false causes this method to\n   * return null if the user has no avatar image. Otherwise, a default image URL\n   * will be returned. Default: true. (Deprecated)\n   * @param allowDirectLinks - (optional) If true, the avatar URL will be\n   * returned even if it is a direct hyperlink rather than a matrix content URL.\n   * If false, any non-matrix content URLs will be ignored. Setting this option to\n   * true will expose URLs that, if fetched, will leak information about the user\n   * to anyone who they share a room with.\n   * @param useAuthentication - (optional) If true, the caller supports authenticated\n   * media and wants an authentication-required URL. Note that server support for\n   * authenticated media will not be checked - it is the caller's responsibility\n   * to do so before calling this function. Note also that useAuthentication\n   * implies allowRedirects. Defaults to false (unauthenticated endpoints).\n   * @returns the avatar URL or null.\n   */\n  getAvatarUrl(baseUrl, width, height, resizeMethod) {\n    var allowDefault = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n    var allowDirectLinks = arguments.length > 5 ? arguments[5] : undefined;\n    var useAuthentication = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false;\n    var rawUrl = this.getMxcAvatarUrl();\n    if (!rawUrl && !allowDefault) {\n      return null;\n    }\n    var httpUrl = getHttpUriForMxc(baseUrl, rawUrl, width, height, resizeMethod, allowDirectLinks, undefined, useAuthentication);\n    if (httpUrl) {\n      return httpUrl;\n    }\n    return null;\n  }\n\n  /**\n   * get the mxc avatar url, either from a state event, or from a lazily loaded member\n   * @returns the mxc avatar url\n   */\n  getMxcAvatarUrl() {\n    if (this.events.member) {\n      return this.events.member.getDirectionalContent().avatar_url;\n    } else if (this.user) {\n      return this.user.avatarUrl;\n    }\n  }\n}\nexport var MXID_PATTERN = /@.+:.+/;\nvar LTR_RTL_PATTERN = /[\\u200E\\u200F\\u202A-\\u202F]/;\nfunction shouldDisambiguate(selfUserId, displayName, roomState) {\n  if (!displayName || displayName === selfUserId) return false;\n  if (!roomState) return false;\n  var strippedDisplayName = removeHiddenChars(displayName);\n\n  // First check if the displayname is something we consider truthy\n  // after stripping it of zero width characters and padding spaces\n  if (!strippedDisplayName) return false;\n\n  // Next check if the name contains something that look like a mxid\n  // If it does, it may be someone trying to impersonate someone else\n  // Show full mxid in this case\n  if (MXID_PATTERN.test(strippedDisplayName)) return true;\n\n  // Also show mxid if the display name contains any LTR/RTL characters as these\n  // make it very difficult for us to find similar *looking* display names\n  // E.g \"Mark\" could be cloned by writing \"kraM\" but in RTL.\n  if (LTR_RTL_PATTERN.test(displayName)) return true;\n\n  // Also show mxid if there are other people with the same or similar\n  // displayname, after hidden character removal.\n  var userIds = roomState.getUserIdsWithDisplayName(displayName);\n  if (userIds.some(u => u !== selfUserId)) return true;\n  return false;\n}\nfunction calculateDisplayName(selfUserId, displayName, disambiguate) {\n  if (!displayName || displayName === selfUserId) return selfUserId;\n  if (disambiguate) return removeDirectionOverrideChars(displayName) + \" (\" + selfUserId + \")\";\n\n  // First check if the displayname is something we consider truthy\n  // after stripping it of zero width characters and padding spaces\n  if (!removeHiddenChars(displayName)) return selfUserId;\n\n  // We always strip the direction override characters (LRO and RLO).\n  // These override the text direction for all subsequent characters\n  // in the paragraph so if display names contained these, they'd\n  // need to be wrapped in something to prevent this from leaking out\n  // (which we can do in HTML but not text) or we'd need to add\n  // control characters to the string to reset any overrides (eg.\n  // adding PDF characters at the end). As far as we can see,\n  // there should be no reason these would be necessary - rtl display\n  // names should flip into the correct direction automatically based on\n  // the characters, and you can still embed rtl in ltr or vice versa\n  // with the embed chars or marker chars.\n  return removeDirectionOverrideChars(displayName);\n}\n//# sourceMappingURL=room-member.js.map","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport var Visibility = /*#__PURE__*/function (Visibility) {\n  Visibility[\"Public\"] = \"public\";\n  Visibility[\"Private\"] = \"private\";\n  return Visibility;\n}({});\nexport var Preset = /*#__PURE__*/function (Preset) {\n  Preset[\"PrivateChat\"] = \"private_chat\";\n  Preset[\"TrustedPrivateChat\"] = \"trusted_private_chat\";\n  Preset[\"PublicChat\"] = \"public_chat\";\n  return Preset;\n}({});\n// Knock and private are reserved keywords which are not yet implemented.\nexport var JoinRule = /*#__PURE__*/function (JoinRule) {\n  JoinRule[\"Public\"] = \"public\";\n  JoinRule[\"Invite\"] = \"invite\";\n  /**\n   * @deprecated Reserved keyword. Should not be used. Not yet implemented.\n   */\n  JoinRule[\"Private\"] = \"private\";\n  JoinRule[\"Knock\"] = \"knock\";\n  JoinRule[\"Restricted\"] = \"restricted\";\n  return JoinRule;\n}({});\nexport var RestrictedAllowType = /*#__PURE__*/function (RestrictedAllowType) {\n  RestrictedAllowType[\"RoomMembership\"] = \"m.room_membership\";\n  return RestrictedAllowType;\n}({});\nexport var GuestAccess = /*#__PURE__*/function (GuestAccess) {\n  GuestAccess[\"CanJoin\"] = \"can_join\";\n  GuestAccess[\"Forbidden\"] = \"forbidden\";\n  return GuestAccess;\n}({});\nexport var HistoryVisibility = /*#__PURE__*/function (HistoryVisibility) {\n  HistoryVisibility[\"Invited\"] = \"invited\";\n  HistoryVisibility[\"Joined\"] = \"joined\";\n  HistoryVisibility[\"Shared\"] = \"shared\";\n  HistoryVisibility[\"WorldReadable\"] = \"world_readable\";\n  return HistoryVisibility;\n}({});\n\n/**\n * A policy name & url in a specific internationalisation\n * @see https://spec.matrix.org/v1.13/identity-service-api/#get_matrixidentityv2terms_response-200_internationalised-policy\n */\n\n/**\n * A versioned policy with internationalised variants\n * @see https://spec.matrix.org/v1.13/identity-service-api/#get_matrixidentityv2terms_response-200_policy-object\n */\n\n/**\n * Response from the Terms API for Identity servers\n * @see https://spec.matrix.org/v1.13/identity-service-api/#get_matrixidentityv2terms\n */\n//# sourceMappingURL=partials.js.map","/*\nCopyright 2021 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Determines if the given optional was provided a value.\n * @param s - The optional to test.\n * @returns True if the value is defined.\n */\nexport function isProvided(s) {\n  return s !== null && s !== undefined;\n}\n\n/**\n * Determines if the given optional string is a defined string.\n * @param s - The input string.\n * @returns True if the input is a defined string.\n */\nexport function isOptionalAString(s) {\n  return isProvided(s) && typeof s === \"string\";\n}\n//# sourceMappingURL=utilities.js.map","/*\nCopyright 2021 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { NamespacedValue, UnstableValue } from \"matrix-events-sdk\";\nimport { isProvided } from \"../extensible_events_v1/utilities.js\";\n\n// Types and utilities for MSC1767: Extensible events (version 1) in Matrix\n\n/**\n * Represents the stable and unstable values of a given namespace.\n */\n\n/**\n * Represents a namespaced value, if the value is a string. Used to extract provided types\n * from a TSNamespace<N> (in cases where only stable *or* unstable is provided).\n */\n\n/**\n * Creates a type which is V when T is `never`, otherwise T.\n */\n// See https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887 for details on the array syntax.\n\n/**\n * The namespaced value for m.message\n */\nexport var M_MESSAGE = new UnstableValue(\"m.message\", \"org.matrix.msc1767.message\");\n\n/**\n * An m.message event rendering\n */\n\n/**\n * The content for an m.message event\n */\n\n/**\n * The namespaced value for m.text\n */\nexport var M_TEXT = new UnstableValue(\"m.text\", \"org.matrix.msc1767.text\");\n\n/**\n * The content for an m.text event\n */\n\n/**\n * The namespaced value for m.html\n */\nexport var M_HTML = new UnstableValue(\"m.html\", \"org.matrix.msc1767.html\");\n\n/**\n * The content for an m.html event\n */\n\n/**\n * The content for an m.message, m.text, or m.html event\n */\n\n/**\n * The namespaced value for an m.reference relation\n */\nexport var REFERENCE_RELATION = new NamespacedValue(\"m.reference\");\n\n/**\n * Represents any relation type\n */\n\n/**\n * An m.relates_to relationship\n */\n\n/**\n * Partial types for a Matrix Event.\n */\n\n/**\n * Represents a potentially namespaced event type.\n */\n\n/**\n * Determines if two event types are the same, including namespaces.\n * @param given - The given event type. This will be compared\n * against the expected type.\n * @param expected - The expected event type.\n * @returns True if the given type matches the expected type.\n */\nexport function isEventTypeSame(given, expected) {\n  if (typeof given === \"string\") {\n    if (typeof expected === \"string\") {\n      return expected === given;\n    } else {\n      return expected.matches(given);\n    }\n  } else {\n    if (typeof expected === \"string\") {\n      return given.matches(expected);\n    } else {\n      var expectedNs = expected;\n      var givenNs = given;\n      return expectedNs.matches(givenNs.name) || isProvided(givenNs.altName) && expectedNs.matches(givenNs.altName);\n    }\n  }\n}\n//# sourceMappingURL=extensible_events.js.map","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport { NamespacedValue } from \"../NamespacedValue.js\";\n/**\n * Extensible topic event type based on MSC3765\n * https://github.com/matrix-org/matrix-spec-proposals/pull/3765\n *\n * @example\n * ```\n * {\n *      \"type\": \"m.room.topic,\n *      \"state_key\": \"\",\n *      \"content\": {\n *          \"topic\": \"All about **pizza**\",\n *          \"m.topic\": [{\n *              \"body\": \"All about **pizza**\",\n *              \"mimetype\": \"text/plain\",\n *          }, {\n *              \"body\": \"All about <b>pizza</b>\",\n *              \"mimetype\": \"text/html\",\n *          }],\n *      }\n * }\n * ```\n */\n\n/**\n * The event type for an m.topic event (in content)\n */\nexport var M_TOPIC = new NamespacedValue(\"m.topic\");\n\n/**\n * The event content for an m.topic event (in content)\n */\n\n/**\n * A previous incorrect form of m.topic used by matrix-js-sdk\n * TODO remove this after a few releases\n *      https://github.com/matrix-org/matrix-js-sdk/pull/4984#pullrequestreview-3174251065\n */\n\n/**\n * The event definition for an m.topic event (in content)\n */\n\n/**\n * The event content for an m.room.topic event\n */\n//# sourceMappingURL=topic.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2018 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MsgType } from \"./@types/event.js\";\nimport { M_TEXT, REFERENCE_RELATION } from \"./@types/extensible_events.js\";\nimport { isProvided } from \"./extensible_events_v1/utilities.js\";\nimport { M_ASSET, LocationAssetType, M_LOCATION, M_TIMESTAMP } from \"./@types/location.js\";\nimport { M_TOPIC } from \"./@types/topic.js\";\n/**\n * Generates the content for a HTML Message event\n * @param body - the plaintext body of the message\n * @param htmlBody - the HTML representation of the message\n * @returns\n */\nexport function makeHtmlMessage(body, htmlBody) {\n  return {\n    msgtype: MsgType.Text,\n    format: \"org.matrix.custom.html\",\n    body: body,\n    formatted_body: htmlBody\n  };\n}\n\n/**\n * Generates the content for a HTML Notice event\n * @param body - the plaintext body of the notice\n * @param htmlBody - the HTML representation of the notice\n * @returns\n */\nexport function makeHtmlNotice(body, htmlBody) {\n  return {\n    msgtype: MsgType.Notice,\n    format: \"org.matrix.custom.html\",\n    body: body,\n    formatted_body: htmlBody\n  };\n}\n\n/**\n * Generates the content for a HTML Emote event\n * @param body - the plaintext body of the emote\n * @param htmlBody - the HTML representation of the emote\n * @returns\n */\nexport function makeHtmlEmote(body, htmlBody) {\n  return {\n    msgtype: MsgType.Emote,\n    format: \"org.matrix.custom.html\",\n    body: body,\n    formatted_body: htmlBody\n  };\n}\n\n/**\n * Generates the content for a Plaintext Message event\n * @param body - the plaintext body of the emote\n * @returns\n */\nexport function makeTextMessage(body) {\n  return {\n    msgtype: MsgType.Text,\n    body: body\n  };\n}\n\n/**\n * Generates the content for a Plaintext Notice event\n * @param body - the plaintext body of the notice\n * @returns\n */\nexport function makeNotice(body) {\n  return {\n    msgtype: MsgType.Notice,\n    body: body\n  };\n}\n\n/**\n * Generates the content for a Plaintext Emote event\n * @param body - the plaintext body of the emote\n * @returns\n */\nexport function makeEmoteMessage(body) {\n  return {\n    msgtype: MsgType.Emote,\n    body: body\n  };\n}\n\n/** Location content helpers */\n\nexport var getTextForLocationEvent = (uri, assetType, timestamp, description) => {\n  var date = \"at \".concat(new Date(timestamp).toISOString());\n  var assetName = assetType === LocationAssetType.Self ? \"User\" : undefined;\n  var quotedDescription = description ? \"\\\"\".concat(description, \"\\\"\") : undefined;\n  return [assetName, \"Location\", quotedDescription, uri, date].filter(Boolean).join(\" \");\n};\n\n/**\n * Generates the content for a Location event\n * @param uri - a geo:// uri for the location\n * @param timestamp - the timestamp when the location was correct (milliseconds since the UNIX epoch)\n * @param description - the (optional) label for this location on the map\n * @param assetType - the (optional) asset type of this location e.g. \"m.self\"\n * @param text - optional. A text for the location\n */\nexport var makeLocationContent = (text, uri, timestamp, description, assetType) => {\n  var defaultedText = text !== null && text !== void 0 ? text : getTextForLocationEvent(uri, assetType || LocationAssetType.Self, timestamp, description);\n  var timestampEvent = timestamp ? {\n    [M_TIMESTAMP.name]: timestamp\n  } : {};\n  return _objectSpread({\n    msgtype: MsgType.Location,\n    body: defaultedText,\n    geo_uri: uri,\n    [M_LOCATION.name]: {\n      description,\n      uri\n    },\n    [M_ASSET.name]: {\n      type: assetType || LocationAssetType.Self\n    },\n    [M_TEXT.name]: defaultedText\n  }, timestampEvent);\n};\n\n/**\n * Parse location event content and transform to\n * a backwards compatible modern m.location event format\n */\nexport var parseLocationEvent = wireEventContent => {\n  var _location$uri, _asset$type;\n  var location = M_LOCATION.findIn(wireEventContent);\n  var asset = M_ASSET.findIn(wireEventContent);\n  var timestamp = M_TIMESTAMP.findIn(wireEventContent);\n  var text = M_TEXT.findIn(wireEventContent);\n  var geoUri = (_location$uri = location === null || location === void 0 ? void 0 : location.uri) !== null && _location$uri !== void 0 ? _location$uri : wireEventContent === null || wireEventContent === void 0 ? void 0 : wireEventContent.geo_uri;\n  var description = location === null || location === void 0 ? void 0 : location.description;\n  var assetType = (_asset$type = asset === null || asset === void 0 ? void 0 : asset.type) !== null && _asset$type !== void 0 ? _asset$type : LocationAssetType.Self;\n  var fallbackText = text !== null && text !== void 0 ? text : wireEventContent.body;\n  return makeLocationContent(fallbackText, geoUri, timestamp !== null && timestamp !== void 0 ? timestamp : undefined, description, assetType);\n};\n\n/**\n * Topic event helpers\n */\n\nexport var makeTopicContent = (topic, htmlTopic) => {\n  var renderings = [];\n  // Put HTML first because clients will render the first type in\n  // the array that they understand\n  if (isProvided(htmlTopic)) {\n    renderings.push({\n      body: htmlTopic,\n      mimetype: \"text/html\"\n    });\n  }\n  if (isProvided(topic)) {\n    renderings.push({\n      body: topic,\n      mimetype: \"text/plain\"\n    });\n  }\n  return {\n    topic,\n    [M_TOPIC.name]: {\n      \"m.text\": renderings\n    }\n  };\n};\nexport var parseTopicContent = content => {\n  var _ref, _mtopic$find$body, _mtopic$find, _mtopic$find2;\n  var mtopicParent = M_TOPIC.findIn(content);\n  var mtopic = Array.isArray(mtopicParent) ? mtopicParent : mtopicParent === null || mtopicParent === void 0 ? void 0 : mtopicParent[\"m.text\"];\n  // TODO remove support for the old malformed m.topic arrays after a few releases (only allow array in m.text)\n  //      https://github.com/matrix-org/matrix-js-sdk/pull/4984#pullrequestreview-3174251065\n  //const mtopic = M_TOPIC.findIn<MTopicContent>(content)?.[\"m.text\"];\n  if (!Array.isArray(mtopic)) {\n    var _content$topic;\n    return {\n      text: (_content$topic = content.topic) !== null && _content$topic !== void 0 ? _content$topic : undefined\n    };\n  }\n  var text = (_ref = (_mtopic$find$body = mtopic === null || mtopic === void 0 || (_mtopic$find = mtopic.find(r => !isProvided(r.mimetype) || r.mimetype === \"text/plain\")) === null || _mtopic$find === void 0 ? void 0 : _mtopic$find.body) !== null && _mtopic$find$body !== void 0 ? _mtopic$find$body : content.topic) !== null && _ref !== void 0 ? _ref : undefined;\n  var html = mtopic === null || mtopic === void 0 || (_mtopic$find2 = mtopic.find(r => r.mimetype === \"text/html\")) === null || _mtopic$find2 === void 0 ? void 0 : _mtopic$find2.body;\n  return {\n    text,\n    html\n  };\n};\n\n/**\n * Beacon event helpers\n */\n\nexport var makeBeaconInfoContent = (timeout, isLive, description, assetType, timestamp) => ({\n  description,\n  timeout,\n  live: isLive,\n  [M_TIMESTAMP.name]: timestamp || Date.now(),\n  [M_ASSET.name]: {\n    type: assetType !== null && assetType !== void 0 ? assetType : LocationAssetType.Self\n  }\n});\n/**\n * Flatten beacon info event content\n */\nexport var parseBeaconInfoContent = content => {\n  var _M_TIMESTAMP$findIn;\n  var {\n    description,\n    timeout,\n    live\n  } = content;\n  var timestamp = (_M_TIMESTAMP$findIn = M_TIMESTAMP.findIn(content)) !== null && _M_TIMESTAMP$findIn !== void 0 ? _M_TIMESTAMP$findIn : undefined;\n  var asset = M_ASSET.findIn(content);\n  return {\n    description,\n    timeout,\n    live,\n    assetType: asset === null || asset === void 0 ? void 0 : asset.type,\n    timestamp\n  };\n};\nexport var makeBeaconContent = (uri, timestamp, beaconInfoEventId, description) => ({\n  [M_LOCATION.name]: {\n    description,\n    uri\n  },\n  [M_TIMESTAMP.name]: timestamp,\n  \"m.relates_to\": {\n    rel_type: REFERENCE_RELATION.name,\n    event_id: beaconInfoEventId\n  }\n});\nexport var parseBeaconContent = content => {\n  var _M_TIMESTAMP$findIn2;\n  var location = M_LOCATION.findIn(content);\n  var timestamp = (_M_TIMESTAMP$findIn2 = M_TIMESTAMP.findIn(content)) !== null && _M_TIMESTAMP$findIn2 !== void 0 ? _M_TIMESTAMP$findIn2 : undefined;\n  return {\n    description: location === null || location === void 0 ? void 0 : location.description,\n    uri: location === null || location === void 0 ? void 0 : location.uri,\n    timestamp\n  };\n};\n//# sourceMappingURL=content-helpers.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { parseBeaconContent, parseBeaconInfoContent } from \"../content-helpers.js\";\nimport { sortEventsByLatestContentTimestamp } from \"../utils.js\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.js\";\nexport var BeaconEvent = /*#__PURE__*/function (BeaconEvent) {\n  BeaconEvent[\"New\"] = \"Beacon.new\";\n  BeaconEvent[\"Update\"] = \"Beacon.update\";\n  BeaconEvent[\"LivenessChange\"] = \"Beacon.LivenessChange\";\n  BeaconEvent[\"Destroy\"] = \"Beacon.Destroy\";\n  BeaconEvent[\"LocationUpdate\"] = \"Beacon.LocationUpdate\";\n  return BeaconEvent;\n}({});\nexport var isTimestampInDuration = (startTimestamp, durationMs, timestamp) => timestamp >= startTimestamp && startTimestamp + durationMs >= timestamp;\n\n// beacon info events are uniquely identified by\n// `<roomId>_<state_key>`\n\nexport var getBeaconInfoIdentifier = event => \"\".concat(event.getRoomId(), \"_\").concat(event.getStateKey());\n\n// https://github.com/matrix-org/matrix-spec-proposals/pull/3672\nexport class Beacon extends TypedEventEmitter {\n  constructor(rootEvent) {\n    super();\n    this.rootEvent = rootEvent;\n    _defineProperty(this, \"roomId\", void 0);\n    // beaconInfo is assigned by setBeaconInfo in the constructor\n    // ! to make tsc believe it is definitely assigned\n    _defineProperty(this, \"_beaconInfo\", void 0);\n    _defineProperty(this, \"_isLive\", void 0);\n    _defineProperty(this, \"livenessWatchTimeout\", void 0);\n    _defineProperty(this, \"_latestLocationEvent\", void 0);\n    _defineProperty(this, \"clearLatestLocation\", () => {\n      this._latestLocationEvent = undefined;\n      this.emit(BeaconEvent.LocationUpdate, this.latestLocationState);\n    });\n    this.roomId = this.rootEvent.getRoomId();\n    this.setBeaconInfo(this.rootEvent);\n  }\n  get isLive() {\n    return !!this._isLive;\n  }\n  get identifier() {\n    return getBeaconInfoIdentifier(this.rootEvent);\n  }\n  get beaconInfoId() {\n    return this.rootEvent.getId();\n  }\n  get beaconInfoOwner() {\n    return this.rootEvent.getStateKey();\n  }\n  get beaconInfoEventType() {\n    return this.rootEvent.getType();\n  }\n  get beaconInfo() {\n    return this._beaconInfo;\n  }\n  get latestLocationState() {\n    return this._latestLocationEvent && parseBeaconContent(this._latestLocationEvent.getContent());\n  }\n  get latestLocationEvent() {\n    return this._latestLocationEvent;\n  }\n  update(beaconInfoEvent) {\n    if (getBeaconInfoIdentifier(beaconInfoEvent) !== this.identifier) {\n      throw new Error(\"Invalid updating event\");\n    }\n    // don't update beacon with an older event\n    if (beaconInfoEvent.getTs() < this.rootEvent.getTs()) {\n      return;\n    }\n    this.rootEvent = beaconInfoEvent;\n    this.setBeaconInfo(this.rootEvent);\n    this.emit(BeaconEvent.Update, beaconInfoEvent, this);\n    this.clearLatestLocation();\n  }\n  destroy() {\n    if (this.livenessWatchTimeout) {\n      clearTimeout(this.livenessWatchTimeout);\n    }\n    this._isLive = false;\n    this.emit(BeaconEvent.Destroy, this.identifier);\n  }\n\n  /**\n   * Monitor liveness of a beacon\n   * Emits BeaconEvent.LivenessChange when beacon expires\n   */\n  monitorLiveness() {\n    if (this.livenessWatchTimeout) {\n      clearTimeout(this.livenessWatchTimeout);\n    }\n    this.checkLiveness();\n    if (!this.beaconInfo) return;\n    if (this.isLive) {\n      var expiryInMs = this.beaconInfo.timestamp + this.beaconInfo.timeout - Date.now();\n      if (expiryInMs > 1) {\n        this.livenessWatchTimeout = setTimeout(() => {\n          this.monitorLiveness();\n        }, expiryInMs);\n      }\n    } else if (this.beaconInfo.timestamp > Date.now()) {\n      // beacon start timestamp is in the future\n      // check liveness again then\n      this.livenessWatchTimeout = setTimeout(() => {\n        this.monitorLiveness();\n      }, this.beaconInfo.timestamp - Date.now());\n    }\n  }\n\n  /**\n   * Process Beacon locations\n   * Emits BeaconEvent.LocationUpdate\n   */\n  addLocations(beaconLocationEvents) {\n    var _validLocationEvents$;\n    // discard locations for beacons that are not live\n    if (!this.isLive) {\n      return;\n    }\n    var validLocationEvents = beaconLocationEvents.filter(event => {\n      var content = event.getContent();\n      var parsed = parseBeaconContent(content);\n      if (!parsed.uri || !parsed.timestamp) return false; // we won't be able to process these\n      var {\n        timestamp\n      } = parsed;\n      return this._beaconInfo.timestamp &&\n      // only include positions that were taken inside the beacon's live period\n      isTimestampInDuration(this._beaconInfo.timestamp, this._beaconInfo.timeout, timestamp) && (\n      // ignore positions older than our current latest location\n      !this.latestLocationState || timestamp > this.latestLocationState.timestamp);\n    });\n    var latestLocationEvent = (_validLocationEvents$ = validLocationEvents.sort(sortEventsByLatestContentTimestamp)) === null || _validLocationEvents$ === void 0 ? void 0 : _validLocationEvents$[0];\n    if (latestLocationEvent) {\n      this._latestLocationEvent = latestLocationEvent;\n      this.emit(BeaconEvent.LocationUpdate, this.latestLocationState);\n    }\n  }\n  setBeaconInfo(event) {\n    this._beaconInfo = parseBeaconInfoContent(event.getContent());\n    this.checkLiveness();\n  }\n  checkLiveness() {\n    var prevLiveness = this.isLive;\n\n    // element web sets a beacon's start timestamp to the senders local current time\n    // when Alice's system clock deviates slightly from Bob's a beacon Alice intended to be live\n    // may have a start timestamp in the future from Bob's POV\n    // handle this by adding 6min of leniency to the start timestamp when it is in the future\n    if (!this.beaconInfo) return;\n    var startTimestamp = this.beaconInfo.timestamp > Date.now() ? this.beaconInfo.timestamp - 360000 /* 6min */ : this.beaconInfo.timestamp;\n    this._isLive = !!this._beaconInfo.live && !!startTimestamp && isTimestampInDuration(startTimestamp, this._beaconInfo.timeout, Date.now());\n    if (prevLiveness !== this.isLive) {\n      this.emit(BeaconEvent.LivenessChange, this.isLive, this);\n    }\n  }\n}\n//# sourceMappingURL=beacon.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// eslint-disable-next-line no-restricted-imports\n\nexport class ReEmitter {\n  constructor(target) {\n    this.target = target;\n    // Map from emitter to event name to re-emitter\n    _defineProperty(this, \"reEmitters\", new WeakMap());\n  }\n  reEmit(source, eventNames) {\n    var _this = this;\n    var reEmittersByEvent = this.reEmitters.get(source);\n    if (!reEmittersByEvent) {\n      reEmittersByEvent = new Map();\n      this.reEmitters.set(source, reEmittersByEvent);\n    }\n    var _loop = function _loop(eventName) {\n      if (reEmittersByEvent.has(eventName)) return 1; // continue\n\n      // We include the source as the last argument for event handlers which may need it,\n      // such as read receipt listeners on the client class which won't have the context\n      // of the room.\n      var forSource = function forSource() {\n        // EventEmitter special cases 'error' to make the emit function throw if no\n        // handler is attached, which sort of makes sense for making sure that something\n        // handles an error, but for re-emitting, there could be a listener on the original\n        // source object so the test doesn't really work. We *could* try to replicate the\n        // same logic and throw if there is no listener on either the source or the target,\n        // but this behaviour is fairly undesireable for us anyway: the main place we throw\n        // 'error' events is for calls, where error events are usually emitted some time\n        // later by a different part of the code where 'emit' throwing because the app hasn't\n        // added an error handler isn't terribly helpful. (A better fix in retrospect may\n        // have been to just avoid using the event name 'error', but backwards compat...)\n        if (eventName === \"error\" && _this.target.listenerCount(\"error\") === 0) return;\n        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n          args[_key] = arguments[_key];\n        }\n        _this.target.emit(eventName, ...args, source);\n      };\n      source.on(eventName, forSource);\n      reEmittersByEvent.set(eventName, forSource);\n    };\n    for (var eventName of eventNames) {\n      if (_loop(eventName)) continue;\n    }\n  }\n  stopReEmitting(source, eventNames) {\n    var reEmittersByEvent = this.reEmitters.get(source);\n    if (!reEmittersByEvent) return; // We were never re-emitting these events in the first place\n\n    for (var eventName of eventNames) {\n      source.off(eventName, reEmittersByEvent.get(eventName));\n      reEmittersByEvent.delete(eventName);\n    }\n    if (reEmittersByEvent.size === 0) this.reEmitters.delete(source);\n  }\n}\nexport class TypedReEmitter extends ReEmitter {\n  constructor(target) {\n    super(target);\n  }\n  reEmit(source, eventNames) {\n    super.reEmit(source, eventNames);\n  }\n  stopReEmitting(source, eventNames) {\n    super.stopReEmitting(source, eventNames);\n  }\n}\n//# sourceMappingURL=ReEmitter.js.map","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { UnstableValue } from \"../NamespacedValue.js\";\n/**\n * Beacon info and beacon event types as described in MSC3672\n * https://github.com/matrix-org/matrix-spec-proposals/pull/3672\n */\n\n/**\n * Beacon info events are state events.\n * We have two requirements for these events:\n * 1. they can only be written by their owner\n * 2. a user can have an arbitrary number of beacon_info events\n *\n * 1. is achieved by setting the state_key to the owners mxid.\n * Event keys in room state are a combination of `type` + `state_key`.\n * To achieve an arbitrary number of only owner-writable state events\n * we introduce a variable suffix to the event type\n *\n * @example\n * ```\n * {\n *      \"type\": \"m.beacon_info.@matthew:matrix.org.1\",\n *      \"state_key\": \"@matthew:matrix.org\",\n *      \"content\": {\n *          \"m.beacon_info\": {\n *              \"description\": \"The Matthew Tracker\",\n *              \"timeout\": 86400000,\n *          },\n *          // more content as described below\n *      }\n * },\n * {\n *      \"type\": \"m.beacon_info.@matthew:matrix.org.2\",\n *      \"state_key\": \"@matthew:matrix.org\",\n *      \"content\": {\n *          \"m.beacon_info\": {\n *              \"description\": \"Another different Matthew tracker\",\n *              \"timeout\": 400000,\n *          },\n *          // more content as described below\n *      }\n * }\n * ```\n */\n\n/**\n * Non-variable type for m.beacon_info event content\n */\nexport var M_BEACON_INFO = new UnstableValue(\"m.beacon_info\", \"org.matrix.msc3672.beacon_info\");\nexport var M_BEACON = new UnstableValue(\"m.beacon\", \"org.matrix.msc3672.beacon\");\n\n/**\n * m.beacon_info Event example from the spec\n * https://github.com/matrix-org/matrix-spec-proposals/pull/3672\n * @example\n * ```\n * {\n *   \"type\": \"m.beacon_info\",\n *   \"state_key\": \"@matthew:matrix.org\",\n *   \"content\": {\n *     \"m.beacon_info\": {\n *       \"description\": \"The Matthew Tracker\", // same as an `m.location` description\n *       \"timeout\": 86400000, // how long from the last event until we consider the beacon inactive in milliseconds\n *     },\n *     \"m.ts\": 1436829458432, // creation timestamp of the beacon on the client\n *     \"m.asset\": {\n *       \"type\": \"m.self\" // the type of asset being tracked as per MSC3488\n *     }\n *   }\n * }\n * ```\n */\n\n/**\n * m.beacon_info.* event content\n */\n\n/**\n * m.beacon event example\n * https://github.com/matrix-org/matrix-spec-proposals/pull/3672\n * @example\n * ```\n * {\n *   \"type\": \"m.beacon\",\n *   \"sender\": \"@matthew:matrix.org\",\n *   \"content\": {\n *       \"m.relates_to\": { // from MSC2674: https://github.com/matrix-org/matrix-doc/pull/2674\n *           \"rel_type\": \"m.reference\", // from MSC3267: https://github.com/matrix-org/matrix-doc/pull/3267\n *           \"event_id\": \"$beacon_info\"\n *       },\n *       \"m.location\": {\n *           \"uri\": \"geo:51.5008,0.1247;u=35\",\n *           \"description\": \"Arbitrary beacon information\"\n *       },\n *       \"m.ts\": 1636829458432,\n *   }\n * }\n * ```\n */\n\n/**\n * Content of an m.beacon event\n */\n//# sourceMappingURL=beacon.js.map","/*\nCopyright 2025 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Room versions strings that we know about and do not use hydra semantics.\n */\nvar PRE_HYDRA_ROOM_VERSIONS = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\"];\n\n/**\n * Checks if the given room version is one where new \"hydra\" power level\n * semantics (ie. room version 12 or later) should be used\n * (see https://github.com/matrix-org/matrix-spec-proposals/pull/4289).\n * This will return `false` for versions that are known to the js-sdk and\n * do not use hydra: any room versions unknown to the js-sdk (experimental or\n * otherwise) will cause the function to return true.\n *\n * @param roomVersion - The version of the room to check.\n * @returns `true` if hydra semantics should be used for the room version, `false` otherwise.\n */\nexport function shouldUseHydraForRoomVersion(roomVersion) {\n  return !PRE_HYDRA_ROOM_VERSIONS.includes(roomVersion);\n}\n//# sourceMappingURL=roomVersion.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { RoomMember } from \"./room-member.js\";\nimport { logger } from \"../logger.js\";\nimport { isNumber, removeHiddenChars } from \"../utils.js\";\nimport { EventType, UNSTABLE_MSC2716_MARKER } from \"../@types/event.js\";\nimport { MatrixEventEvent } from \"./event.js\";\nimport { GuestAccess, HistoryVisibility, JoinRule } from \"../@types/partials.js\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.js\";\nimport { Beacon, BeaconEvent, getBeaconInfoIdentifier } from \"./beacon.js\";\nimport { TypedReEmitter } from \"../ReEmitter.js\";\nimport { M_BEACON, M_BEACON_INFO } from \"../@types/beacon.js\";\nimport { KnownMembership } from \"../@types/membership.js\";\nimport { shouldUseHydraForRoomVersion } from \"../utils/roomVersion.js\";\n// possible statuses for out-of-band member loading\nvar OobStatus = /*#__PURE__*/function (OobStatus) {\n  OobStatus[OobStatus[\"NotStarted\"] = 0] = \"NotStarted\";\n  OobStatus[OobStatus[\"InProgress\"] = 1] = \"InProgress\";\n  OobStatus[OobStatus[\"Finished\"] = 2] = \"Finished\";\n  return OobStatus;\n}(OobStatus || {});\nexport var RoomStateEvent = /*#__PURE__*/function (RoomStateEvent) {\n  RoomStateEvent[\"Events\"] = \"RoomState.events\";\n  RoomStateEvent[\"Members\"] = \"RoomState.members\";\n  RoomStateEvent[\"NewMember\"] = \"RoomState.newMember\";\n  RoomStateEvent[\"Update\"] = \"RoomState.update\";\n  // signals batches of updates without specificity\n  RoomStateEvent[\"BeaconLiveness\"] = \"RoomState.BeaconLiveness\";\n  RoomStateEvent[\"Marker\"] = \"RoomState.Marker\";\n  return RoomStateEvent;\n}({});\nexport class RoomState extends TypedEventEmitter {\n  /**\n   * Construct room state.\n   *\n   * Room State represents the state of the room at a given point.\n   * It can be mutated by adding state events to it.\n   * There are two types of room member associated with a state event:\n   * normal member objects (accessed via getMember/getMembers) which mutate\n   * with the state to represent the current state of that room/user, e.g.\n   * the object returned by `getMember('@bob:example.com')` will mutate to\n   * get a different display name if Bob later changes his display name\n   * in the room.\n   * There are also 'sentinel' members (accessed via getSentinelMember).\n   * These also represent the state of room members at the point in time\n   * represented by the RoomState object, but unlike objects from getMember,\n   * sentinel objects will always represent the room state as at the time\n   * getSentinelMember was called, so if Bob subsequently changes his display\n   * name, a room member object previously acquired with getSentinelMember\n   * will still have his old display name. Calling getSentinelMember again\n   * after the display name change will return a new RoomMember object\n   * with Bob's new display name.\n   *\n   * @param roomId - Optional. The ID of the room which has this state.\n   * If none is specified it just tracks paginationTokens, useful for notifTimelineSet\n   * @param oobMemberFlags - Optional. The state of loading out of bound members.\n   * As the timeline might get reset while they are loading, this state needs to be inherited\n   * and shared when the room state is cloned for the new timeline.\n   * This should only be passed from clone.\n   */\n  constructor(roomId) {\n    var oobMemberFlags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n      status: OobStatus.NotStarted\n    };\n    super();\n    this.roomId = roomId;\n    this.oobMemberFlags = oobMemberFlags;\n    _defineProperty(this, \"reEmitter\", new TypedReEmitter(this));\n    _defineProperty(this, \"sentinels\", {});\n    // userId: RoomMember\n    // stores fuzzy matches to a list of userIDs (applies utils.removeHiddenChars to keys)\n    _defineProperty(this, \"displayNameToUserIds\", new Map());\n    _defineProperty(this, \"userIdsToDisplayNames\", {});\n    _defineProperty(this, \"tokenToInvite\", {});\n    // 3pid invite state_key to m.room.member invite\n    _defineProperty(this, \"joinedMemberCount\", null);\n    // cache of the number of joined members\n    // joined members count from summary api\n    // once set, we know the server supports the summary api\n    // and we should only trust that\n    // we could also only trust that before OOB members\n    // are loaded but doesn't seem worth the hassle atm\n    _defineProperty(this, \"summaryJoinedMemberCount\", null);\n    // same for invited member count\n    _defineProperty(this, \"invitedMemberCount\", null);\n    _defineProperty(this, \"summaryInvitedMemberCount\", null);\n    _defineProperty(this, \"modified\", -1);\n    // XXX: Should be read-only\n    // The room member dictionary, keyed on the user's ID.\n    _defineProperty(this, \"members\", {});\n    // userId: RoomMember\n    // The state events dictionary, keyed on the event type and then the state_key value.\n    _defineProperty(this, \"events\", new Map());\n    // Map<eventType, Map<stateKey, MatrixEvent>>\n    // The pagination token for this state.\n    _defineProperty(this, \"paginationToken\", null);\n    _defineProperty(this, \"beacons\", new Map());\n    _defineProperty(this, \"_liveBeaconIds\", []);\n    // We only wants to print warnings about bad room state once.\n    _defineProperty(this, \"getVersionWarning\", false);\n    this.updateModifiedTime();\n  }\n\n  /**\n   * Gets the version of the room\n   * @returns The version of the room\n   */\n  getRoomVersion() {\n    var _createEvent$getConte;\n    var createEvent = this.getStateEvents(EventType.RoomCreate, \"\");\n    if (!createEvent) {\n      if (!this.getVersionWarning) {\n        logger.warn(\"[getVersion] Room \" + this.roomId + \" does not have an m.room.create event\");\n        this.getVersionWarning = true;\n      }\n      return \"1\";\n    }\n    return (_createEvent$getConte = createEvent.getContent()[\"room_version\"]) !== null && _createEvent$getConte !== void 0 ? _createEvent$getConte : \"1\";\n  }\n\n  /**\n   * Returns the number of joined members in this room\n   * This method caches the result.\n   * @returns The number of members in this room whose membership is 'join'\n   */\n  getJoinedMemberCount() {\n    if (this.summaryJoinedMemberCount !== null) {\n      return this.summaryJoinedMemberCount;\n    }\n    if (this.joinedMemberCount === null) {\n      this.joinedMemberCount = this.getMembers().reduce((count, m) => {\n        return m.membership === KnownMembership.Join ? count + 1 : count;\n      }, 0);\n    }\n    return this.joinedMemberCount;\n  }\n\n  /**\n   * Set the joined member count explicitly (like from summary part of the sync response)\n   * @param count - the amount of joined members\n   */\n  setJoinedMemberCount(count) {\n    this.summaryJoinedMemberCount = count;\n  }\n\n  /**\n   * Returns the number of invited members in this room\n   * @returns The number of members in this room whose membership is 'invite'\n   */\n  getInvitedMemberCount() {\n    if (this.summaryInvitedMemberCount !== null) {\n      return this.summaryInvitedMemberCount;\n    }\n    if (this.invitedMemberCount === null) {\n      this.invitedMemberCount = this.getMembers().reduce((count, m) => {\n        return m.membership === KnownMembership.Invite ? count + 1 : count;\n      }, 0);\n    }\n    return this.invitedMemberCount;\n  }\n\n  /**\n   * Set the amount of invited members in this room\n   * @param count - the amount of invited members\n   */\n  setInvitedMemberCount(count) {\n    this.summaryInvitedMemberCount = count;\n  }\n\n  /**\n   * Get all RoomMembers in this room.\n   * @returns A list of RoomMembers.\n   */\n  getMembers() {\n    return Object.values(this.members);\n  }\n\n  /**\n   * Get all RoomMembers in this room, excluding the user IDs provided.\n   * @param excludedIds - The user IDs to exclude.\n   * @returns A list of RoomMembers.\n   */\n  getMembersExcept(excludedIds) {\n    return this.getMembers().filter(m => !excludedIds.includes(m.userId));\n  }\n\n  /**\n   * Get a room member by their user ID.\n   * @param userId - The room member's user ID.\n   * @returns The member or null if they do not exist.\n   */\n  getMember(userId) {\n    return this.members[userId] || null;\n  }\n\n  /**\n   * Get a room member whose properties will not change with this room state. You\n   * typically want this if you want to attach a RoomMember to a MatrixEvent which\n   * may no longer be represented correctly by Room.currentState or Room.oldState.\n   * The term 'sentinel' refers to the fact that this RoomMember is an unchanging\n   * guardian for state at this particular point in time.\n   * @param userId - The room member's user ID.\n   * @returns The member or null if they do not exist.\n   */\n  getSentinelMember(userId) {\n    if (!userId) return null;\n    var sentinel = this.sentinels[userId];\n    if (sentinel === undefined) {\n      sentinel = new RoomMember(this.roomId, userId);\n      var member = this.members[userId];\n      if (member !== null && member !== void 0 && member.events.member) {\n        sentinel.setMembershipEvent(member.events.member, this);\n      }\n      this.sentinels[userId] = sentinel;\n    }\n    return sentinel;\n  }\n\n  /**\n   * Get state events from the state of the room.\n   * @param eventType - The event type of the state event.\n   * @returns A list of events\n   */\n\n  /**\n   * Get state events from the state of the room.\n   * @param eventType - The event type of the state event.\n   * @param stateKey - The state_key of the state event.\n   * @returns A single event (or null if no match found).\n   */\n\n  getStateEvents(eventType, stateKey) {\n    if (!this.events.has(eventType)) {\n      // no match\n      return stateKey === undefined ? [] : null;\n    }\n    if (stateKey === undefined) {\n      // return all values\n      return Array.from(this.events.get(eventType).values());\n    }\n    var event = this.events.get(eventType).get(stateKey);\n    return event ? event : null;\n  }\n  get hasLiveBeacons() {\n    var _this$liveBeaconIds;\n    return !!((_this$liveBeaconIds = this.liveBeaconIds) !== null && _this$liveBeaconIds !== void 0 && _this$liveBeaconIds.length);\n  }\n  get liveBeaconIds() {\n    return this._liveBeaconIds;\n  }\n\n  /**\n   * Creates a copy of this room state so that mutations to either won't affect the other.\n   * @returns the copy of the room state\n   */\n  clone() {\n    var copy = new RoomState(this.roomId, this.oobMemberFlags);\n\n    // Ugly hack: because setStateEvents will mark\n    // members as susperseding future out of bound members\n    // if loading is in progress (through oobMemberFlags)\n    // since these are not new members, we're merely copying them\n    // set the status to not started\n    // after copying, we set back the status\n    var status = this.oobMemberFlags.status;\n    this.oobMemberFlags.status = OobStatus.NotStarted;\n    Array.from(this.events.values()).forEach(eventsByStateKey => {\n      copy.setStateEvents(Array.from(eventsByStateKey.values()));\n    });\n\n    // Ugly hack: see above\n    this.oobMemberFlags.status = status;\n    if (this.summaryInvitedMemberCount !== null) {\n      copy.setInvitedMemberCount(this.getInvitedMemberCount());\n    }\n    if (this.summaryJoinedMemberCount !== null) {\n      copy.setJoinedMemberCount(this.getJoinedMemberCount());\n    }\n\n    // copy out of band flags if needed\n    if (this.oobMemberFlags.status == OobStatus.Finished) {\n      // copy markOutOfBand flags\n      this.getMembers().forEach(member => {\n        if (member.isOutOfBand()) {\n          var _copy$getMember;\n          (_copy$getMember = copy.getMember(member.userId)) === null || _copy$getMember === void 0 || _copy$getMember.markOutOfBand();\n        }\n      });\n    }\n    return copy;\n  }\n\n  /**\n   * Add previously unknown state events.\n   * When lazy loading members while back-paginating,\n   * the relevant room state for the timeline chunk at the end\n   * of the chunk can be set with this method.\n   * @param events - state events to prepend\n   */\n  setUnknownStateEvents(events) {\n    var unknownStateEvents = events.filter(event => {\n      return !this.events.has(event.getType()) || !this.events.get(event.getType()).has(event.getStateKey());\n    });\n    this.setStateEvents(unknownStateEvents);\n  }\n\n  /**\n   * Add an array of one or more state MatrixEvents, overwriting any existing\n   * state with the same `{type, stateKey}` tuple. Will fire \"RoomState.events\"\n   * for every event added. May fire \"RoomState.members\" if there are\n   * `m.room.member` events. May fire \"RoomStateEvent.Marker\" if there are\n   * `UNSTABLE_MSC2716_MARKER` events.\n   * @param stateEvents - a list of state events for this room.\n   *\n   * @remarks\n   * Fires {@link RoomStateEvent.Members}\n   * Fires {@link RoomStateEvent.NewMember}\n   * Fires {@link RoomStateEvent.Events}\n   * Fires {@link RoomStateEvent.Marker}\n   */\n  setStateEvents(stateEvents, markerFoundOptions) {\n    this.updateModifiedTime();\n\n    // update the core event dict\n    stateEvents.forEach(event => {\n      if (event.getRoomId() !== this.roomId || !event.isState()) return;\n      if (M_BEACON_INFO.matches(event.getType())) {\n        this.setBeacon(event);\n      }\n      var lastStateEvent = this.getStateEventMatching(event);\n      this.setStateEvent(event);\n      if (event.getType() === EventType.RoomMember) {\n        var _event$getContent$dis;\n        this.updateDisplayNameCache(event.getStateKey(), (_event$getContent$dis = event.getContent().displayname) !== null && _event$getContent$dis !== void 0 ? _event$getContent$dis : \"\");\n        this.updateThirdPartyTokenCache(event);\n      }\n      this.emit(RoomStateEvent.Events, event, this, lastStateEvent);\n    });\n    this.onBeaconLivenessChange();\n    // update higher level data structures. This needs to be done AFTER the\n    // core event dict as these structures may depend on other state events in\n    // the given array (e.g. disambiguating display names in one go to do both\n    // clashing names rather than progressively which only catches 1 of them).\n    stateEvents.forEach(event => {\n      if (event.getRoomId() !== this.roomId || !event.isState()) return;\n      if (event.getType() === EventType.RoomMember) {\n        var userId = event.getStateKey();\n\n        // leave events apparently elide the displayname or avatar_url,\n        // so let's fake one up so that we don't leak user ids\n        // into the timeline\n        if (event.getContent().membership === KnownMembership.Leave || event.getContent().membership === KnownMembership.Ban) {\n          event.getContent().avatar_url = event.getContent().avatar_url || event.getPrevContent().avatar_url;\n          event.getContent().displayname = event.getContent().displayname || event.getPrevContent().displayname;\n        }\n        var member = this.getOrCreateMember(userId, event);\n        member.setMembershipEvent(event, this);\n        this.updateMember(member);\n        this.emit(RoomStateEvent.Members, event, this, member);\n      } else if (event.getType() === EventType.RoomPowerLevels) {\n        // events with unknown state keys should be ignored\n        // and should not aggregate onto members power levels\n        if (event.getStateKey() !== \"\") {\n          return;\n        }\n        var members = Object.values(this.members);\n        var createEvent = this.getStateEvents(EventType.RoomCreate, \"\");\n        var creators = getCreators(this.getRoomVersion(), createEvent);\n        members.forEach(member => {\n          // We only propagate `RoomState.members` event if the\n          // power levels has been changed\n          // large room suffer from large re-rendering especially when not needed\n          var oldLastModified = member.getLastModifiedTime();\n          if (createEvent) {\n            var pl = powerLevelForUserId(member.userId, event, creators);\n            member.setPowerLevel(pl, event);\n          }\n          if (oldLastModified !== member.getLastModifiedTime()) {\n            this.emit(RoomStateEvent.Members, event, this, member);\n          }\n        });\n\n        // assume all our sentinels are now out-of-date\n        this.sentinels = {};\n      } else if (UNSTABLE_MSC2716_MARKER.matches(event.getType())) {\n        this.emit(RoomStateEvent.Marker, event, markerFoundOptions);\n      }\n    });\n    this.emit(RoomStateEvent.Update, this);\n  }\n  processBeaconEvents(events, matrixClient) {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      if (!events.length ||\n      // discard locations if we have no beacons\n      !_this.beacons.size) {\n        return;\n      }\n      var beaconByEventIdDict = [..._this.beacons.values()].reduce((dict, beacon) => {\n        dict[beacon.beaconInfoId] = beacon;\n        return dict;\n      }, {});\n      var processBeaconRelation = (beaconInfoEventId, event) => {\n        if (!M_BEACON.matches(event.getType())) {\n          return;\n        }\n        var beacon = beaconByEventIdDict[beaconInfoEventId];\n        if (beacon) {\n          beacon.addLocations([event]);\n        }\n      };\n      var _loop = function* _loop(event) {\n          var _event$getRelation;\n          var relatedToEventId = (_event$getRelation = event.getRelation()) === null || _event$getRelation === void 0 ? void 0 : _event$getRelation.event_id;\n          // not related to a beacon we know about; discard\n          if (!relatedToEventId || !beaconByEventIdDict[relatedToEventId]) return {\n            v: void 0\n          };\n          if (!M_BEACON.matches(event.getType()) && !event.isEncrypted()) return {\n            v: void 0\n          };\n          try {\n            yield matrixClient.decryptEventIfNeeded(event);\n            processBeaconRelation(relatedToEventId, event);\n          } catch (_unused) {\n            if (event.isDecryptionFailure()) {\n              // add an event listener for once the event is decrypted.\n              event.once(MatrixEventEvent.Decrypted, /*#__PURE__*/_asyncToGenerator(function* () {\n                processBeaconRelation(relatedToEventId, event);\n              }));\n            }\n          }\n        },\n        _ret;\n      for (var event of events) {\n        _ret = yield* _loop(event);\n        if (_ret) return _ret.v;\n      }\n    })();\n  }\n\n  /**\n   * Looks up a member by the given userId, and if it doesn't exist,\n   * create it and emit the `RoomState.newMember` event.\n   * This method makes sure the member is added to the members dictionary\n   * before emitting, as this is done from setStateEvents and setOutOfBandMember.\n   * @param userId - the id of the user to look up\n   * @param event - the membership event for the (new) member. Used to emit.\n   * @returns the member, existing or newly created.\n   *\n   * @remarks\n   * Fires {@link RoomStateEvent.NewMember}\n   */\n  getOrCreateMember(userId, event) {\n    var member = this.members[userId];\n    if (!member) {\n      member = new RoomMember(this.roomId, userId);\n      // add member to members before emitting any events,\n      // as event handlers often lookup the member\n      this.members[userId] = member;\n      this.emit(RoomStateEvent.NewMember, event, this, member);\n    }\n    return member;\n  }\n  setStateEvent(event) {\n    if (!this.events.has(event.getType())) {\n      this.events.set(event.getType(), new Map());\n    }\n    this.events.get(event.getType()).set(event.getStateKey(), event);\n  }\n\n  /**\n   * @experimental\n   */\n  setBeacon(event) {\n    var beaconIdentifier = getBeaconInfoIdentifier(event);\n    if (this.beacons.has(beaconIdentifier)) {\n      var _beacon = this.beacons.get(beaconIdentifier);\n      if (event.isRedacted()) {\n        var _event$getRedactionEv;\n        if (_beacon.beaconInfoId === ((_event$getRedactionEv = event.getRedactionEvent()) === null || _event$getRedactionEv === void 0 ? void 0 : _event$getRedactionEv.redacts)) {\n          _beacon.destroy();\n          this.beacons.delete(beaconIdentifier);\n        }\n        return;\n      }\n      return _beacon.update(event);\n    }\n    if (event.isRedacted()) {\n      return;\n    }\n    var beacon = new Beacon(event);\n    this.reEmitter.reEmit(beacon, [BeaconEvent.New, BeaconEvent.Update, BeaconEvent.Destroy, BeaconEvent.LivenessChange]);\n    this.emit(BeaconEvent.New, event, beacon);\n    beacon.on(BeaconEvent.LivenessChange, this.onBeaconLivenessChange.bind(this));\n    beacon.on(BeaconEvent.Destroy, this.onBeaconLivenessChange.bind(this));\n    this.beacons.set(beacon.identifier, beacon);\n  }\n\n  /**\n   * @experimental\n   * Check liveness of room beacons\n   * emit RoomStateEvent.BeaconLiveness event\n   */\n  onBeaconLivenessChange() {\n    this._liveBeaconIds = Array.from(this.beacons.values()).filter(beacon => beacon.isLive).map(beacon => beacon.identifier);\n    this.emit(RoomStateEvent.BeaconLiveness, this, this.hasLiveBeacons);\n  }\n  getStateEventMatching(event) {\n    var _this$events$get$get, _this$events$get;\n    return (_this$events$get$get = (_this$events$get = this.events.get(event.getType())) === null || _this$events$get === void 0 ? void 0 : _this$events$get.get(event.getStateKey())) !== null && _this$events$get$get !== void 0 ? _this$events$get$get : null;\n  }\n  updateMember(member) {\n    // this member may have a power level already, so set it.\n    var createEvent = this.getStateEvents(EventType.RoomCreate, \"\");\n    var pwrLvlEvent = this.getStateEvents(EventType.RoomPowerLevels, \"\");\n    if (pwrLvlEvent && createEvent) {\n      var powerLevel = powerLevelForUserId(member.userId, pwrLvlEvent, getCreators(this.getRoomVersion(), createEvent));\n      member.setPowerLevel(powerLevel, pwrLvlEvent);\n    }\n\n    // blow away the sentinel which is now outdated\n    delete this.sentinels[member.userId];\n    this.members[member.userId] = member;\n    this.joinedMemberCount = null;\n    this.invitedMemberCount = null;\n  }\n\n  /**\n   * Get the out-of-band members loading state, whether loading is needed or not.\n   * Note that loading might be in progress and hence isn't needed.\n   * @returns whether or not the members of this room need to be loaded\n   */\n  needsOutOfBandMembers() {\n    return this.oobMemberFlags.status === OobStatus.NotStarted;\n  }\n\n  /**\n   * Check if loading of out-of-band-members has completed\n   *\n   * @returns true if the full membership list of this room has been loaded. False if it is not started or is in\n   *    progress.\n   */\n  outOfBandMembersReady() {\n    return this.oobMemberFlags.status === OobStatus.Finished;\n  }\n\n  /**\n   * Mark this room state as waiting for out-of-band members,\n   * ensuring it doesn't ask for them to be requested again\n   * through needsOutOfBandMembers\n   */\n  markOutOfBandMembersStarted() {\n    if (this.oobMemberFlags.status !== OobStatus.NotStarted) {\n      return;\n    }\n    this.oobMemberFlags.status = OobStatus.InProgress;\n  }\n\n  /**\n   * Mark this room state as having failed to fetch out-of-band members\n   */\n  markOutOfBandMembersFailed() {\n    if (this.oobMemberFlags.status !== OobStatus.InProgress) {\n      return;\n    }\n    this.oobMemberFlags.status = OobStatus.NotStarted;\n  }\n\n  /**\n   * Clears the loaded out-of-band members\n   */\n  clearOutOfBandMembers() {\n    var count = 0;\n    Object.keys(this.members).forEach(userId => {\n      var member = this.members[userId];\n      if (member.isOutOfBand()) {\n        ++count;\n        delete this.members[userId];\n      }\n    });\n    logger.log(\"LL: RoomState removed \".concat(count, \" members...\"));\n    this.oobMemberFlags.status = OobStatus.NotStarted;\n  }\n\n  /**\n   * Sets the loaded out-of-band members.\n   * @param stateEvents - array of membership state events\n   */\n  setOutOfBandMembers(stateEvents) {\n    logger.log(\"LL: RoomState about to set \".concat(stateEvents.length, \" OOB members ...\"));\n    if (this.oobMemberFlags.status !== OobStatus.InProgress) {\n      return;\n    }\n    logger.log(\"LL: RoomState put in finished state ...\");\n    this.oobMemberFlags.status = OobStatus.Finished;\n    stateEvents.forEach(e => this.setOutOfBandMember(e));\n    this.emit(RoomStateEvent.Update, this);\n  }\n\n  /**\n   * Sets a single out of band member, used by both setOutOfBandMembers and clone\n   * @param stateEvent - membership state event\n   */\n  setOutOfBandMember(stateEvent) {\n    if (stateEvent.getType() !== EventType.RoomMember) {\n      return;\n    }\n    var userId = stateEvent.getStateKey();\n    var existingMember = this.getMember(userId);\n    // never replace members received as part of the sync\n    if (existingMember && !existingMember.isOutOfBand()) {\n      return;\n    }\n    var member = this.getOrCreateMember(userId, stateEvent);\n    member.setMembershipEvent(stateEvent, this);\n    // needed to know which members need to be stored seperately\n    // as they are not part of the sync accumulator\n    // this is cleared by setMembershipEvent so when it's updated through /sync\n    member.markOutOfBand();\n    this.updateDisplayNameCache(member.userId, member.name);\n    this.setStateEvent(stateEvent);\n    this.updateMember(member);\n    this.emit(RoomStateEvent.Members, stateEvent, this, member);\n  }\n\n  /**\n   * Set the current typing event for this room.\n   * @param event - The typing event\n   */\n  setTypingEvent(event) {\n    Object.values(this.members).forEach(function (member) {\n      member.setTypingEvent(event);\n    });\n  }\n\n  /**\n   * Get the m.room.member event which has the given third party invite token.\n   *\n   * @param token - The token\n   * @returns The m.room.member event or null\n   */\n  getInviteForThreePidToken(token) {\n    return this.tokenToInvite[token] || null;\n  }\n\n  /**\n   * Update the last modified time to the current time.\n   */\n  updateModifiedTime() {\n    this.modified = Date.now();\n  }\n\n  /**\n   * Get the timestamp when this room state was last updated. This timestamp is\n   * updated when this object has received new state events.\n   * @returns The timestamp\n   */\n  getLastModifiedTime() {\n    return this.modified;\n  }\n\n  /**\n   * Get user IDs with the specified or similar display names.\n   * @param displayName - The display name to get user IDs from.\n   * @returns An array of user IDs or an empty array.\n   */\n  getUserIdsWithDisplayName(displayName) {\n    var _this$displayNameToUs;\n    return (_this$displayNameToUs = this.displayNameToUserIds.get(removeHiddenChars(displayName))) !== null && _this$displayNameToUs !== void 0 ? _this$displayNameToUs : [];\n  }\n\n  /**\n   * Returns true if userId is in room, event is not redacted and either sender of\n   * mxEvent or has power level sufficient to redact events other than their own.\n   * @param mxEvent - The event to test permission for\n   * @param userId - The user ID of the user to test permission for\n   * @returns true if the given used ID can redact given event\n   */\n  maySendRedactionForEvent(mxEvent, userId) {\n    var member = this.getMember(userId);\n    if (!member || member.membership === KnownMembership.Leave) return false;\n    if (mxEvent.status || mxEvent.isRedacted()) return false;\n\n    // The user may have been the sender, but they can't redact their own message\n    // if redactions are blocked.\n    var canRedact = this.maySendEvent(EventType.RoomRedaction, userId);\n    if (!canRedact) return false;\n    if (mxEvent.getSender() === userId) return true;\n    return this.hasSufficientPowerLevelFor(\"redact\", member.powerLevel);\n  }\n\n  /**\n   * Returns true if the given power level is sufficient for action\n   * @param action - The type of power level to check\n   * @param powerLevel - The power level of the member\n   * @returns true if the given power level is sufficient\n   */\n  hasSufficientPowerLevelFor(action, powerLevel) {\n    var powerLevelsEvent = this.getStateEvents(EventType.RoomPowerLevels, \"\");\n    var powerLevels = {};\n    if (powerLevelsEvent) {\n      powerLevels = powerLevelsEvent.getContent();\n    }\n    var requiredLevel = 50;\n    if (isNumber(powerLevels[action])) {\n      requiredLevel = powerLevels[action];\n    }\n    return powerLevel >= requiredLevel;\n  }\n\n  /**\n   * Short-form for maySendEvent('m.room.message', userId)\n   * @param userId - The user ID of the user to test permission for\n   * @returns true if the given user ID should be permitted to send\n   *                   message events into the given room.\n   */\n  maySendMessage(userId) {\n    return this.maySendEventOfType(EventType.RoomMessage, userId, false);\n  }\n\n  /**\n   * Returns true if the given user ID has permission to send a normal\n   * event of type `eventType` into this room.\n   * @param eventType - The type of event to test\n   * @param userId - The user ID of the user to test permission for\n   * @returns true if the given user ID should be permitted to send\n   *                        the given type of event into this room,\n   *                        according to the room's state.\n   */\n  maySendEvent(eventType, userId) {\n    return this.maySendEventOfType(eventType, userId, false);\n  }\n\n  /**\n   * Returns true if the given MatrixClient has permission to send a state\n   * event of type `stateEventType` into this room.\n   * @param stateEventType - The type of state events to test\n   * @param cli - The client to test permission for\n   * @returns true if the given client should be permitted to send\n   *                        the given type of state event into this room,\n   *                        according to the room's state.\n   */\n  mayClientSendStateEvent(stateEventType, cli) {\n    if (cli.isGuest() || !cli.credentials.userId) {\n      return false;\n    }\n    return this.maySendStateEvent(stateEventType, cli.credentials.userId);\n  }\n\n  /**\n   * Returns true if the given user ID has permission to send a state\n   * event of type `stateEventType` into this room.\n   * @param stateEventType - The type of state events to test\n   * @param userId - The user ID of the user to test permission for\n   * @returns true if the given user ID should be permitted to send\n   *                        the given type of state event into this room,\n   *                        according to the room's state.\n   */\n  maySendStateEvent(stateEventType, userId) {\n    return this.maySendEventOfType(stateEventType, userId, true);\n  }\n\n  /**\n   * Returns true if the given user ID has permission to send a normal or state\n   * event of type `eventType` into this room.\n   * @param eventType - The type of event to test\n   * @param userId - The user ID of the user to test permission for\n   * @param state - If true, tests if the user may send a state\n   event of this type. Otherwise tests whether\n   they may send a regular event.\n   * @returns true if the given user ID should be permitted to send\n   *                        the given type of event into this room,\n   *                        according to the room's state.\n   */\n  maySendEventOfType(eventType, userId, state) {\n    var _roomMember$powerLeve;\n    var powerLevelsEvent = this.getStateEvents(EventType.RoomPowerLevels, \"\");\n    var powerLevels;\n    var eventsLevels = {};\n    var stateDefault = 0;\n    var eventsDefault = 0;\n    if (powerLevelsEvent) {\n      powerLevels = powerLevelsEvent.getContent();\n      eventsLevels = powerLevels.events || {};\n      if (Number.isSafeInteger(powerLevels.state_default)) {\n        stateDefault = powerLevels.state_default;\n      } else {\n        stateDefault = 50;\n      }\n      if (Number.isSafeInteger(powerLevels.events_default)) {\n        eventsDefault = powerLevels.events_default;\n      }\n    }\n    var requiredLevel = state ? stateDefault : eventsDefault;\n    if (Number.isSafeInteger(eventsLevels[eventType])) {\n      requiredLevel = eventsLevels[eventType];\n    }\n    var roomMember = this.getMember(userId);\n    var userPowerLevel = (_roomMember$powerLeve = roomMember === null || roomMember === void 0 ? void 0 : roomMember.powerLevel) !== null && _roomMember$powerLeve !== void 0 ? _roomMember$powerLeve : 0;\n    return userPowerLevel >= requiredLevel;\n  }\n\n  /**\n   * Returns true if the given user ID has permission to trigger notification\n   * of type `notifLevelKey`\n   * @param notifLevelKey - The level of notification to test (eg. 'room')\n   * @param userId - The user ID of the user to test permission for\n   * @returns true if the given user ID has permission to trigger a\n   *                        notification of this type.\n   */\n  mayTriggerNotifOfType(notifLevelKey, userId) {\n    var member = this.getMember(userId);\n    if (!member) {\n      return false;\n    }\n    var powerLevelsEvent = this.getStateEvents(EventType.RoomPowerLevels, \"\");\n    var notifLevel = 50;\n    if (powerLevelsEvent && powerLevelsEvent.getContent() && powerLevelsEvent.getContent().notifications && isNumber(powerLevelsEvent.getContent().notifications[notifLevelKey])) {\n      notifLevel = powerLevelsEvent.getContent().notifications[notifLevelKey];\n    }\n    return member.powerLevel >= notifLevel;\n  }\n\n  /**\n   * Returns the join rule based on the m.room.join_rule state event, defaulting to `invite`.\n   * @returns the join_rule applied to this room\n   */\n  getJoinRule() {\n    var _joinRuleEvent$getCon;\n    var joinRuleEvent = this.getStateEvents(EventType.RoomJoinRules, \"\");\n    var joinRuleContent = (_joinRuleEvent$getCon = joinRuleEvent === null || joinRuleEvent === void 0 ? void 0 : joinRuleEvent.getContent()) !== null && _joinRuleEvent$getCon !== void 0 ? _joinRuleEvent$getCon : {};\n    return joinRuleContent[\"join_rule\"] || JoinRule.Invite;\n  }\n\n  /**\n   * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.\n   * @returns the history_visibility applied to this room\n   */\n  getHistoryVisibility() {\n    var _historyVisibilityEve;\n    var historyVisibilityEvent = this.getStateEvents(EventType.RoomHistoryVisibility, \"\");\n    var historyVisibilityContent = (_historyVisibilityEve = historyVisibilityEvent === null || historyVisibilityEvent === void 0 ? void 0 : historyVisibilityEvent.getContent()) !== null && _historyVisibilityEve !== void 0 ? _historyVisibilityEve : {};\n    return historyVisibilityContent[\"history_visibility\"] || HistoryVisibility.Shared;\n  }\n\n  /**\n   * Returns the guest access based on the m.room.guest_access state event, defaulting to `shared`.\n   * @returns the guest_access applied to this room\n   */\n  getGuestAccess() {\n    var _guestAccessEvent$get;\n    var guestAccessEvent = this.getStateEvents(EventType.RoomGuestAccess, \"\");\n    var guestAccessContent = (_guestAccessEvent$get = guestAccessEvent === null || guestAccessEvent === void 0 ? void 0 : guestAccessEvent.getContent()) !== null && _guestAccessEvent$get !== void 0 ? _guestAccessEvent$get : {};\n    return guestAccessContent[\"guest_access\"] || GuestAccess.Forbidden;\n  }\n\n  /**\n   * Find the predecessor room based on this room state.\n   *\n   * @param msc3946ProcessDynamicPredecessor - if true, look for an\n   * m.room.predecessor state event and use it if found (MSC3946).\n   * @returns null if this room has no predecessor. Otherwise, returns\n   * the roomId, last eventId and viaServers of the predecessor room.\n   *\n   * If msc3946ProcessDynamicPredecessor is true, use m.predecessor events\n   * as well as m.room.create events to find predecessors.\n   *\n   * Note: if an m.predecessor event is used, eventId may be undefined\n   * since last_known_event_id is optional.\n   *\n   * Note: viaServers may be undefined, and will definitely be undefined if\n   * this predecessor comes from a RoomCreate event (rather than a\n   * RoomPredecessor, which has the optional via_servers property).\n   */\n  findPredecessor() {\n    var msc3946ProcessDynamicPredecessor = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n    // Note: the tests for this function are against Room.findPredecessor,\n    // which just calls through to here.\n\n    if (msc3946ProcessDynamicPredecessor) {\n      var predecessorEvent = this.getStateEvents(EventType.RoomPredecessor, \"\");\n      if (predecessorEvent) {\n        var content = predecessorEvent.getContent();\n        var _roomId = content.predecessor_room_id;\n        var eventId = content.last_known_event_id;\n        if (typeof eventId !== \"string\") {\n          eventId = undefined;\n        }\n        var viaServers = content.via_servers;\n        if (!Array.isArray(viaServers)) {\n          viaServers = undefined;\n        }\n        if (typeof _roomId === \"string\") {\n          return {\n            roomId: _roomId,\n            eventId,\n            viaServers\n          };\n        }\n      }\n    }\n    var createEvent = this.getStateEvents(EventType.RoomCreate, \"\");\n    if (createEvent) {\n      var predecessor = createEvent.getContent()[\"predecessor\"];\n      if (predecessor) {\n        var _roomId2 = predecessor[\"room_id\"];\n        if (typeof _roomId2 === \"string\") {\n          var _eventId = predecessor[\"event_id\"];\n          if (typeof _eventId !== \"string\" || _eventId === \"\") {\n            _eventId = undefined;\n          }\n          return {\n            roomId: _roomId2,\n            eventId: _eventId\n          };\n        }\n      }\n    }\n    return null;\n  }\n  updateThirdPartyTokenCache(memberEvent) {\n    if (!memberEvent.getContent().third_party_invite) {\n      return;\n    }\n    var token = (memberEvent.getContent().third_party_invite.signed || {}).token;\n    if (!token) {\n      return;\n    }\n    var threePidInvite = this.getStateEvents(EventType.RoomThirdPartyInvite, token);\n    if (!threePidInvite) {\n      return;\n    }\n    this.tokenToInvite[token] = memberEvent;\n  }\n  updateDisplayNameCache(userId, displayName) {\n    var oldName = this.userIdsToDisplayNames[userId];\n    delete this.userIdsToDisplayNames[userId];\n    if (oldName) {\n      // Remove the old name from the cache.\n      // We clobber the user_id > name lookup but the name -> [user_id] lookup\n      // means we need to remove that user ID from that array rather than nuking\n      // the lot.\n      var strippedOldName = removeHiddenChars(oldName);\n      var existingUserIds = this.displayNameToUserIds.get(strippedOldName);\n      if (existingUserIds) {\n        // remove this user ID from this array\n        var filteredUserIDs = existingUserIds.filter(id => id !== userId);\n        this.displayNameToUserIds.set(strippedOldName, filteredUserIDs);\n      }\n    }\n    this.userIdsToDisplayNames[userId] = displayName;\n    var strippedDisplayname = displayName && removeHiddenChars(displayName);\n    // an empty stripped displayname (undefined/'') will be set to MXID in room-member.js\n    if (strippedDisplayname) {\n      var _this$displayNameToUs2;\n      var arr = (_this$displayNameToUs2 = this.displayNameToUserIds.get(strippedDisplayname)) !== null && _this$displayNameToUs2 !== void 0 ? _this$displayNameToUs2 : [];\n      arr.push(userId);\n      this.displayNameToUserIds.set(strippedDisplayname, arr);\n    }\n  }\n}\n\n/**\n * Get the set of creator user IDs for a room: empty if the room is not a 'hydra' room, otherwise\n * computed from the sender of the m.room.create event plus the additional_creators field.\n * @param roomVersion The version of the room\n * @param roomCreateEvent The m.room.create event for the room\n * @returns A set of user IDs of the creators of the room.\n */\nfunction getCreators(roomVersion, roomCreateEvent) {\n  var creators = new Set();\n  if (shouldUseHydraForRoomVersion(roomVersion) && roomCreateEvent) {\n    var roomCreateSender = roomCreateEvent.getSender();\n    if (roomCreateSender) creators.add(roomCreateSender);\n    var additionalCreators = roomCreateEvent.getDirectionalContent().additional_creators;\n    if (Array.isArray(additionalCreators)) additionalCreators.forEach(c => creators.add(c));\n  }\n  return creators;\n}\n\n/**\n *\n * @param userId The user ID to compute the power level for\n * @param powerLevelEvents The power level event for the room\n * @param creators The set of creator user IDs for the room if the room is a 'hydra' room, otherwise the empty set.\n */\nfunction powerLevelForUserId(userId, powerLevelEvent, creators) {\n  if (creators.has(userId)) {\n    // As of \"Hydra\", If the user is a creator, they always have the highest power level\n    return Infinity;\n  } else {\n    var evContent = powerLevelEvent.getDirectionalContent();\n    var users = evContent.users || {};\n    if (users[userId] !== undefined && Number.isInteger(users[userId])) {\n      return users[userId];\n    } else if (evContent.users_default !== undefined) {\n      return evContent.users_default;\n    } else {\n      return 0;\n    }\n  }\n}\n//# sourceMappingURL=room-state.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { RoomState } from \"./room-state.js\";\nimport { EventType } from \"../@types/event.js\";\nexport var Direction = /*#__PURE__*/function (Direction) {\n  Direction[\"Backward\"] = \"b\";\n  Direction[\"Forward\"] = \"f\";\n  return Direction;\n}({});\nexport class EventTimeline {\n  /**\n   * Static helper method to set sender and target properties\n   *\n   * @param event -   the event whose metadata is to be set\n   * @param stateContext -  the room state to be queried\n   * @param toStartOfTimeline -  if true the event's forwardLooking flag is set false\n   */\n  static setEventMetadata(event, stateContext, toStartOfTimeline) {\n    event.setMetadata(stateContext, toStartOfTimeline);\n  }\n  /**\n   * Construct a new EventTimeline\n   *\n   * <p>An EventTimeline represents a contiguous sequence of events in a room.\n   *\n   * <p>As well as keeping track of the events themselves, it stores the state of\n   * the room at the beginning and end of the timeline, and pagination tokens for\n   * going backwards and forwards in the timeline.\n   *\n   * <p>In order that clients can meaningfully maintain an index into a timeline,\n   * the EventTimeline object tracks a 'baseIndex'. This starts at zero, but is\n   * incremented when events are prepended to the timeline. The index of an event\n   * relative to baseIndex therefore remains constant.\n   *\n   * <p>Once a timeline joins up with its neighbour, they are linked together into a\n   * doubly-linked list.\n   *\n   * @param eventTimelineSet - the set of timelines this is part of\n   */\n  constructor(eventTimelineSet) {\n    var _eventTimelineSet$roo, _eventTimelineSet$roo2;\n    this.eventTimelineSet = eventTimelineSet;\n    _defineProperty(this, \"roomId\", void 0);\n    _defineProperty(this, \"name\", void 0);\n    _defineProperty(this, \"events\", []);\n    _defineProperty(this, \"baseIndex\", 0);\n    _defineProperty(this, \"startState\", void 0);\n    _defineProperty(this, \"endState\", void 0);\n    // If we have a roomId then we delegate pagination token storage to the room state objects `startState` and\n    // `endState`, but for things like the notification timeline which mix multiple rooms we store the tokens ourselves.\n    _defineProperty(this, \"startToken\", null);\n    _defineProperty(this, \"endToken\", null);\n    _defineProperty(this, \"prevTimeline\", null);\n    _defineProperty(this, \"nextTimeline\", null);\n    _defineProperty(this, \"paginationRequests\", {\n      [Direction.Backward]: null,\n      [Direction.Forward]: null\n    });\n    this.roomId = (_eventTimelineSet$roo = (_eventTimelineSet$roo2 = eventTimelineSet.room) === null || _eventTimelineSet$roo2 === void 0 ? void 0 : _eventTimelineSet$roo2.roomId) !== null && _eventTimelineSet$roo !== void 0 ? _eventTimelineSet$roo : null;\n    if (this.roomId) {\n      this.startState = new RoomState(this.roomId);\n      this.endState = new RoomState(this.roomId);\n    }\n\n    // this is used by client.js\n    this.paginationRequests = {\n      b: null,\n      f: null\n    };\n    this.name = this.roomId + \":\" + new Date().toISOString();\n  }\n\n  /**\n   * Initialise the start and end state with the given events\n   *\n   * <p>This can only be called before any events are added.\n   *\n   * @param stateEvents - list of state events to initialise the\n   * state with.\n   * @throws Error if an attempt is made to call this after addEvent is called.\n   */\n  initialiseState(stateEvents) {\n    var _this$startState, _this$endState;\n    var {\n      timelineWasEmpty\n    } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    if (this.events.length > 0) {\n      throw new Error(\"Cannot initialise state after events are added\");\n    }\n    (_this$startState = this.startState) === null || _this$startState === void 0 || _this$startState.setStateEvents(stateEvents, {\n      timelineWasEmpty\n    });\n    (_this$endState = this.endState) === null || _this$endState === void 0 || _this$endState.setStateEvents(stateEvents, {\n      timelineWasEmpty\n    });\n  }\n\n  /**\n   * Forks the (live) timeline, taking ownership of the existing directional state of this timeline.\n   * All attached listeners will keep receiving state updates from the new live timeline state.\n   * The end state of this timeline gets replaced with an independent copy of the current RoomState,\n   * and will need a new pagination token if it ever needs to paginate forwards.\n    * @param direction -   EventTimeline.BACKWARDS to get the state at the\n   *   start of the timeline; EventTimeline.FORWARDS to get the state at the end\n   *   of the timeline.\n   *\n   * @returns the new timeline\n   */\n  forkLive(direction) {\n    var forkState = this.getState(direction);\n    var timeline = new EventTimeline(this.eventTimelineSet);\n    timeline.startState = forkState === null || forkState === void 0 ? void 0 : forkState.clone();\n    // Now clobber the end state of the new live timeline with that from the\n    // previous live timeline. It will be identical except that we'll keep\n    // using the same RoomMember objects for the 'live' set of members with any\n    // listeners still attached\n    timeline.endState = forkState;\n    // Firstly, we just stole the current timeline's end state, so it needs a new one.\n    // Make an immutable copy of the state so back pagination will get the correct sentinels.\n    this.endState = forkState === null || forkState === void 0 ? void 0 : forkState.clone();\n    return timeline;\n  }\n\n  /**\n   * Creates an independent timeline, inheriting the directional state from this timeline.\n   *\n   * @param direction -   EventTimeline.BACKWARDS to get the state at the\n   *   start of the timeline; EventTimeline.FORWARDS to get the state at the end\n   *   of the timeline.\n   *\n   * @returns the new timeline\n   */\n  fork(direction) {\n    var forkState = this.getState(direction);\n    var timeline = new EventTimeline(this.eventTimelineSet);\n    timeline.startState = forkState === null || forkState === void 0 ? void 0 : forkState.clone();\n    timeline.endState = forkState === null || forkState === void 0 ? void 0 : forkState.clone();\n    return timeline;\n  }\n\n  /**\n   * Get the ID of the room for this timeline\n   * @returns room ID\n   */\n  getRoomId() {\n    return this.roomId;\n  }\n\n  /**\n   * Get the filter for this timeline's timelineSet (if any)\n   * @returns filter\n   */\n  getFilter() {\n    return this.eventTimelineSet.getFilter();\n  }\n\n  /**\n   * Get the timelineSet for this timeline\n   * @returns timelineSet\n   */\n  getTimelineSet() {\n    return this.eventTimelineSet;\n  }\n\n  /**\n   * Get the base index.\n   *\n   * <p>This is an index which is incremented when events are prepended to the\n   * timeline. An individual event therefore stays at the same index in the array\n   * relative to the base index (although note that a given event's index may\n   * well be less than the base index, thus giving that event a negative relative\n   * index).\n   */\n  getBaseIndex() {\n    return this.baseIndex;\n  }\n\n  /**\n   * Get the list of events in this context\n   *\n   * @returns An array of MatrixEvents\n   */\n  getEvents() {\n    return this.events;\n  }\n\n  /**\n   * Get the room state at the start/end of the timeline\n   *\n   * @param direction -   EventTimeline.BACKWARDS to get the state at the\n   *   start of the timeline; EventTimeline.FORWARDS to get the state at the end\n   *   of the timeline.\n   *\n   * @returns state at the start/end of the timeline\n   */\n  getState(direction) {\n    if (direction == EventTimeline.BACKWARDS) {\n      return this.startState;\n    } else if (direction == EventTimeline.FORWARDS) {\n      return this.endState;\n    } else {\n      throw new Error(\"Invalid direction '\" + direction + \"'\");\n    }\n  }\n\n  /**\n   * Get a pagination token\n   *\n   * @param direction - EventTimeline.BACKWARDS to get the pagination\n   *   token for going backwards in time; EventTimeline.FORWARDS to get the\n   *   pagination token for going forwards in time.\n   *\n   * @returns pagination token\n   */\n  getPaginationToken(direction) {\n    if (this.roomId) {\n      return this.getState(direction).paginationToken;\n    } else if (direction === Direction.Backward) {\n      return this.startToken;\n    } else {\n      return this.endToken;\n    }\n  }\n\n  /**\n   * Set a pagination token\n   *\n   * @param token -       pagination token\n   *\n   * @param direction -    EventTimeline.BACKWARDS to set the pagination\n   *   token for going backwards in time; EventTimeline.FORWARDS to set the\n   *   pagination token for going forwards in time.\n   */\n  setPaginationToken(token, direction) {\n    if (this.roomId) {\n      this.getState(direction).paginationToken = token;\n    } else if (direction === Direction.Backward) {\n      this.startToken = token;\n    } else {\n      this.endToken = token;\n    }\n  }\n\n  /**\n   * Get the next timeline in the series\n   *\n   * @param direction - EventTimeline.BACKWARDS to get the previous\n   *   timeline; EventTimeline.FORWARDS to get the next timeline.\n   *\n   * @returns previous or following timeline, if they have been\n   * joined up.\n   */\n  getNeighbouringTimeline(direction) {\n    if (direction == EventTimeline.BACKWARDS) {\n      return this.prevTimeline;\n    } else if (direction == EventTimeline.FORWARDS) {\n      return this.nextTimeline;\n    } else {\n      throw new Error(\"Invalid direction '\" + direction + \"'\");\n    }\n  }\n\n  /**\n   * Set the next timeline in the series\n   *\n   * @param neighbour - previous/following timeline\n   *\n   * @param direction - EventTimeline.BACKWARDS to set the previous\n   *   timeline; EventTimeline.FORWARDS to set the next timeline.\n   *\n   * @throws Error if an attempt is made to set the neighbouring timeline when\n   * it is already set.\n   */\n  setNeighbouringTimeline(neighbour, direction) {\n    if (this.getNeighbouringTimeline(direction)) {\n      throw new Error(\"timeline already has a neighbouring timeline - \" + \"cannot reset neighbour (direction: \" + direction + \")\");\n    }\n    if (direction == EventTimeline.BACKWARDS) {\n      this.prevTimeline = neighbour;\n    } else if (direction == EventTimeline.FORWARDS) {\n      this.nextTimeline = neighbour;\n    } else {\n      throw new Error(\"Invalid direction '\" + direction + \"'\");\n    }\n\n    // make sure we don't try to paginate this timeline\n    this.setPaginationToken(null, direction);\n  }\n\n  /**\n   * Add a new event to the timeline, and update the state\n   *\n   * @param event - new event\n   * @param options - addEvent options\n   */\n  addEvent(event, _ref) {\n    var {\n      toStartOfTimeline,\n      roomState,\n      timelineWasEmpty,\n      addToState\n    } = _ref;\n    if (!roomState) {\n      roomState = toStartOfTimeline ? this.startState : this.endState;\n    }\n    var timelineSet = this.getTimelineSet();\n    if (timelineSet.room) {\n      EventTimeline.setEventMetadata(event, roomState, toStartOfTimeline);\n\n      // modify state but only on unfiltered timelineSets\n      if (addToState && event.isState() && timelineSet.room.getUnfilteredTimelineSet() === timelineSet) {\n        var _roomState;\n        (_roomState = roomState) === null || _roomState === void 0 || _roomState.setStateEvents([event], {\n          timelineWasEmpty\n        });\n        // it is possible that the act of setting the state event means we\n        // can set more metadata (specifically sender/target props), so try\n        // it again if the prop wasn't previously set. It may also mean that\n        // the sender/target is updated (if the event set was a room member event)\n        // so we want to use the *updated* member (new avatar/name) instead.\n        //\n        // However, we do NOT want to do this on member events if we're going\n        // back in time, else we'll set the .sender value for BEFORE the given\n        // member event, whereas we want to set the .sender value for the ACTUAL\n        // member event itself.\n        if (!event.sender || event.getType() === EventType.RoomMember && !toStartOfTimeline) {\n          EventTimeline.setEventMetadata(event, roomState, toStartOfTimeline);\n        }\n      }\n    }\n    var insertIndex;\n    if (toStartOfTimeline) {\n      insertIndex = 0;\n    } else {\n      insertIndex = this.events.length;\n    }\n    this.events.splice(insertIndex, 0, event); // insert element\n    if (toStartOfTimeline) {\n      this.baseIndex++;\n    }\n  }\n\n  /**\n   * Insert a new event into the timeline, and update the state.\n   *\n   * TEMPORARY: until we have recursive relations, we need this function\n   * to exist to allow us to insert events in timeline order, which is our\n   * best guess for Sync Order.\n   * This is a copy of addEvent above, modified to allow inserting an event at\n   * a specific index.\n   *\n   * @internal\n   */\n  insertEvent(event, insertIndex, roomState, addToState) {\n    var timelineSet = this.getTimelineSet();\n    if (timelineSet.room) {\n      EventTimeline.setEventMetadata(event, roomState, false);\n\n      // modify state but only on unfiltered timelineSets\n      if (addToState && event.isState() && timelineSet.room.getUnfilteredTimelineSet() === timelineSet) {\n        roomState.setStateEvents([event], {});\n        // it is possible that the act of setting the state event means we\n        // can set more metadata (specifically sender/target props), so try\n        // it again if the prop wasn't previously set. It may also mean that\n        // the sender/target is updated (if the event set was a room member event)\n        // so we want to use the *updated* member (new avatar/name) instead.\n        //\n        // However, we do NOT want to do this on member events if we're going\n        // back in time, else we'll set the .sender value for BEFORE the given\n        // member event, whereas we want to set the .sender value for the ACTUAL\n        // member event itself.\n        if (!event.sender || event.getType() === EventType.RoomMember) {\n          EventTimeline.setEventMetadata(event, roomState, false);\n        }\n      }\n    }\n    this.events.splice(insertIndex, 0, event); // insert element\n  }\n\n  /**\n   * Remove an event from the timeline\n   *\n   * @param eventId -  ID of event to be removed\n   * @returns removed event, or null if not found\n   */\n  removeEvent(eventId) {\n    for (var i = this.events.length - 1; i >= 0; i--) {\n      var ev = this.events[i];\n      if (ev.getId() == eventId) {\n        this.events.splice(i, 1);\n        if (i < this.baseIndex) {\n          this.baseIndex--;\n        }\n        return ev;\n      }\n    }\n    return null;\n  }\n\n  /**\n   * Return a string to identify this timeline, for debugging\n   *\n   * @returns name for this timeline\n   */\n  toString() {\n    return this.name;\n  }\n}\n/**\n * Symbolic constant for methods which take a 'direction' argument:\n * refers to the start of the timeline, or backwards in time.\n */\n_defineProperty(EventTimeline, \"BACKWARDS\", Direction.Backward);\n/**\n * Symbolic constant for methods which take a 'direction' argument:\n * refers to the end of the timeline, or forwards in time.\n */\n_defineProperty(EventTimeline, \"FORWARDS\", Direction.Forward);\n//# sourceMappingURL=event-timeline.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2019, 2021, 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventStatus, MatrixEventEvent } from \"./event.js\";\nimport { logger } from \"../logger.js\";\nimport { RelationType } from \"../@types/event.js\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.js\";\nimport { Room } from \"./room.js\";\nexport var RelationsEvent = /*#__PURE__*/function (RelationsEvent) {\n  RelationsEvent[\"Add\"] = \"Relations.add\";\n  RelationsEvent[\"Remove\"] = \"Relations.remove\";\n  RelationsEvent[\"Redaction\"] = \"Relations.redaction\";\n  return RelationsEvent;\n}({});\nvar matchesEventType = function matchesEventType(eventType, targetEventType) {\n  var altTargetEventTypes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];\n  return [targetEventType, ...altTargetEventTypes].includes(eventType);\n};\n\n/**\n * A container for relation events that supports easy access to common ways of\n * aggregating such events. Each instance holds events that of a single relation\n * type and event type. All of the events also relate to the same original event.\n *\n * The typical way to get one of these containers is via\n * EventTimelineSet#getRelationsForEvent.\n */\nexport class Relations extends TypedEventEmitter {\n  /**\n   * @param relationType - The type of relation involved, such as \"m.annotation\", \"m.reference\", \"m.replace\", etc.\n   * @param eventType - The relation event's type, such as \"m.reaction\", etc.\n   * @param client - The client which created this instance. For backwards compatibility also accepts a Room.\n   * @param altEventTypes - alt event types for relation events, for example to support unstable prefixed event types\n   */\n  constructor(relationType, eventType, client, altEventTypes) {\n    var _this;\n    super();\n    _this = this;\n    this.relationType = relationType;\n    this.eventType = eventType;\n    this.altEventTypes = altEventTypes;\n    _defineProperty(this, \"relationEventIds\", new Set());\n    _defineProperty(this, \"relations\", new Set());\n    _defineProperty(this, \"annotationsByKey\", {});\n    _defineProperty(this, \"annotationsBySender\", {});\n    _defineProperty(this, \"sortedAnnotationsByKey\", []);\n    _defineProperty(this, \"targetEvent\", null);\n    _defineProperty(this, \"creationEmitted\", false);\n    _defineProperty(this, \"client\", void 0);\n    /**\n     * Listens for event status changes to remove cancelled events.\n     *\n     * @param event - The event whose status has changed\n     * @param status - The new status\n     */\n    _defineProperty(this, \"onEventStatus\", (event, status) => {\n      if (!event.isSending()) {\n        // Sending is done, so we don't need to listen anymore\n        event.removeListener(MatrixEventEvent.Status, this.onEventStatus);\n        return;\n      }\n      if (status !== EventStatus.CANCELLED) {\n        return;\n      }\n      // Event was cancelled, remove from the collection\n      event.removeListener(MatrixEventEvent.Status, this.onEventStatus);\n      this.removeEvent(event);\n    });\n    /**\n     * For relations that have been redacted, we want to remove them from\n     * aggregation data sets and emit an update event.\n     *\n     * To do so, we listen for `Event.beforeRedaction`, which happens:\n     *   - after the server accepted the redaction and remote echoed back to us\n     *   - before the original event has been marked redacted in the client\n     *\n     * @param redactedEvent - The original relation event that is about to be redacted.\n     */\n    _defineProperty(this, \"onBeforeRedaction\", /*#__PURE__*/function () {\n      var _ref = _asyncToGenerator(function* (redactedEvent) {\n        if (!_this.relations.has(redactedEvent)) {\n          return;\n        }\n        _this.relations.delete(redactedEvent);\n        if (_this.relationType === RelationType.Annotation) {\n          // Remove the redacted annotation from aggregation by key\n          _this.removeAnnotationFromAggregation(redactedEvent);\n        } else if (_this.relationType === RelationType.Replace && _this.targetEvent && !_this.targetEvent.isState()) {\n          var lastReplacement = yield _this.getLastReplacement();\n          _this.targetEvent.makeReplaced(lastReplacement);\n        }\n        redactedEvent.removeListener(MatrixEventEvent.BeforeRedaction, _this.onBeforeRedaction);\n        _this.emit(RelationsEvent.Redaction, redactedEvent);\n      });\n      return function (_x) {\n        return _ref.apply(this, arguments);\n      };\n    }());\n    this.client = client instanceof Room ? client.client : client;\n  }\n\n  /**\n   * Add relation events to this collection.\n   *\n   * @param event - The new relation event to be added.\n   */\n  addEvent(event) {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      if (_this2.relationEventIds.has(event.getId())) {\n        return;\n      }\n      var relation = event.getRelation();\n      if (!relation) {\n        logger.error(\"Event must have relation info\");\n        return;\n      }\n      var relationType = relation.rel_type;\n      var eventType = event.getType();\n      if (_this2.relationType !== relationType || !matchesEventType(eventType, _this2.eventType, _this2.altEventTypes)) {\n        logger.error(\"Event relation info doesn't match this container\");\n        return;\n      }\n\n      // If the event is in the process of being sent, listen for cancellation\n      // so we can remove the event from the collection.\n      if (event.isSending()) {\n        event.on(MatrixEventEvent.Status, _this2.onEventStatus);\n      }\n      _this2.relations.add(event);\n      _this2.relationEventIds.add(event.getId());\n      if (_this2.relationType === RelationType.Annotation) {\n        _this2.addAnnotationToAggregation(event);\n      } else if (_this2.relationType === RelationType.Replace && _this2.targetEvent && !_this2.targetEvent.isState()) {\n        var lastReplacement = yield _this2.getLastReplacement();\n        _this2.targetEvent.makeReplaced(lastReplacement);\n      }\n      event.on(MatrixEventEvent.BeforeRedaction, _this2.onBeforeRedaction);\n      _this2.emit(RelationsEvent.Add, event);\n      _this2.maybeEmitCreated();\n    })();\n  }\n\n  /**\n   * Remove relation event from this collection.\n   *\n   * @param event - The relation event to remove.\n   */\n  removeEvent(event) {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      if (!_this3.relations.has(event)) {\n        return;\n      }\n      _this3.relations.delete(event);\n      if (_this3.relationType === RelationType.Annotation) {\n        _this3.removeAnnotationFromAggregation(event);\n      } else if (_this3.relationType === RelationType.Replace && _this3.targetEvent && !_this3.targetEvent.isState()) {\n        var lastReplacement = yield _this3.getLastReplacement();\n        _this3.targetEvent.makeReplaced(lastReplacement);\n      }\n      _this3.emit(RelationsEvent.Remove, event);\n    })();\n  }\n  /**\n   * Get all relation events in this collection.\n   *\n   * These are currently in the order of insertion to this collection, which\n   * won't match timeline order in the case of scrollback.\n   * TODO: Tweak `addEvent` to insert correctly for scrollback.\n   *\n   * Relation events in insertion order.\n   */\n  getRelations() {\n    return [...this.relations];\n  }\n  addAnnotationToAggregation(event) {\n    var _event$getRelation;\n    var {\n      key\n    } = (_event$getRelation = event.getRelation()) !== null && _event$getRelation !== void 0 ? _event$getRelation : {};\n    if (!key) return;\n    var eventsForKey = this.annotationsByKey[key];\n    if (!eventsForKey) {\n      eventsForKey = this.annotationsByKey[key] = new Set();\n      this.sortedAnnotationsByKey.push([key, eventsForKey]);\n    }\n    // Add the new event to the set for this key\n    eventsForKey.add(event);\n    // Re-sort the [key, events] pairs in descending order of event count\n    this.sortedAnnotationsByKey.sort((a, b) => {\n      var aEvents = a[1];\n      var bEvents = b[1];\n      return bEvents.size - aEvents.size;\n    });\n    var sender = event.getSender();\n    var eventsFromSender = this.annotationsBySender[sender];\n    if (!eventsFromSender) {\n      eventsFromSender = this.annotationsBySender[sender] = new Set();\n    }\n    // Add the new event to the set for this sender\n    eventsFromSender.add(event);\n  }\n  removeAnnotationFromAggregation(event) {\n    var _event$getRelation2;\n    var {\n      key\n    } = (_event$getRelation2 = event.getRelation()) !== null && _event$getRelation2 !== void 0 ? _event$getRelation2 : {};\n    if (!key) return;\n    var eventsForKey = this.annotationsByKey[key];\n    if (eventsForKey) {\n      eventsForKey.delete(event);\n\n      // Re-sort the [key, events] pairs in descending order of event count\n      this.sortedAnnotationsByKey.sort((a, b) => {\n        var aEvents = a[1];\n        var bEvents = b[1];\n        return bEvents.size - aEvents.size;\n      });\n    }\n    var sender = event.getSender();\n    var eventsFromSender = this.annotationsBySender[sender];\n    if (eventsFromSender) {\n      eventsFromSender.delete(event);\n    }\n  }\n  /**\n   * Get all events in this collection grouped by key and sorted by descending\n   * event count in each group.\n   *\n   * This is currently only supported for the annotation relation type.\n   *\n   * An array of [key, events] pairs sorted by descending event count.\n   * The events are stored in a Set (which preserves insertion order).\n   */\n  getSortedAnnotationsByKey() {\n    if (this.relationType !== RelationType.Annotation) {\n      // Other relation types are not grouped currently.\n      return null;\n    }\n    return this.sortedAnnotationsByKey;\n  }\n\n  /**\n   * Get all events in this collection grouped by sender.\n   *\n   * This is currently only supported for the annotation relation type.\n   *\n   * An object with each relation sender as a key and the matching Set of\n   * events for that sender as a value.\n   */\n  getAnnotationsBySender() {\n    if (this.relationType !== RelationType.Annotation) {\n      // Other relation types are not grouped currently.\n      return null;\n    }\n    return this.annotationsBySender;\n  }\n\n  /**\n   * Returns the most recent (and allowed) m.replace relation, if any.\n   *\n   * This is currently only supported for the m.replace relation type,\n   * once the target event is known, see `addEvent`.\n   */\n  getLastReplacement() {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      if (_this4.relationType !== RelationType.Replace) {\n        // Aggregating on last only makes sense for this relation type\n        return null;\n      }\n      if (!_this4.targetEvent) {\n        // Don't know which replacements to accept yet.\n        // This method shouldn't be called before the original\n        // event is known anyway.\n        return null;\n      }\n\n      // the all-knowning server tells us that the event at some point had\n      // this timestamp for its replacement, so any following replacement should definitely not be less\n      var replaceRelation = _this4.targetEvent.getServerAggregatedRelation(RelationType.Replace);\n      var minTs = replaceRelation === null || replaceRelation === void 0 ? void 0 : replaceRelation.origin_server_ts;\n      var lastReplacement = _this4.getRelations().reduce((last, event) => {\n        if (event.getSender() !== _this4.targetEvent.getSender()) {\n          return last;\n        }\n        if (minTs && minTs > event.getTs()) {\n          return last;\n        }\n        if (last && last.getTs() > event.getTs()) {\n          return last;\n        }\n        return event;\n      }, null);\n      if (lastReplacement !== null && lastReplacement !== void 0 && lastReplacement.shouldAttemptDecryption() && _this4.client.getCrypto()) {\n        // Dirty but we are expecting to pass the cryptoBackend which is not accessible here\n        yield lastReplacement.attemptDecryption(_this4.client.getCrypto());\n      } else if (lastReplacement !== null && lastReplacement !== void 0 && lastReplacement.isBeingDecrypted()) {\n        yield lastReplacement.getDecryptionPromise();\n      }\n      return lastReplacement;\n    })();\n  }\n\n  /*\n   * @param targetEvent - the event the relations are related to.\n   */\n  setTargetEvent(event) {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      if (_this5.targetEvent) {\n        return;\n      }\n      _this5.targetEvent = event;\n      if (_this5.relationType === RelationType.Replace && !_this5.targetEvent.isState()) {\n        var replacement = yield _this5.getLastReplacement();\n        // this is the initial update, so only call it if we already have something\n        // to not emit Event.replaced needlessly\n        if (replacement) {\n          _this5.targetEvent.makeReplaced(replacement);\n        }\n      }\n      _this5.maybeEmitCreated();\n    })();\n  }\n  maybeEmitCreated() {\n    if (this.creationEmitted) {\n      return;\n    }\n    // Only emit we're \"created\" once we have a target event instance _and_\n    // at least one related event.\n    if (!this.targetEvent || !this.relations.size) {\n      return;\n    }\n    this.creationEmitted = true;\n    this.targetEvent.emit(MatrixEventEvent.RelationsCreated, this.relationType, this.eventType);\n  }\n}\n//# sourceMappingURL=relations.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { Relations } from \"./relations.js\";\nimport { EventStatus, MatrixEventEvent } from \"./event.js\";\nexport class RelationsContainer {\n  constructor(client, room) {\n    this.client = client;\n    this.room = room;\n    // A tree of objects to access a set of related children for an event, as in:\n    // this.relations.get(parentEventId).get(relationType).get(relationEventType)\n    _defineProperty(this, \"relations\", new Map());\n  }\n\n  /**\n   * Get a collection of child events to a given event in this timeline set.\n   *\n   * @param eventId - The ID of the event that you'd like to access child events for.\n   * For example, with annotations, this would be the ID of the event being annotated.\n   * @param relationType - The type of relationship involved, such as \"m.annotation\", \"m.reference\", \"m.replace\", etc.\n   * @param eventType - The relation event's type, such as \"m.reaction\", etc.\n   * @throws If `eventId</code>, <code>relationType</code> or <code>eventType`\n   * are not valid.\n   *\n   * @returns\n   * A container for relation events or undefined if there are no relation events for\n   * the relationType.\n   */\n  getChildEventsForEvent(eventId, relationType, eventType) {\n    var _this$relations$get;\n    return (_this$relations$get = this.relations.get(eventId)) === null || _this$relations$get === void 0 || (_this$relations$get = _this$relations$get.get(relationType)) === null || _this$relations$get === void 0 ? void 0 : _this$relations$get.get(eventType);\n  }\n  getAllChildEventsForEvent(parentEventId) {\n    var _this$relations$get2;\n    var relationsForEvent = (_this$relations$get2 = this.relations.get(parentEventId)) !== null && _this$relations$get2 !== void 0 ? _this$relations$get2 : new Map();\n    var events = [];\n    for (var relationsRecord of relationsForEvent.values()) {\n      for (var relations of relationsRecord.values()) {\n        events.push(...relations.getRelations());\n      }\n    }\n    return events;\n  }\n\n  /**\n   * Set an event as the target event if any Relations exist for it already.\n   * Child events can point to other child events as their parent, so this method may be\n   * called for events which are also logically child events.\n   *\n   * @param event - The event to check as relation target.\n   */\n  aggregateParentEvent(event) {\n    var relationsForEvent = this.relations.get(event.getId());\n    if (!relationsForEvent) return;\n    for (var relationsWithRelType of relationsForEvent.values()) {\n      for (var relationsWithEventType of relationsWithRelType.values()) {\n        relationsWithEventType.setTargetEvent(event);\n      }\n    }\n  }\n\n  /**\n   * Add relation events to the relevant relation collection.\n   *\n   * @param event - The new child event to be aggregated.\n   * @param timelineSet - The event timeline set within which to search for the related event if any.\n   */\n  aggregateChildEvent(event, timelineSet) {\n    if (event.isRedacted() || event.status === EventStatus.CANCELLED) {\n      return;\n    }\n    var relation = event.getRelation();\n    if (!relation) return;\n    var onEventDecrypted = () => {\n      if (event.isDecryptionFailure()) {\n        // This could for example happen if the encryption keys are not yet available.\n        // The event may still be decrypted later. Register the listener again.\n        event.once(MatrixEventEvent.Decrypted, onEventDecrypted);\n        return;\n      }\n      this.aggregateChildEvent(event, timelineSet);\n    };\n\n    // If the event is currently encrypted, wait until it has been decrypted.\n    if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) {\n      event.once(MatrixEventEvent.Decrypted, onEventDecrypted);\n      return;\n    }\n    var {\n      event_id: relatesToEventId,\n      rel_type: relationType\n    } = relation;\n    var eventType = event.getType();\n    var relationsForEvent = this.relations.get(relatesToEventId);\n    if (!relationsForEvent) {\n      relationsForEvent = new Map();\n      this.relations.set(relatesToEventId, relationsForEvent);\n    }\n    var relationsWithRelType = relationsForEvent.get(relationType);\n    if (!relationsWithRelType) {\n      relationsWithRelType = new Map();\n      relationsForEvent.set(relationType, relationsWithRelType);\n    }\n    var relationsWithEventType = relationsWithRelType.get(eventType);\n    if (!relationsWithEventType) {\n      var _this$room, _ref, _timelineSet$findEven;\n      relationsWithEventType = new Relations(relationType, eventType, this.client);\n      relationsWithRelType.set(eventType, relationsWithEventType);\n      var _room = (_this$room = this.room) !== null && _this$room !== void 0 ? _this$room : timelineSet === null || timelineSet === void 0 ? void 0 : timelineSet.room;\n      var relatesToEvent = (_ref = (_timelineSet$findEven = timelineSet === null || timelineSet === void 0 ? void 0 : timelineSet.findEventById(relatesToEventId)) !== null && _timelineSet$findEven !== void 0 ? _timelineSet$findEven : _room === null || _room === void 0 ? void 0 : _room.findEventById(relatesToEventId)) !== null && _ref !== void 0 ? _ref : _room === null || _room === void 0 ? void 0 : _room.getPendingEvent(relatesToEventId);\n      if (relatesToEvent) {\n        relationsWithEventType.setTargetEvent(relatesToEvent);\n      }\n    }\n    relationsWithEventType.addEvent(event);\n  }\n}\n//# sourceMappingURL=relations-container.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventTimeline } from \"./event-timeline.js\";\nimport { logger } from \"../logger.js\";\nimport { RoomEvent } from \"./room.js\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.js\";\nimport { RelationsContainer } from \"./relations-container.js\";\nvar DEBUG = true;\n\n/* istanbul ignore next */\nvar debuglog;\nif (DEBUG) {\n  // using bind means that we get to keep useful line numbers in the console\n  debuglog = logger.log.bind(logger);\n} else {\n  /* istanbul ignore next */\n  debuglog = function debuglog() {};\n}\nexport var DuplicateStrategy = /*#__PURE__*/function (DuplicateStrategy) {\n  DuplicateStrategy[\"Ignore\"] = \"ignore\";\n  DuplicateStrategy[\"Replace\"] = \"replace\";\n  return DuplicateStrategy;\n}({});\nexport class EventTimelineSet extends TypedEventEmitter {\n  /**\n   * Construct a set of EventTimeline objects, typically on behalf of a given\n   * room.  A room may have multiple EventTimelineSets for different levels\n   * of filtering.  The global notification list is also an EventTimelineSet, but\n   * lacks a room.\n   *\n   * <p>This is an ordered sequence of timelines, which may or may not\n   * be continuous. Each timeline lists a series of events, as well as tracking\n   * the room state at the start and the end of the timeline (if appropriate).\n   * It also tracks forward and backward pagination tokens, as well as containing\n   * links to the next timeline in the sequence.\n   *\n   * <p>There is one special timeline - the 'live' timeline, which represents the\n   * timeline to which events are being added in real-time as they are received\n   * from the /sync API. Note that you should not retain references to this\n   * timeline - even if it is the current timeline right now, it may not remain\n   * so if the server gives us a timeline gap in /sync.\n   *\n   * <p>In order that we can find events from their ids later, we also maintain a\n   * map from event_id to timeline and index.\n   *\n   * @param room - Room for this timelineSet. May be null for non-room cases, such as the\n   * notification timeline.\n   * @param opts - Options inherited from Room.\n   * @param client - the Matrix client which owns this EventTimelineSet,\n   * can be omitted if room is specified.\n   * @param thread - the thread to which this timeline set relates.\n   * @param threadListType - the type of thread list represented, if any\n   * (e.g., All threads or My threads)\n   */\n  constructor(room) {\n    var _this$room$relations, _this$room, _room$client;\n    var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    var client = arguments.length > 2 ? arguments[2] : undefined;\n    var thread = arguments.length > 3 ? arguments[3] : undefined;\n    var threadListType = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;\n    super();\n    this.room = room;\n    this.thread = thread;\n    this.threadListType = threadListType;\n    _defineProperty(this, \"relations\", void 0);\n    _defineProperty(this, \"timelineSupport\", void 0);\n    _defineProperty(this, \"displayPendingEvents\", void 0);\n    _defineProperty(this, \"liveTimeline\", void 0);\n    _defineProperty(this, \"timelines\", void 0);\n    _defineProperty(this, \"_eventIdToTimeline\", new Map());\n    _defineProperty(this, \"filter\", void 0);\n    this.timelineSupport = Boolean(opts.timelineSupport);\n    this.liveTimeline = new EventTimeline(this);\n    this.displayPendingEvents = opts.pendingEvents !== false;\n\n    // just a list - *not* ordered.\n    this.timelines = [this.liveTimeline];\n    this._eventIdToTimeline = new Map();\n    this.filter = opts.filter;\n    this.relations = (_this$room$relations = (_this$room = this.room) === null || _this$room === void 0 ? void 0 : _this$room.relations) !== null && _this$room$relations !== void 0 ? _this$room$relations : new RelationsContainer((_room$client = room === null || room === void 0 ? void 0 : room.client) !== null && _room$client !== void 0 ? _room$client : client);\n  }\n\n  /**\n   * Get all the timelines in this set\n   * @returns the timelines in this set\n   */\n  getTimelines() {\n    return this.timelines;\n  }\n\n  /**\n   * Get the filter object this timeline set is filtered on, if any\n   * @returns the optional filter for this timelineSet\n   */\n  getFilter() {\n    return this.filter;\n  }\n\n  /**\n   * Set the filter object this timeline set is filtered on\n   * (passed to the server when paginating via /messages).\n   * @param filter - the filter for this timelineSet\n   */\n  setFilter(filter) {\n    this.filter = filter;\n  }\n\n  /**\n   * Get the list of pending sent events for this timelineSet's room, filtered\n   * by the timelineSet's filter if appropriate.\n   *\n   * @returns A list of the sent events\n   * waiting for remote echo.\n   *\n   * @throws If `opts.pendingEventOrdering` was not 'detached'\n   */\n  getPendingEvents() {\n    if (!this.room || !this.displayPendingEvents) {\n      return [];\n    }\n    return this.room.getPendingEvents();\n  }\n  /**\n   * Get the live timeline for this room.\n   *\n   * @returns live timeline\n   */\n  getLiveTimeline() {\n    return this.liveTimeline;\n  }\n\n  /**\n   * Set the live timeline for this room.\n   *\n   * @returns live timeline\n   */\n  setLiveTimeline(timeline) {\n    this.liveTimeline = timeline;\n  }\n\n  /**\n   * Return the timeline (if any) this event is in.\n   * @param eventId - the eventId being sought\n   * @returns timeline\n   */\n  eventIdToTimeline(eventId) {\n    return this._eventIdToTimeline.get(eventId);\n  }\n\n  /**\n   * Track a new event as if it were in the same timeline as an old event,\n   * replacing it.\n   * @param oldEventId -  event ID of the original event\n   * @param newEventId -  event ID of the replacement event\n   */\n  replaceEventId(oldEventId, newEventId) {\n    var existingTimeline = this._eventIdToTimeline.get(oldEventId);\n    if (existingTimeline) {\n      this._eventIdToTimeline.delete(oldEventId);\n      this._eventIdToTimeline.set(newEventId, existingTimeline);\n    }\n  }\n\n  /**\n   * Reset the live timeline, and start a new one.\n   *\n   * <p>This is used when /sync returns a 'limited' timeline.\n   *\n   * @param backPaginationToken -   token for back-paginating the new timeline\n   * @param forwardPaginationToken - token for forward-paginating the old live timeline,\n   * if absent or null, all timelines are reset.\n   *\n   * @remarks\n   * Fires {@link RoomEvent.TimelineReset}\n   */\n  resetLiveTimeline(backPaginationToken, forwardPaginationToken) {\n    // Each EventTimeline has RoomState objects tracking the state at the start\n    // and end of that timeline. The copies at the end of the live timeline are\n    // special because they will have listeners attached to monitor changes to\n    // the current room state, so we move this RoomState from the end of the\n    // current live timeline to the end of the new one and, if necessary,\n    // replace it with a newly created one. We also make a copy for the start\n    // of the new timeline.\n\n    // if timeline support is disabled, forget about the old timelines\n    var resetAllTimelines = !this.timelineSupport || !forwardPaginationToken;\n    var oldTimeline = this.liveTimeline;\n    var newTimeline = resetAllTimelines ? oldTimeline.forkLive(EventTimeline.FORWARDS) : oldTimeline.fork(EventTimeline.FORWARDS);\n    if (resetAllTimelines) {\n      this.timelines = [newTimeline];\n      this._eventIdToTimeline = new Map();\n    } else {\n      this.timelines.push(newTimeline);\n    }\n    if (forwardPaginationToken) {\n      // Now set the forward pagination token on the old live timeline\n      // so it can be forward-paginated.\n      oldTimeline.setPaginationToken(forwardPaginationToken, EventTimeline.FORWARDS);\n    }\n\n    // make sure we set the pagination token before firing timelineReset,\n    // otherwise clients which start back-paginating will fail, and then get\n    // stuck without realising that they *can* back-paginate.\n    newTimeline.setPaginationToken(backPaginationToken !== null && backPaginationToken !== void 0 ? backPaginationToken : null, EventTimeline.BACKWARDS);\n\n    // Now we can swap the live timeline to the new one.\n    this.liveTimeline = newTimeline;\n    this.emit(RoomEvent.TimelineReset, this.room, this, resetAllTimelines);\n  }\n\n  /**\n   * Get the timeline which contains the given event, if any\n   *\n   * @param eventId -  event ID to look for\n   * @returns timeline containing\n   * the given event, or null if unknown\n   */\n  getTimelineForEvent(eventId) {\n    if (eventId === null || eventId === undefined) {\n      return null;\n    }\n    var res = this._eventIdToTimeline.get(eventId);\n    return res === undefined ? null : res;\n  }\n\n  /**\n   * Get an event which is stored in our timelines\n   *\n   * @param eventId -  event ID to look for\n   * @returns the given event, or undefined if unknown\n   */\n  findEventById(eventId) {\n    var tl = this.getTimelineForEvent(eventId);\n    if (!tl) {\n      return undefined;\n    }\n    return tl.getEvents().find(function (ev) {\n      return ev.getId() == eventId;\n    });\n  }\n\n  /**\n   * Add a new timeline to this timeline list\n   *\n   * @returns newly-created timeline\n   */\n  addTimeline() {\n    if (!this.timelineSupport) {\n      throw new Error(\"timeline support is disabled. Set the 'timelineSupport'\" + \" parameter to true when creating MatrixClient to enable\" + \" it.\");\n    }\n    var timeline = new EventTimeline(this);\n    this.timelines.push(timeline);\n    return timeline;\n  }\n\n  /**\n   * Add events to a timeline\n   *\n   * <p>Will fire \"Room.timeline\" for each event added.\n   *\n   * @param events - A list of events to add.\n   *\n   * @param toStartOfTimeline -   True to add these events to the start\n   * (oldest) instead of the end (newest) of the timeline. If true, the oldest\n   * event will be the <b>last</b> element of 'events'.\n   *\n   * @param timeline -   timeline to\n   *    add events to.\n   *\n   * @param paginationToken -   token for the next batch of events\n   *\n   * @remarks\n   * Fires {@link RoomEvent.Timeline}\n   *\n   */\n  addEventsToTimeline(events, toStartOfTimeline, addToState, timeline, paginationToken) {\n    if (!timeline) {\n      throw new Error(\"'timeline' not specified for EventTimelineSet.addEventsToTimeline\");\n    }\n    if (!toStartOfTimeline && timeline == this.liveTimeline) {\n      throw new Error(\"EventTimelineSet.addEventsToTimeline cannot be used for adding events to \" + \"the live timeline - use Room.addLiveEvents instead\");\n    }\n    if (this.filter) {\n      events = this.filter.filterRoomTimeline(events);\n      if (!events.length) {\n        return;\n      }\n    }\n    var direction = toStartOfTimeline ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS;\n    var inverseDirection = toStartOfTimeline ? EventTimeline.FORWARDS : EventTimeline.BACKWARDS;\n\n    // Adding events to timelines can be quite complicated. The following\n    // illustrates some of the corner-cases.\n    //\n    // Let's say we start by knowing about four timelines. timeline3 and\n    // timeline4 are neighbours:\n    //\n    //    timeline1    timeline2    timeline3    timeline4\n    //      [M]          [P]          [S] <------> [T]\n    //\n    // Now we paginate timeline1, and get the following events from the server:\n    // [M, N, P, R, S, T, U].\n    //\n    // 1. First, we ignore event M, since we already know about it.\n    //\n    // 2. Next, we append N to timeline 1.\n    //\n    // 3. Next, we don't add event P, since we already know about it,\n    //    but we do link together the timelines. We now have:\n    //\n    //    timeline1    timeline2    timeline3    timeline4\n    //      [M, N] <---> [P]          [S] <------> [T]\n    //\n    // 4. Now we add event R to timeline2:\n    //\n    //    timeline1    timeline2    timeline3    timeline4\n    //      [M, N] <---> [P, R]       [S] <------> [T]\n    //\n    //    Note that we have switched the timeline we are working on from\n    //    timeline1 to timeline2.\n    //\n    // 5. We ignore event S, but again join the timelines:\n    //\n    //    timeline1    timeline2    timeline3    timeline4\n    //      [M, N] <---> [P, R] <---> [S] <------> [T]\n    //\n    // 6. We ignore event T, and the timelines are already joined, so there\n    //    is nothing to do.\n    //\n    // 7. Finally, we add event U to timeline4:\n    //\n    //    timeline1    timeline2    timeline3    timeline4\n    //      [M, N] <---> [P, R] <---> [S] <------> [T, U]\n    //\n    // The important thing to note in the above is what happened when we\n    // already knew about a given event:\n    //\n    //   - if it was appropriate, we joined up the timelines (steps 3, 5).\n    //   - in any case, we started adding further events to the timeline which\n    //       contained the event we knew about (steps 3, 5, 6).\n    //\n    //\n    // So much for adding events to the timeline. But what do we want to do\n    // with the pagination token?\n    //\n    // In the case above, we will be given a pagination token which tells us how to\n    // get events beyond 'U' - in this case, it makes sense to store this\n    // against timeline4. But what if timeline4 already had 'U' and beyond? in\n    // that case, our best bet is to throw away the pagination token we were\n    // given and stick with whatever token timeline4 had previously. In short,\n    // we want to only store the pagination token if the last event we receive\n    // is one we didn't previously know about.\n    //\n    // We make an exception for this if it turns out that we already knew about\n    // *all* of the events, and we weren't able to join up any timelines. When\n    // that happens, it means our existing pagination token is faulty, since it\n    // is only telling us what we already know. Rather than repeatedly\n    // paginating with the same token, we might as well use the new pagination\n    // token in the hope that we eventually work our way out of the mess.\n\n    var didUpdate = false;\n    var lastEventWasNew = false;\n    for (var event of events) {\n      var eventId = event.getId();\n      var existingTimeline = this._eventIdToTimeline.get(eventId);\n      if (!existingTimeline) {\n        // we don't know about this event yet. Just add it to the timeline.\n        this.addEventToTimeline(event, timeline, {\n          toStartOfTimeline,\n          addToState\n        });\n        lastEventWasNew = true;\n        didUpdate = true;\n        continue;\n      }\n      lastEventWasNew = false;\n      if (existingTimeline == timeline) {\n        debuglog(\"Event \" + eventId + \" already in timeline \" + timeline);\n        continue;\n      }\n      var neighbour = timeline.getNeighbouringTimeline(direction);\n      if (neighbour) {\n        // this timeline already has a neighbour in the relevant direction;\n        // let's assume the timelines are already correctly linked up, and\n        // skip over to it.\n        //\n        // there's probably some edge-case here where we end up with an\n        // event which is in a timeline a way down the chain, and there is\n        // a break in the chain somewhere. But I can't really imagine how\n        // that would happen, so I'm going to ignore it for now.\n        //\n        if (existingTimeline == neighbour) {\n          debuglog(\"Event \" + eventId + \" in neighbouring timeline - \" + \"switching to \" + existingTimeline);\n        } else {\n          debuglog(\"Event \" + eventId + \" already in a different \" + \"timeline \" + existingTimeline);\n        }\n        timeline = existingTimeline;\n        continue;\n      }\n\n      // time to join the timelines.\n      logger.info(\"Already have timeline for \" + eventId + \" - joining timeline \" + timeline + \" to \" + existingTimeline);\n\n      // Variables to keep the line length limited below.\n      var existingIsLive = existingTimeline === this.liveTimeline;\n      var timelineIsLive = timeline === this.liveTimeline;\n      var backwardsIsLive = direction === EventTimeline.BACKWARDS && existingIsLive;\n      var forwardsIsLive = direction === EventTimeline.FORWARDS && timelineIsLive;\n      if (backwardsIsLive || forwardsIsLive) {\n        // The live timeline should never be spliced into a non-live position.\n        // We use independent logging to better discover the problem at a glance.\n        if (backwardsIsLive) {\n          logger.warn(\"Refusing to set a preceding existingTimeLine on our \" + \"timeline as the existingTimeLine is live (\" + existingTimeline + \")\");\n        }\n        if (forwardsIsLive) {\n          logger.warn(\"Refusing to set our preceding timeline on a existingTimeLine \" + \"as our timeline is live (\" + timeline + \")\");\n        }\n        continue; // abort splicing - try next event\n      }\n      timeline.setNeighbouringTimeline(existingTimeline, direction);\n      existingTimeline.setNeighbouringTimeline(timeline, inverseDirection);\n      timeline = existingTimeline;\n      didUpdate = true;\n    }\n\n    // see above - if the last event was new to us, or if we didn't find any\n    // new information, we update the pagination token for whatever\n    // timeline we ended up on.\n    if (lastEventWasNew || !didUpdate) {\n      if (direction === EventTimeline.FORWARDS && timeline === this.liveTimeline) {\n        logger.warn({\n          lastEventWasNew,\n          didUpdate\n        }); // for debugging\n        logger.warn(\"Refusing to set forwards pagination token of live timeline \" + \"\".concat(timeline, \" to \").concat(paginationToken));\n        return;\n      }\n      timeline.setPaginationToken(paginationToken !== null && paginationToken !== void 0 ? paginationToken : null, direction);\n    }\n  }\n\n  /**\n   * Add an event to the end of this live timeline.\n   *\n   * @param event - Event to be added\n   * @param options - addLiveEvent options\n   */\n  addLiveEvent(event, _ref) {\n    var {\n      duplicateStrategy,\n      fromCache,\n      roomState,\n      timelineWasEmpty,\n      addToState\n    } = _ref;\n    if (this.filter) {\n      var events = this.filter.filterRoomTimeline([event]);\n      if (!events.length) {\n        return;\n      }\n    }\n    var timeline = this._eventIdToTimeline.get(event.getId());\n    if (timeline) {\n      if (duplicateStrategy === DuplicateStrategy.Replace) {\n        debuglog(\"EventTimelineSet.addLiveEvent: replacing duplicate event \" + event.getId());\n        var tlEvents = timeline.getEvents();\n        for (var j = 0; j < tlEvents.length; j++) {\n          if (tlEvents[j].getId() === event.getId()) {\n            // still need to set the right metadata on this event\n            if (!roomState) {\n              roomState = timeline.getState(EventTimeline.FORWARDS);\n            }\n            EventTimeline.setEventMetadata(event, roomState, false);\n            tlEvents[j] = event;\n\n            // XXX: we need to fire an event when this happens.\n            break;\n          }\n        }\n      } else {\n        debuglog(\"EventTimelineSet.addLiveEvent: ignoring duplicate event \" + event.getId());\n      }\n      return;\n    }\n    this.addEventToTimeline(event, this.liveTimeline, {\n      toStartOfTimeline: false,\n      fromCache,\n      roomState,\n      timelineWasEmpty,\n      addToState\n    });\n  }\n\n  /**\n   * Add event to the given timeline, and emit Room.timeline. Assumes\n   * we have already checked we don't know about this event.\n   *\n   * Will fire \"Room.timeline\" for each event added.\n   *\n   * @param event - the event to add\n   * @param timeline - the timeline onto which to add it\n   * @param options - addEventToTimeline options\n   *\n   * @remarks\n   * Fires {@link RoomEvent.Timeline}\n   */\n  addEventToTimeline(event, timeline, _ref2) {\n    var {\n      toStartOfTimeline,\n      fromCache = false,\n      roomState,\n      timelineWasEmpty,\n      addToState\n    } = _ref2;\n    if (timeline.getTimelineSet() !== this) {\n      var _this$thread;\n      throw new Error(\"EventTimelineSet.addEventToTimeline: Timeline=\".concat(timeline.toString(), \" does not belong \\\" +\\n                \\\"in timelineSet(threadId=\").concat((_this$thread = this.thread) === null || _this$thread === void 0 ? void 0 : _this$thread.id, \")\"));\n    }\n    var eventId = event.getId();\n    this.relations.aggregateParentEvent(event);\n    this.relations.aggregateChildEvent(event, this);\n\n    // Make sure events don't get mixed in timelines they shouldn't be in (e.g. a\n    // threaded message should not be in the main timeline).\n    //\n    // We can only run this check for timelines with a `room` because `canContain`\n    // requires it\n    if (this.room && !this.canContain(event)) {\n      var _this$thread2;\n      var eventDebugString = \"event=\".concat(eventId);\n      if (event.threadRootId) {\n        eventDebugString += \"(belongs to thread=\".concat(event.threadRootId, \")\");\n      }\n      logger.warn(\"EventTimelineSet.addEventToTimeline: Ignoring \".concat(eventDebugString, \" that does not belong \") + \"in timeline=\".concat(timeline.toString(), \" timelineSet(threadId=\").concat((_this$thread2 = this.thread) === null || _this$thread2 === void 0 ? void 0 : _this$thread2.id, \")\"));\n      return;\n    }\n    timeline.addEvent(event, {\n      toStartOfTimeline,\n      roomState,\n      timelineWasEmpty,\n      addToState\n    });\n    this._eventIdToTimeline.set(eventId, timeline);\n    var data = {\n      timeline: timeline,\n      liveEvent: !toStartOfTimeline && timeline == this.liveTimeline && !fromCache\n    };\n    this.emit(RoomEvent.Timeline, event, this.room, Boolean(toStartOfTimeline), false, data);\n  }\n\n  /**\n   * Insert event to the given timeline, and emit Room.timeline. Assumes\n   * we have already checked we don't know about this event.\n   *\n   * TEMPORARY: until we have recursive relations, we need this function\n   * to exist to allow us to insert events in timeline order, which is our\n   * best guess for Sync Order.\n   * This is a copy of addEventToTimeline above, modified to insert the event\n   * after the event it relates to, and before any event with a later\n   * timestamp. This is our best guess at Sync Order.\n   *\n   * Will fire \"Room.timeline\" for each event added.\n   *\n   * @internal\n   *\n   * @remarks\n   * Fires {@link RoomEvent.Timeline}\n   */\n  insertEventIntoTimeline(event, timeline, roomState, addToState) {\n    if (timeline.getTimelineSet() !== this) {\n      var _this$thread3;\n      throw new Error(\"EventTimelineSet.insertEventIntoTimeline: Timeline=\".concat(timeline.toString(), \" does not belong \\\" +\\n                \\\"in timelineSet(threadId=\").concat((_this$thread3 = this.thread) === null || _this$thread3 === void 0 ? void 0 : _this$thread3.id, \")\"));\n    }\n    var eventId = event.getId();\n    this.relations.aggregateParentEvent(event);\n    this.relations.aggregateChildEvent(event, this);\n\n    // Make sure events don't get mixed in timelines they shouldn't be in (e.g. a\n    // threaded message should not be in the main timeline).\n    //\n    // We can only run this check for timelines with a `room` because `canContain`\n    // requires it\n    if (this.room && !this.canContain(event)) {\n      var _this$thread4;\n      var eventDebugString = \"event=\".concat(eventId);\n      if (event.threadRootId) {\n        eventDebugString += \"(belongs to thread=\".concat(event.threadRootId, \")\");\n      }\n      logger.warn(\"EventTimelineSet.insertEventIntoTimeline: Ignoring \".concat(eventDebugString, \" that does not belong \") + \"in timeline=\".concat(timeline.toString(), \" timelineSet(threadId=\").concat((_this$thread4 = this.thread) === null || _this$thread4 === void 0 ? void 0 : _this$thread4.id, \")\"));\n      return;\n    }\n\n    // Find the event that this event is related to - the \"parent\"\n    var parentEventId = event.relationEventId;\n    if (!parentEventId) {\n      // Not related to anything - we just append\n      this.addEventToTimeline(event, timeline, {\n        toStartOfTimeline: false,\n        fromCache: false,\n        timelineWasEmpty: false,\n        roomState,\n        addToState\n      });\n      return;\n    }\n    var parentEvent = this.findEventById(parentEventId);\n    var timelineEvents = timeline.getEvents();\n\n    // Start searching from the parent event, or if it's not loaded, start\n    // at the beginning and insert purely using timestamp order.\n    var parentIndex = parentEvent !== undefined ? timelineEvents.indexOf(parentEvent) : 0;\n    var insertIndex = parentIndex;\n    for (; insertIndex < timelineEvents.length; insertIndex++) {\n      var nextEvent = timelineEvents[insertIndex];\n      if (nextEvent.getTs() > event.getTs()) {\n        // We found an event later than ours, so insert before that.\n        break;\n      }\n    }\n    // If we got to the end of the loop, insertIndex points at the end of\n    // the list.\n\n    timeline.insertEvent(event, insertIndex, roomState, addToState);\n    this._eventIdToTimeline.set(eventId, timeline);\n    var data = {\n      timeline: timeline,\n      // The purpose of this method is inserting events in the middle of the\n      // timeline, so the events are, by definition, not live (whether or not\n      // we're adding them to the live timeline).\n      liveEvent: false\n    };\n    this.emit(RoomEvent.Timeline, event, this.room, false, false, data);\n  }\n\n  /**\n   * Replaces event with ID oldEventId with one with newEventId, if oldEventId is\n   * recognised.  Otherwise, add to the live timeline.  Used to handle remote echos.\n   *\n   * @param localEvent -     the new event to be added to the timeline\n   * @param oldEventId -          the ID of the original event\n   * @param newEventId -         the ID of the replacement event\n   *\n   * @remarks\n   * Fires {@link RoomEvent.Timeline}\n   */\n  handleRemoteEcho(localEvent, oldEventId, newEventId) {\n    // XXX: why don't we infer newEventId from localEvent?\n    var existingTimeline = this._eventIdToTimeline.get(oldEventId);\n    if (existingTimeline) {\n      this._eventIdToTimeline.delete(oldEventId);\n      this._eventIdToTimeline.set(newEventId, existingTimeline);\n    } else if (!this.filter || this.filter.filterRoomTimeline([localEvent]).length) {\n      this.addEventToTimeline(localEvent, this.liveTimeline, {\n        toStartOfTimeline: false,\n        addToState: false\n      });\n    }\n  }\n\n  /**\n   * Removes a single event from this room.\n   *\n   * @param eventId -  The id of the event to remove\n   *\n   * @returns the removed event, or null if the event was not found\n   * in this room.\n   */\n  removeEvent(eventId) {\n    var timeline = this._eventIdToTimeline.get(eventId);\n    if (!timeline) {\n      return null;\n    }\n    var removed = timeline.removeEvent(eventId);\n    if (removed) {\n      this._eventIdToTimeline.delete(eventId);\n      var data = {\n        timeline: timeline\n      };\n      this.emit(RoomEvent.Timeline, removed, this.room, undefined, true, data);\n    }\n    return removed;\n  }\n\n  /**\n   * Determine where two events appear in the timeline relative to one another\n   *\n   * @param eventId1 -   The id of the first event\n   * @param eventId2 -   The id of the second event\n    * @returns -1 if eventId1 precedes eventId2, and +1 eventId1 succeeds\n   * eventId2. 0 if they are the same event; null if we can't tell (either\n   * because we don't know about one of the events, or because they are in\n   * separate timelines which don't join up).\n   */\n  compareEventOrdering(eventId1, eventId2) {\n    if (eventId1 == eventId2) {\n      // optimise this case\n      return 0;\n    }\n    var timeline1 = this._eventIdToTimeline.get(eventId1);\n    var timeline2 = this._eventIdToTimeline.get(eventId2);\n    if (timeline1 === undefined) {\n      return null;\n    }\n    if (timeline2 === undefined) {\n      return null;\n    }\n    if (timeline1 === timeline2) {\n      // both events are in the same timeline - figure out their relative indices\n      var idx1 = undefined;\n      var idx2 = undefined;\n      var events = timeline1.getEvents();\n      for (var idx = 0; idx < events.length && (idx1 === undefined || idx2 === undefined); idx++) {\n        var evId = events[idx].getId();\n        if (evId == eventId1) {\n          idx1 = idx;\n        }\n        if (evId == eventId2) {\n          idx2 = idx;\n        }\n      }\n      var difference = idx1 - idx2;\n\n      // Return the sign of difference.\n      if (difference < 0) {\n        return -1;\n      } else if (difference > 0) {\n        return 1;\n      } else {\n        return 0;\n      }\n    }\n\n    // the events are in different timelines. Iterate through the\n    // linkedlist to see which comes first.\n\n    // first work forwards from timeline1\n    var tl = timeline1;\n    while (tl) {\n      if (tl === timeline2) {\n        // timeline1 is before timeline2\n        return -1;\n      }\n      tl = tl.getNeighbouringTimeline(EventTimeline.FORWARDS);\n    }\n\n    // now try backwards from timeline1\n    tl = timeline1;\n    while (tl) {\n      if (tl === timeline2) {\n        // timeline2 is before timeline1\n        return 1;\n      }\n      tl = tl.getNeighbouringTimeline(EventTimeline.BACKWARDS);\n    }\n\n    // the timelines are not contiguous.\n    return null;\n  }\n\n  /**\n   * Determine whether a given event can sanely be added to this event timeline set,\n   * for timeline sets relating to a thread, only return true for events in the same\n   * thread timeline, for timeline sets not relating to a thread only return true\n   * for events which should be shown in the main room timeline.\n   * Requires the `room` property to have been set at EventTimelineSet construction time.\n   *\n   * @param event - the event to check whether it belongs to this timeline set.\n   * @throws Error if `room` was not set when constructing this timeline set.\n   * @returns whether the event belongs to this timeline set.\n   */\n  canContain(event) {\n    if (!this.room) {\n      throw new Error(\"Cannot call `EventTimelineSet::canContain without a `room` set. \" + \"Set the room when creating the EventTimelineSet to call this method.\");\n    }\n    var {\n      threadId,\n      shouldLiveInRoom,\n      shouldLiveInThread\n    } = this.room.eventShouldLiveIn(event);\n    if (this.thread) {\n      return this.thread.id === threadId;\n    }\n    if (!shouldLiveInRoom && !shouldLiveInThread) {\n      var _this$room2;\n      logger.warn(\"EventTimelineSet:canContain event encountered which cannot be added to any timeline roomId=\".concat((_this$room2 = this.room) === null || _this$room2 === void 0 ? void 0 : _this$room2.roomId, \" eventId=\").concat(event.getId(), \" threadId=\").concat(event.threadRootId));\n    }\n    return shouldLiveInRoom;\n  }\n}\n//# sourceMappingURL=event-timeline-set.js.map","/*\nCopyright 2015 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Enum for event statuses.\n * @readonly\n */\nexport var EventStatus = /*#__PURE__*/function (EventStatus) {\n  /** The event was not sent and will no longer be retried. */\n  EventStatus[\"NOT_SENT\"] = \"not_sent\";\n  /** The message is being encrypted */\n  EventStatus[\"ENCRYPTING\"] = \"encrypting\";\n  /** The event is in the process of being sent. */\n  EventStatus[\"SENDING\"] = \"sending\";\n  /** The event is in a queue waiting to be sent. */\n  EventStatus[\"QUEUED\"] = \"queued\";\n  /** The event has been sent to the server, but we have not yet received the echo. */\n  EventStatus[\"SENT\"] = \"sent\";\n  /** The event was cancelled before it was successfully sent. */\n  EventStatus[\"CANCELLED\"] = \"cancelled\";\n  return EventStatus;\n}({});\n//# sourceMappingURL=event-status.js.map","/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * A stripped m.room.member event which contains the key renderable fields from the event,\n * sent only in simplified sliding sync (not `/v3/sync`).\n * This is very similar to MSC4186Hero from sliding-sync.ts but an internal format with\n * camelCase rather than underscores.\n */\n\n/**\n * High level summary information for a room, as returned by `/v3/sync`.\n */\n\n/**\n * Construct a new Room Summary. A summary can be used for display on a recent\n * list, without having to load the entire room list into memory.\n * @param roomId - Required. The ID of this room.\n * @param info - Optional. The summary info. Additional keys are supported.\n */\nexport class RoomSummary {\n  constructor(roomId, info) {\n    this.roomId = roomId;\n  }\n}\n//# sourceMappingURL=room-summary.js.map","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { ServerControlledNamespacedValue } from \"../NamespacedValue.js\";\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3773\n *\n * @experimental\n */\nexport var UNREAD_THREAD_NOTIFICATIONS = new ServerControlledNamespacedValue(\"unread_thread_notifications\", \"org.matrix.msc3773.unread_thread_notifications\");\n//# sourceMappingURL=sync.js.map","/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { FILTER_RELATED_BY_REL_TYPES, FILTER_RELATED_BY_SENDERS, THREAD_RELATION_TYPE } from \"./models/thread.js\";\n\n/**\n * Checks if a value matches a given field value, which may be a * terminated\n * wildcard pattern.\n * @param actualValue -  The value to be compared\n * @param filterValue -  The filter pattern to be compared\n * @returns true if the actualValue matches the filterValue\n */\nfunction matchesWildcard(actualValue, filterValue) {\n  if (filterValue.endsWith(\"*\")) {\n    var typePrefix = filterValue.slice(0, -1);\n    return actualValue.slice(0, typePrefix.length) === typePrefix;\n  } else {\n    return actualValue === filterValue;\n  }\n}\n\n/* eslint-disable camelcase */\n\n/* eslint-enable camelcase */\n\n/**\n * FilterComponent is a section of a Filter definition which defines the\n * types, rooms, senders filters etc to be applied to a particular type of resource.\n * This is all ported over from synapse's Filter object.\n *\n * N.B. that synapse refers to these as 'Filters', and what js-sdk refers to as\n * 'Filters' are referred to as 'FilterCollections'.\n */\nexport class FilterComponent {\n  constructor(filterJson, userId) {\n    this.filterJson = filterJson;\n    this.userId = userId;\n  }\n\n  /**\n   * Checks with the filter component matches the given event\n   * @param event - event to be checked against the filter\n   * @returns true if the event matches the filter\n   */\n  check(event) {\n    var _event$getUnsigned, _bundledRelationships;\n    var bundledRelationships = ((_event$getUnsigned = event.getUnsigned()) === null || _event$getUnsigned === void 0 ? void 0 : _event$getUnsigned[\"m.relations\"]) || {};\n    var relations = Object.keys(bundledRelationships);\n    // Relation senders allows in theory a look-up of any senders\n    // however clients can only know about the current user participation status\n    // as sending a whole list of participants could be proven problematic in terms\n    // of performance\n    // This should be improved when bundled relationships solve that problem\n    var relationSenders = [];\n    if (this.userId && bundledRelationships !== null && bundledRelationships !== void 0 && (_bundledRelationships = bundledRelationships[THREAD_RELATION_TYPE.name]) !== null && _bundledRelationships !== void 0 && _bundledRelationships.current_user_participated) {\n      relationSenders.push(this.userId);\n    }\n    return this.checkFields(event.getRoomId(), event.getSender(), event.getType(), event.getContent() ? event.getContent().url !== undefined : false, relations, relationSenders);\n  }\n\n  /**\n   * Converts the filter component into the form expected over the wire\n   */\n  toJSON() {\n    return Object.fromEntries(Object.entries({\n      types: this.filterJson.types,\n      not_types: this.filterJson.not_types,\n      rooms: this.filterJson.rooms,\n      not_rooms: this.filterJson.not_rooms,\n      senders: this.filterJson.senders,\n      not_senders: this.filterJson.not_senders,\n      contains_url: this.filterJson.contains_url,\n      [FILTER_RELATED_BY_SENDERS.name]: this.filterJson[FILTER_RELATED_BY_SENDERS.name],\n      [FILTER_RELATED_BY_REL_TYPES.name]: this.filterJson[FILTER_RELATED_BY_REL_TYPES.name]\n    }).filter(_ref => {\n      var [_key, value] = _ref;\n      return value;\n    }));\n  }\n\n  /**\n   * Checks whether the filter component matches the given event fields.\n   * @param roomId -        the roomId for the event being checked\n   * @param sender -        the sender of the event being checked\n   * @param eventType -     the type of the event being checked\n   * @param containsUrl -  whether the event contains a content.url field\n   * @param relationTypes -  whether has aggregated relation of the given type\n   * @param relationSenders - whether one of the relation is sent by the user listed\n   * @returns true if the event fields match the filter\n   */\n  checkFields(roomId, sender, eventType, containsUrl, relationTypes, relationSenders) {\n    var literalKeys = {\n      rooms: function rooms(v) {\n        return roomId === v;\n      },\n      senders: function senders(v) {\n        return sender === v;\n      },\n      types: function types(v) {\n        return matchesWildcard(eventType, v);\n      }\n    };\n    for (var name in literalKeys) {\n      var matchFunc = literalKeys[name];\n      var notName = \"not_\" + name;\n      var disallowedValues = this.filterJson[notName];\n      if (disallowedValues !== null && disallowedValues !== void 0 && disallowedValues.some(matchFunc)) {\n        return false;\n      }\n      var allowedValues = this.filterJson[name];\n      if (allowedValues && !allowedValues.some(matchFunc)) {\n        return false;\n      }\n    }\n    var containsUrlFilter = this.filterJson.contains_url;\n    if (containsUrlFilter !== undefined && containsUrlFilter !== containsUrl) {\n      return false;\n    }\n    var relationTypesFilter = this.filterJson[FILTER_RELATED_BY_REL_TYPES.name];\n    if (relationTypesFilter !== undefined) {\n      if (!this.arrayMatchesFilter(relationTypesFilter, relationTypes)) {\n        return false;\n      }\n    }\n    var relationSendersFilter = this.filterJson[FILTER_RELATED_BY_SENDERS.name];\n    if (relationSendersFilter !== undefined) {\n      if (!this.arrayMatchesFilter(relationSendersFilter, relationSenders)) {\n        return false;\n      }\n    }\n    return true;\n  }\n  arrayMatchesFilter(filter, values) {\n    return values.length > 0 && filter.every(value => {\n      return values.includes(value);\n    });\n  }\n\n  /**\n   * Filters a list of events down to those which match this filter component\n   * @param events -  Events to be checked against the filter component\n   * @returns events which matched the filter component\n   */\n  filter(events) {\n    return events.filter(this.check, this);\n  }\n\n  /**\n   * Returns the limit field for a given filter component, providing a default of\n   * 10 if none is otherwise specified. Cargo-culted from Synapse.\n   * @returns the limit for this filter component.\n   */\n  limit() {\n    return this.filterJson.limit !== undefined ? this.filterJson.limit : 10;\n  }\n}\n//# sourceMappingURL=filter-component.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2015 - 2021 Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { UNREAD_THREAD_NOTIFICATIONS } from \"./@types/sync.js\";\nimport { FilterComponent } from \"./filter-component.js\";\n/**\n */\nfunction setProp(obj, keyNesting, val) {\n  var nestedKeys = keyNesting.split(\".\");\n  var currentObj = obj;\n  for (var i = 0; i < nestedKeys.length - 1; i++) {\n    if (!currentObj[nestedKeys[i]]) {\n      currentObj[nestedKeys[i]] = {};\n    }\n    currentObj = currentObj[nestedKeys[i]];\n  }\n  currentObj[nestedKeys[nestedKeys.length - 1]] = val;\n}\n\n/* eslint-disable camelcase */\n\n/* eslint-enable camelcase */\n\nexport class Filter {\n  /**\n   * Create a filter from existing data.\n   */\n  static fromJson(userId, filterId, jsonObj) {\n    var filter = new Filter(userId, filterId);\n    filter.setDefinition(jsonObj);\n    return filter;\n  }\n  /**\n   * Construct a new Filter.\n   * @param userId - The user ID for this filter.\n   * @param filterId - The filter ID if known.\n   */\n  constructor(userId, filterId) {\n    this.userId = userId;\n    this.filterId = filterId;\n    _defineProperty(this, \"definition\", {});\n    _defineProperty(this, \"roomFilter\", void 0);\n    _defineProperty(this, \"roomTimelineFilter\", void 0);\n  }\n\n  /**\n   * Get the ID of this filter on your homeserver (if known)\n   * @returns The filter ID\n   */\n  getFilterId() {\n    return this.filterId;\n  }\n\n  /**\n   * Get the JSON body of the filter.\n   * @returns The filter definition\n   */\n  getDefinition() {\n    return this.definition;\n  }\n\n  /**\n   * Set the JSON body of the filter\n   * @param definition - The filter definition\n   */\n  setDefinition(definition) {\n    this.definition = definition;\n\n    // This is all ported from synapse's FilterCollection()\n\n    // definitions look something like:\n    // {\n    //   \"room\": {\n    //     \"rooms\": [\"!abcde:example.com\"],\n    //     \"not_rooms\": [\"!123456:example.com\"],\n    //     \"state\": {\n    //       \"types\": [\"m.room.*\"],\n    //       \"not_rooms\": [\"!726s6s6q:example.com\"],\n    //       \"lazy_load_members\": true,\n    //     },\n    //     \"timeline\": {\n    //       \"limit\": 10,\n    //       \"types\": [\"m.room.message\"],\n    //       \"not_rooms\": [\"!726s6s6q:example.com\"],\n    //       \"not_senders\": [\"@spam:example.com\"]\n    //       \"contains_url\": true\n    //     },\n    //     \"ephemeral\": {\n    //       \"types\": [\"m.receipt\", \"m.typing\"],\n    //       \"not_rooms\": [\"!726s6s6q:example.com\"],\n    //       \"not_senders\": [\"@spam:example.com\"]\n    //     }\n    //   },\n    //   \"presence\": {\n    //     \"types\": [\"m.presence\"],\n    //     \"not_senders\": [\"@alice:example.com\"]\n    //   },\n    //   \"event_format\": \"client\",\n    //   \"event_fields\": [\"type\", \"content\", \"sender\"]\n    // }\n\n    var roomFilterJson = definition.room;\n\n    // consider the top level rooms/not_rooms filter\n    var roomFilterFields = {};\n    if (roomFilterJson) {\n      if (roomFilterJson.rooms) {\n        roomFilterFields.rooms = roomFilterJson.rooms;\n      }\n      if (roomFilterJson.rooms) {\n        roomFilterFields.not_rooms = roomFilterJson.not_rooms;\n      }\n    }\n    this.roomFilter = new FilterComponent(roomFilterFields, this.userId);\n    this.roomTimelineFilter = new FilterComponent((roomFilterJson === null || roomFilterJson === void 0 ? void 0 : roomFilterJson.timeline) || {}, this.userId);\n\n    // don't bother porting this from synapse yet:\n    // this._room_state_filter =\n    //     new FilterComponent(roomFilterJson.state || {});\n    // this._room_ephemeral_filter =\n    //     new FilterComponent(roomFilterJson.ephemeral || {});\n    // this._room_account_data_filter =\n    //     new FilterComponent(roomFilterJson.account_data || {});\n    // this._presence_filter =\n    //     new FilterComponent(definition.presence || {});\n    // this._account_data_filter =\n    //     new FilterComponent(definition.account_data || {});\n  }\n\n  /**\n   * Get the room.timeline filter component of the filter\n   * @returns room timeline filter component\n   */\n  getRoomTimelineFilterComponent() {\n    return this.roomTimelineFilter;\n  }\n\n  /**\n   * Filter the list of events based on whether they are allowed in a timeline\n   * based on this filter\n   * @param events -  the list of events being filtered\n   * @returns the list of events which match the filter\n   */\n  filterRoomTimeline(events) {\n    if (this.roomFilter) {\n      events = this.roomFilter.filter(events);\n    }\n    if (this.roomTimelineFilter) {\n      events = this.roomTimelineFilter.filter(events);\n    }\n    return events;\n  }\n\n  /**\n   * Set the max number of events to return for each room's timeline.\n   * @param limit - The max number of events to return for each room.\n   */\n  setTimelineLimit(limit) {\n    setProp(this.definition, \"room.timeline.limit\", limit);\n  }\n\n  /**\n   * Enable threads unread notification\n   */\n  setUnreadThreadNotifications(enabled) {\n    var _this$definition, _this$definition2;\n    this.definition = _objectSpread(_objectSpread({}, this.definition), {}, {\n      room: _objectSpread(_objectSpread({}, (_this$definition = this.definition) === null || _this$definition === void 0 ? void 0 : _this$definition.room), {}, {\n        timeline: _objectSpread(_objectSpread({}, (_this$definition2 = this.definition) === null || _this$definition2 === void 0 || (_this$definition2 = _this$definition2.room) === null || _this$definition2 === void 0 ? void 0 : _this$definition2.timeline), {}, {\n          [UNREAD_THREAD_NOTIFICATIONS.name]: enabled\n        })\n      })\n    });\n  }\n  setLazyLoadMembers(enabled) {\n    setProp(this.definition, \"room.state.lazy_load_members\", enabled);\n  }\n\n  /**\n   * Control whether left rooms should be included in responses.\n   * @param includeLeave - True to make rooms the user has left appear\n   * in responses.\n   */\n  setIncludeLeaveRooms(includeLeave) {\n    setProp(this.definition, \"room.include_leave\", includeLeave);\n  }\n}\n_defineProperty(Filter, \"LAZY_LOADING_MESSAGES_FILTER\", {\n  lazy_load_members: true\n});\n//# sourceMappingURL=filter.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n    http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MAIN_ROOM_TIMELINE, ReceiptType } from \"../@types/read_receipts.js\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.js\";\nimport { isSupportedReceiptType } from \"../utils.js\";\nimport { MatrixEvent } from \"./event.js\";\nimport { EventType } from \"../@types/event.js\";\nimport { MapWithDefault } from \"../utils.js\";\nimport { NotificationCountType } from \"./room.js\";\nimport { logger } from \"../logger.js\";\nimport { inMainTimelineForReceipt, threadIdForReceipt } from \"../client.js\";\n\n/**\n * Create a synthetic receipt for the given event\n * @param userId - The user ID if the receipt sender\n * @param event - The event that is to be acknowledged\n * @param receiptType - The type of receipt\n * @param unthreaded - the receipt is unthreaded\n * @returns a new event with the synthetic receipt in it\n */\nexport function synthesizeReceipt(userId, event, receiptType) {\n  var unthreaded = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n  return new MatrixEvent({\n    content: {\n      [event.getId()]: {\n        [receiptType]: {\n          [userId]: _objectSpread({\n            ts: event.getTs()\n          }, !unthreaded && {\n            thread_id: threadIdForReceipt(event)\n          })\n        }\n      }\n    },\n    type: EventType.Receipt,\n    room_id: event.getRoomId()\n  });\n}\nvar ReceiptPairRealIndex = 0;\nvar ReceiptPairSyntheticIndex = 1;\nexport class ReadReceipt extends TypedEventEmitter {\n  constructor() {\n    super(...arguments);\n    // receipts should clobber based on receipt_type and user_id pairs hence\n    // the form of this structure. This is sub-optimal for the exposed APIs\n    // which pass in an event ID and get back some receipts, so we also store\n    // a pre-cached list for this purpose.\n    // Map: receipt type → user Id → receipt\n    _defineProperty(this, \"receipts\", new MapWithDefault(() => new Map()));\n    _defineProperty(this, \"receiptCacheByEventId\", new Map());\n  }\n  /**\n   * Gets the latest receipt for a given user in the room\n   * @param userId - The id of the user for which we want the receipt\n   * @param ignoreSynthesized - Whether to ignore synthesized receipts or not\n   * @param receiptType - Optional. The type of the receipt we want to get\n   * @returns the latest receipts of the chosen type for the chosen user\n   */\n  getReadReceiptForUserId(userId) {\n    var _this$receipts$get$ge, _this$receipts$get;\n    var ignoreSynthesized = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n    var receiptType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ReceiptType.Read;\n    var [realReceipt, syntheticReceipt] = (_this$receipts$get$ge = (_this$receipts$get = this.receipts.get(receiptType)) === null || _this$receipts$get === void 0 ? void 0 : _this$receipts$get.get(userId)) !== null && _this$receipts$get$ge !== void 0 ? _this$receipts$get$ge : [null, null];\n    if (ignoreSynthesized) {\n      return realReceipt;\n    }\n    return syntheticReceipt !== null && syntheticReceipt !== void 0 ? syntheticReceipt : realReceipt;\n  }\n  compareReceipts(a, b) {\n    var _this$getUnfilteredTi;\n    // Try compare them in our unfiltered timeline set order, falling back to receipt timestamp which should be\n    // relatively sane as receipts are set only by the originating homeserver so as long as its clock doesn't\n    // jump around then it should be valid.\n    return (_this$getUnfilteredTi = this.getUnfilteredTimelineSet().compareEventOrdering(a.eventId, b.eventId)) !== null && _this$getUnfilteredTi !== void 0 ? _this$getUnfilteredTi : a.data.ts - b.data.ts;\n  }\n\n  /**\n   * Get the ID of the event that a given user has read up to, or null if:\n   * - we have received no read receipts for them, or\n   * - the receipt we have points at an event we don't have, or\n   * - the thread ID in the receipt does not match the thread root of the\n   *   referenced event.\n   *\n   * (The event might not exist if it is not loaded, and the thread ID might\n   * not match if the event has moved thread because it was redacted.)\n   *\n   * @param userId - The user ID to get read receipt event ID for\n   * @param ignoreSynthesized - If true, return only receipts that have been\n   *                            sent by the server, not implicit ones generated\n   *                            by the JS SDK.\n   * @returns ID of the latest existing event that the given user has read, or null.\n   */\n  getEventReadUpTo(userId) {\n    var ignoreSynthesized = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n    // Find what the latest receipt says is the latest event we have read\n    var latestReceipt = this.getLatestReceipt(userId, ignoreSynthesized);\n    if (!latestReceipt) {\n      return null;\n    }\n    return this.receiptPointsAtConsistentEvent(latestReceipt) ? latestReceipt.eventId : null;\n  }\n\n  /**\n   * Returns true if the event pointed at by this receipt exists, and its\n   * threadRootId is consistent with the thread information in the receipt.\n   */\n  receiptPointsAtConsistentEvent(receipt) {\n    var _receipt$data;\n    var event = this.findEventById(receipt.eventId);\n    if (!event) {\n      // If the receipt points at a non-existent event, we have multiple\n      // possibilities:\n      //\n      // 1. We don't have the event because it's not loaded yet - probably\n      //    it's old and we're best off ignoring the receipt - we can just\n      //    send a new one when we read a new event.\n      //\n      // 2. We have a bug e.g. we misclassified this event into the wrong\n      //    thread.\n      //\n      // 3. The referenced event moved out of this thread (e.g. because it\n      //    was deleted.)\n      //\n      // 4. The receipt had the incorrect thread ID (due to a bug in a\n      // client, or malicious behaviour).\n\n      // This receipt is not \"valid\" because it doesn't point at an event\n      // we have. We want to pretend it doesn't exist.\n      return false;\n    }\n    if (!((_receipt$data = receipt.data) !== null && _receipt$data !== void 0 && _receipt$data.thread_id)) {\n      // If this is an unthreaded receipt, it could point at any event, so\n      // there is no need to validate further - this receipt is valid.\n      return true;\n    }\n    // Otherwise it is a threaded receipt...\n\n    if (receipt.data.thread_id === MAIN_ROOM_TIMELINE) {\n      // The receipt is for the main timeline: we check that the event is\n      // in the main timeline.\n\n      // Check if the event is in the main timeline\n      var eventIsInMainTimeline = inMainTimelineForReceipt(event);\n      if (eventIsInMainTimeline) {\n        // The receipt is for the main timeline, and so is the event, so\n        // the receipt is valid.\n        return true;\n      }\n    } else {\n      // The receipt is for a different thread (not the main timeline)\n\n      if (event.threadRootId === receipt.data.thread_id) {\n        // If the receipt and event agree on the thread ID, the receipt\n        // is valid.\n        return true;\n      }\n    }\n\n    // The receipt thread ID disagrees with the event thread ID. There are 2\n    // possibilities:\n    //\n    // 1. The event moved to a different thread after the receipt was\n    //    created. This can happen if the event was redacted because that\n    //    moves it to the main timeline.\n    //\n    // 2. There is a bug somewhere - either we put the event into the wrong\n    //    thread, or someone sent an incorrect receipt.\n    //\n    // In many cases, we won't get here because the call to findEventById\n    // would have already returned null. We include this check to cover\n    // cases when `this` is a  room, meaning findEventById will find events\n    // in any thread, and to be defensive against unforeseen code paths.\n    logger.warn(\"Ignoring receipt because its thread_id (\".concat(receipt.data.thread_id, \") disagrees \") + \"with the thread root (\".concat(event.threadRootId, \") of the referenced event \") + \"(event ID = \".concat(receipt.eventId, \")\"));\n\n    // This receipt is not \"valid\" because it disagrees with us about what\n    // thread the event is in. We want to pretend it doesn't exist.\n    return false;\n  }\n  getLatestReceipt(userId, ignoreSynthesized) {\n    var _ref, _ref2;\n    // XXX: This is very very ugly and I hope I won't have to ever add a new\n    // receipt type here again. IMHO this should be done by the server in\n    // some more intelligent manner or the client should just use timestamps\n\n    var publicReadReceipt = this.getReadReceiptForUserId(userId, ignoreSynthesized, ReceiptType.Read);\n    var privateReadReceipt = this.getReadReceiptForUserId(userId, ignoreSynthesized, ReceiptType.ReadPrivate);\n\n    // If we have both, compare them\n    var comparison;\n    if (publicReadReceipt !== null && publicReadReceipt !== void 0 && publicReadReceipt.eventId && privateReadReceipt !== null && privateReadReceipt !== void 0 && privateReadReceipt.eventId) {\n      comparison = this.compareReceipts(publicReadReceipt, privateReadReceipt);\n    }\n\n    // The public receipt is more likely to drift out of date so the private\n    // one has precedence\n    if (!comparison) return (_ref = privateReadReceipt !== null && privateReadReceipt !== void 0 ? privateReadReceipt : publicReadReceipt) !== null && _ref !== void 0 ? _ref : null;\n\n    // If public read receipt is older, return the private one\n    return (_ref2 = comparison < 0 ? privateReadReceipt : publicReadReceipt) !== null && _ref2 !== void 0 ? _ref2 : null;\n  }\n  addReceiptToStructure(eventId, receiptType, userId, receipt, synthetic) {\n    var _pair$ReceiptPairSynt2, _pair$ReceiptPairSynt3;\n    var receiptTypesMap = this.receipts.getOrCreate(receiptType);\n    var pair = receiptTypesMap.get(userId);\n    if (!pair) {\n      pair = [null, null];\n      receiptTypesMap.set(userId, pair);\n    }\n    var existingReceipt = pair[ReceiptPairRealIndex];\n    if (synthetic) {\n      var _pair$ReceiptPairSynt;\n      existingReceipt = (_pair$ReceiptPairSynt = pair[ReceiptPairSyntheticIndex]) !== null && _pair$ReceiptPairSynt !== void 0 ? _pair$ReceiptPairSynt : pair[ReceiptPairRealIndex];\n    }\n    var wrappedReceipt = {\n      eventId,\n      data: receipt\n    };\n    if (existingReceipt) {\n      // We only want to add this receipt if we think it is later than the one we already have.\n      // This is managed server-side, but because we synthesize RRs locally we have to do it here too.\n      var _ordering = this.compareReceipts(existingReceipt, wrappedReceipt);\n      if (_ordering >= 0) {\n        return;\n      }\n    }\n    var realReceipt = synthetic ? pair[ReceiptPairRealIndex] : wrappedReceipt;\n    var syntheticReceipt = synthetic ? wrappedReceipt : pair[ReceiptPairSyntheticIndex];\n    var ordering = null;\n    if (realReceipt && syntheticReceipt) {\n      ordering = this.getUnfilteredTimelineSet().compareEventOrdering(realReceipt.eventId, syntheticReceipt.eventId);\n    }\n    var preferSynthetic = ordering === null || ordering < 0;\n\n    // we don't bother caching just real receipts by event ID as there's nothing that would read it.\n    // Take the current cached receipt before we overwrite the pair elements.\n    var cachedReceipt = (_pair$ReceiptPairSynt2 = pair[ReceiptPairSyntheticIndex]) !== null && _pair$ReceiptPairSynt2 !== void 0 ? _pair$ReceiptPairSynt2 : pair[ReceiptPairRealIndex];\n    if (synthetic && preferSynthetic) {\n      pair[ReceiptPairSyntheticIndex] = wrappedReceipt;\n    } else if (!synthetic) {\n      pair[ReceiptPairRealIndex] = wrappedReceipt;\n      if (!preferSynthetic) {\n        pair[ReceiptPairSyntheticIndex] = null;\n      }\n    }\n    var newCachedReceipt = (_pair$ReceiptPairSynt3 = pair[ReceiptPairSyntheticIndex]) !== null && _pair$ReceiptPairSynt3 !== void 0 ? _pair$ReceiptPairSynt3 : pair[ReceiptPairRealIndex];\n    if (cachedReceipt === newCachedReceipt) return;\n\n    // clean up any previous cache entry\n    if (cachedReceipt && this.receiptCacheByEventId.get(cachedReceipt.eventId)) {\n      var previousEventId = cachedReceipt.eventId;\n      // Remove the receipt we're about to clobber out of existence from the cache\n      this.receiptCacheByEventId.set(previousEventId, this.receiptCacheByEventId.get(previousEventId).filter(r => {\n        return r.type !== receiptType || r.userId !== userId;\n      }));\n      if (this.receiptCacheByEventId.get(previousEventId).length < 1) {\n        this.receiptCacheByEventId.delete(previousEventId); // clean up the cache keys\n      }\n    }\n\n    // cache the new one\n    if (!this.receiptCacheByEventId.get(eventId)) {\n      this.receiptCacheByEventId.set(eventId, []);\n    }\n    this.receiptCacheByEventId.get(eventId).push({\n      userId: userId,\n      type: receiptType,\n      data: receipt\n    });\n  }\n\n  /**\n   * Get a list of receipts for the given event.\n   * @param event - the event to get receipts for\n   * @returns A list of receipts with a userId, type and data keys or\n   * an empty list.\n   */\n  getReceiptsForEvent(event) {\n    return this.receiptCacheByEventId.get(event.getId()) || [];\n  }\n\n  /**\n   * Look in this room/thread's timeline to find an event. If `this` is a\n   * room, we look in all threads, but if `this` is a thread, we look only\n   * inside this thread.\n   */\n\n  /**\n   * This issue should also be addressed on synapse's side and is tracked as part\n   * of https://github.com/matrix-org/synapse/issues/14837\n   *\n   * Retrieves the read receipt for the logged in user and checks if it matches\n   * the last event in the room and whether that event originated from the logged\n   * in user.\n   * Under those conditions we can consider the context as read. This is useful\n   * because we never send read receipts against our own events\n   * @param userId - the logged in user\n   */\n  fixupNotifications(userId) {\n    var receipt = this.getReadReceiptForUserId(userId, false);\n    var lastEvent = this.timeline[this.timeline.length - 1];\n    if (lastEvent && (receipt === null || receipt === void 0 ? void 0 : receipt.eventId) === lastEvent.getId() && userId === lastEvent.getSender()) {\n      this.setUnread(NotificationCountType.Total, 0);\n      this.setUnread(NotificationCountType.Highlight, 0);\n    }\n  }\n\n  /**\n   * Add a temporary local-echo receipt to the room to reflect in the\n   * client the fact that we've sent one.\n   * @param userId - The user ID if the receipt sender\n   * @param e - The event that is to be acknowledged\n   * @param receiptType - The type of receipt\n   * @param unthreaded - the receipt is unthreaded\n   */\n  addLocalEchoReceipt(userId, e, receiptType) {\n    var unthreaded = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n    this.addReceipt(synthesizeReceipt(userId, e, receiptType, unthreaded), true);\n  }\n\n  /**\n   * Get a list of user IDs who have <b>read up to</b> the given event.\n   * @param event - the event to get read receipts for.\n   * @returns A list of user IDs.\n   */\n  getUsersReadUpTo(event) {\n    return this.getReceiptsForEvent(event).filter(function (receipt) {\n      return isSupportedReceiptType(receipt.type);\n    }).map(function (receipt) {\n      return receipt.userId;\n    });\n  }\n\n  /**\n   * Determines if the given user has read a particular event ID with the known\n   * history of the room. This is not a definitive check as it relies only on\n   * what is available to the room at the time of execution.\n   * @param userId - The user ID to check the read state of.\n   * @param eventId - The event ID to check if the user read.\n   * @returns True if the user has read the event, false otherwise.\n   */\n\n  /**\n   * Returns the most recent unthreaded receipt for a given user\n   * @param userId - the MxID of the User\n   * @returns an unthreaded Receipt. Can be undefined if receipts have been disabled\n   * or a user chooses to use private read receipts (or we have simply not received\n   * a receipt from this user yet).\n   *\n   * @deprecated use `hasUserReadEvent` or `getEventReadUpTo` instead\n   */\n}\n//# sourceMappingURL=read-receipt.js.map","/*\nCopyright 2022 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { UnstableValue } from \"matrix-events-sdk\";\n/**\n * Identifier for a disclosed poll.\n */\nexport var M_POLL_KIND_DISCLOSED = new UnstableValue(\"m.poll.disclosed\", \"org.matrix.msc3381.poll.disclosed\");\n\n/**\n * Identifier for an undisclosed poll.\n */\nexport var M_POLL_KIND_UNDISCLOSED = new UnstableValue(\"m.poll.undisclosed\", \"org.matrix.msc3381.poll.undisclosed\");\n\n/**\n * Any poll kind.\n */\n\n/**\n * Known poll kind namespaces.\n */\n\n/**\n * The namespaced value for m.poll.start\n */\nexport var M_POLL_START = new UnstableValue(\"m.poll.start\", \"org.matrix.msc3381.poll.start\");\n\n/**\n * The m.poll.start type within event content\n */\n\n/**\n * A poll answer.\n */\n\n/**\n * The event definition for an m.poll.start event (in content)\n */\n\n/**\n * The content for an m.poll.start event\n */\n\n/**\n * The namespaced value for m.poll.response\n */\nexport var M_POLL_RESPONSE = new UnstableValue(\"m.poll.response\", \"org.matrix.msc3381.poll.response\");\n\n/**\n * The m.poll.response type within event content\n */\n\n/**\n * The event definition for an m.poll.response event (in content)\n */\n\n/**\n * The content for an m.poll.response event\n */\n\n/**\n * The namespaced value for m.poll.end\n */\nexport var M_POLL_END = new UnstableValue(\"m.poll.end\", \"org.matrix.msc3381.poll.end\");\n\n/**\n * The event definition for an m.poll.end event (in content)\n */\n\n/**\n * The content for an m.poll.end event\n */\n//# sourceMappingURL=polls.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { M_POLL_START } from \"matrix-events-sdk\";\nimport { M_POLL_END, M_POLL_RESPONSE } from \"../@types/polls.js\";\nimport { Relations } from \"./relations.js\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.js\";\nexport var PollEvent = /*#__PURE__*/function (PollEvent) {\n  PollEvent[\"New\"] = \"Poll.new\";\n  PollEvent[\"End\"] = \"Poll.end\";\n  PollEvent[\"Update\"] = \"Poll.update\";\n  PollEvent[\"Responses\"] = \"Poll.Responses\";\n  PollEvent[\"Destroy\"] = \"Poll.Destroy\";\n  PollEvent[\"UndecryptableRelations\"] = \"Poll.UndecryptableRelations\";\n  return PollEvent;\n}({});\nvar filterResponseRelations = (relationEvents, pollEndTimestamp) => {\n  var responseEvents = relationEvents.filter(event => {\n    if (event.isDecryptionFailure()) {\n      return;\n    }\n    return M_POLL_RESPONSE.matches(event.getType()) &&\n    // From MSC3381:\n    // \"Votes sent on or before the end event's timestamp are valid votes\"\n    event.getTs() <= pollEndTimestamp;\n  });\n  return {\n    responseEvents\n  };\n};\nexport class Poll extends TypedEventEmitter {\n  constructor(rootEvent, matrixClient, room) {\n    super();\n    this.rootEvent = rootEvent;\n    this.matrixClient = matrixClient;\n    this.room = room;\n    _defineProperty(this, \"roomId\", void 0);\n    _defineProperty(this, \"pollEvent\", void 0);\n    _defineProperty(this, \"_isFetchingResponses\", false);\n    _defineProperty(this, \"relationsNextBatch\", void 0);\n    _defineProperty(this, \"responses\", null);\n    _defineProperty(this, \"endEvent\", void 0);\n    /**\n     * Keep track of undecryptable relations\n     * As incomplete result sets affect poll results\n     */\n    _defineProperty(this, \"undecryptableRelationEventIds\", new Set());\n    _defineProperty(this, \"countUndecryptableEvents\", events => {\n      var undecryptableEventIds = events.filter(event => event.isDecryptionFailure()).map(event => event.getId());\n      var previousCount = this.undecryptableRelationsCount;\n      this.undecryptableRelationEventIds = new Set([...this.undecryptableRelationEventIds, ...undecryptableEventIds]);\n      if (this.undecryptableRelationsCount !== previousCount) {\n        this.emit(PollEvent.UndecryptableRelations, this.undecryptableRelationsCount);\n      }\n    });\n    if (!this.rootEvent.getRoomId() || !this.rootEvent.getId()) {\n      throw new Error(\"Invalid poll start event.\");\n    }\n    this.roomId = this.rootEvent.getRoomId();\n    this.pollEvent = this.rootEvent.unstableExtensibleEvent;\n  }\n  get pollId() {\n    return this.rootEvent.getId();\n  }\n  get endEventId() {\n    var _this$endEvent;\n    return (_this$endEvent = this.endEvent) === null || _this$endEvent === void 0 ? void 0 : _this$endEvent.getId();\n  }\n  get isEnded() {\n    return !!this.endEvent;\n  }\n  get isFetchingResponses() {\n    return this._isFetchingResponses;\n  }\n  get undecryptableRelationsCount() {\n    return this.undecryptableRelationEventIds.size;\n  }\n  getResponses() {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      // if we have already fetched some responses\n      // just return them\n      if (_this.responses) {\n        return _this.responses;\n      }\n\n      // if there is no fetching in progress\n      // start fetching\n      if (!_this.isFetchingResponses) {\n        yield _this.fetchResponses();\n      }\n      // return whatever responses we got from the first page\n      return _this.responses;\n    })();\n  }\n\n  /**\n   *\n   * @param event - event with a relation to the rootEvent\n   * @returns void\n   */\n  onNewRelation(event) {\n    var _this$endEvent2;\n    if (M_POLL_END.matches(event.getType()) && this.validateEndEvent(event)) {\n      this.endEvent = event;\n      this.refilterResponsesOnEnd();\n      this.emit(PollEvent.End);\n    }\n\n    // wait for poll responses to be initialised\n    if (!this.responses) {\n      return;\n    }\n    var pollEndTimestamp = ((_this$endEvent2 = this.endEvent) === null || _this$endEvent2 === void 0 ? void 0 : _this$endEvent2.getTs()) || Number.MAX_SAFE_INTEGER;\n    var {\n      responseEvents\n    } = filterResponseRelations([event], pollEndTimestamp);\n    this.countUndecryptableEvents([event]);\n    if (responseEvents.length) {\n      responseEvents.forEach(event => {\n        this.responses.addEvent(event);\n      });\n      this.emit(PollEvent.Responses, this.responses);\n    }\n  }\n  fetchResponses() {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      var _this2$endEvent, _allRelations$nextBat;\n      _this2._isFetchingResponses = true;\n\n      // we want:\n      // - stable and unstable M_POLL_RESPONSE\n      // - stable and unstable M_POLL_END\n      // so make one api call and filter by event type client side\n      var allRelations = yield _this2.matrixClient.relations(_this2.roomId, _this2.rootEvent.getId(), \"m.reference\", undefined, {\n        from: _this2.relationsNextBatch || undefined\n      });\n      yield Promise.all(allRelations.events.map(event => _this2.matrixClient.decryptEventIfNeeded(event)));\n      var responses = _this2.responses || new Relations(\"m.reference\", M_POLL_RESPONSE.name, _this2.matrixClient, [M_POLL_RESPONSE.altName]);\n      var pollEndEvent = allRelations.events.find(event => M_POLL_END.matches(event.getType()));\n      if (_this2.validateEndEvent(pollEndEvent)) {\n        _this2.endEvent = pollEndEvent;\n        _this2.refilterResponsesOnEnd();\n        _this2.emit(PollEvent.End);\n      }\n      var pollCloseTimestamp = ((_this2$endEvent = _this2.endEvent) === null || _this2$endEvent === void 0 ? void 0 : _this2$endEvent.getTs()) || Number.MAX_SAFE_INTEGER;\n      var {\n        responseEvents\n      } = filterResponseRelations(allRelations.events, pollCloseTimestamp);\n      responseEvents.forEach(event => {\n        responses.addEvent(event);\n      });\n      _this2.relationsNextBatch = (_allRelations$nextBat = allRelations.nextBatch) !== null && _allRelations$nextBat !== void 0 ? _allRelations$nextBat : undefined;\n      _this2.responses = responses;\n      _this2.countUndecryptableEvents(allRelations.events);\n\n      // while there are more pages of relations\n      // fetch them\n      if (_this2.relationsNextBatch) {\n        // don't await\n        // we want to return the first page as soon as possible\n        _this2.fetchResponses();\n      } else {\n        // no more pages\n        _this2._isFetchingResponses = false;\n      }\n\n      // emit after updating _isFetchingResponses state\n      _this2.emit(PollEvent.Responses, _this2.responses);\n    })();\n  }\n\n  /**\n   * Only responses made before the poll ended are valid\n   * Refilter after an end event is recieved\n   * To ensure responses are valid\n   */\n  refilterResponsesOnEnd() {\n    var _this$endEvent3;\n    if (!this.responses) {\n      return;\n    }\n    var pollEndTimestamp = ((_this$endEvent3 = this.endEvent) === null || _this$endEvent3 === void 0 ? void 0 : _this$endEvent3.getTs()) || Number.MAX_SAFE_INTEGER;\n    this.responses.getRelations().forEach(event => {\n      if (event.getTs() > pollEndTimestamp) {\n        var _this$responses;\n        (_this$responses = this.responses) === null || _this$responses === void 0 || _this$responses.removeEvent(event);\n      }\n    });\n    this.emit(PollEvent.Responses, this.responses);\n  }\n  validateEndEvent(endEvent) {\n    if (!endEvent) {\n      return false;\n    }\n    /**\n     * Repeated end events are ignored -\n     * only the first (valid) closure event by origin_server_ts is counted.\n     */\n    if (this.endEvent && this.endEvent.getTs() < endEvent.getTs()) {\n      return false;\n    }\n\n    /**\n     * MSC3381\n     * If a m.poll.end event is received from someone other than the poll creator or user with permission to redact\n     * others' messages in the room, the event must be ignored by clients due to being invalid.\n     */\n    var roomCurrentState = this.room.currentState;\n    var endEventSender = endEvent.getSender();\n    return !!endEventSender && (endEventSender === this.rootEvent.getSender() || roomCurrentState.maySendRedactionForEvent(this.rootEvent, endEventSender));\n  }\n}\n\n/**\n * Tests whether the event is a start, response or end poll event.\n *\n * @param event - Event to test\n * @returns true if the event is a poll event, else false\n */\nexport var isPollEvent = event => {\n  var eventType = event.getType();\n  return M_POLL_START.matches(eventType) || M_POLL_RESPONSE.matches(eventType) || M_POLL_END.matches(eventType);\n};\n//# sourceMappingURL=poll.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MAIN_ROOM_TIMELINE } from \"../@types/read_receipts.js\";\nimport { threadIdForReceipt } from \"../client.js\";\nimport { RoomEvent } from \"./room.js\";\nimport { logger } from \"../logger.js\";\n\n/**\n * The latest receipts we have for a room.\n */\nexport class RoomReceipts {\n  constructor(room) {\n    _defineProperty(this, \"room\", void 0);\n    _defineProperty(this, \"threadedReceipts\", void 0);\n    _defineProperty(this, \"unthreadedReceipts\", void 0);\n    _defineProperty(this, \"danglingReceipts\", void 0);\n    /**\n     * Look for dangling receipts for the given event ID,\n     * and add them to the thread of unthread receipts if found.\n     * @param event - the event to look for\n     */\n    _defineProperty(this, \"onTimelineEvent\", event => {\n      var eventId = event.getId();\n      if (!eventId) return;\n      var danglingReceipts = this.danglingReceipts.remove(eventId);\n      danglingReceipts === null || danglingReceipts === void 0 || danglingReceipts.forEach(danglingReceipt => {\n        // The receipt is a thread receipt\n        if (danglingReceipt.receipt.thread_id) {\n          this.threadedReceipts.set(danglingReceipt.receipt.thread_id, danglingReceipt.eventId, danglingReceipt.receiptType, danglingReceipt.userId, danglingReceipt.receipt.ts, danglingReceipt.synthetic);\n        } else {\n          this.unthreadedReceipts.set(eventId, danglingReceipt.receiptType, danglingReceipt.userId, danglingReceipt.receipt.ts, danglingReceipt.synthetic);\n        }\n      });\n    });\n    this.room = room;\n    this.threadedReceipts = new ThreadedReceipts(room);\n    this.unthreadedReceipts = new ReceiptsByUser(room);\n    this.danglingReceipts = new DanglingReceipts();\n    // We listen for timeline events so we can process dangling receipts\n    room.on(RoomEvent.Timeline, this.onTimelineEvent);\n  }\n\n  /**\n   * Remember the receipt information supplied. For each receipt:\n   *\n   * If we don't have the event for this receipt, store it as \"dangling\" so we\n   * can process it later.\n   *\n   * Otherwise store it per-user in either the threaded store for its\n   * thread_id, or the unthreaded store if there is no thread_id.\n   *\n   * Ignores any receipt that is before an existing receipt for the same user\n   * (in the same thread, if applicable). \"Before\" is defined by the\n   * unfilteredTimelineSet of the room.\n   */\n  add(receiptContent, synthetic) {\n    /*\n        Transform this structure:\n        {\n          \"$EVENTID\": {\n            \"m.read|m.read.private\": {\n              \"@user:example.org\": {\n                \"ts\": 1661,\n                \"thread_id\": \"main|$THREAD_ROOT_ID\" // or missing/undefined for an unthreaded receipt\n              }\n            }\n          },\n          ...\n        }\n        into maps of:\n        threaded :: threadid :: userId :: ReceiptInfo\n        unthreaded :: userId :: ReceiptInfo\n        dangling :: eventId :: DanglingReceipt\n    */\n    for (var [_eventId, eventReceipt] of Object.entries(receiptContent)) {\n      for (var [_receiptType, receiptsByUser] of Object.entries(eventReceipt)) {\n        for (var [_userId, _receipt] of Object.entries(receiptsByUser)) {\n          var referencedEvent = this.room.findEventById(_eventId);\n          if (!referencedEvent) {\n            this.danglingReceipts.add(new DanglingReceipt(_eventId, _receiptType, _userId, _receipt, synthetic));\n          } else if (_receipt.thread_id) {\n            this.threadedReceipts.set(_receipt.thread_id, _eventId, _receiptType, _userId, _receipt.ts, synthetic);\n          } else {\n            this.unthreadedReceipts.set(_eventId, _receiptType, _userId, _receipt.ts, synthetic);\n          }\n        }\n      }\n    }\n  }\n  hasUserReadEvent(userId, eventId) {\n    var unthreaded = this.unthreadedReceipts.get(userId);\n    if (unthreaded) {\n      if (isAfterOrSame(unthreaded.eventId, eventId, this.room)) {\n        // The unthreaded receipt is after this event, so we have read it.\n        return true;\n      }\n    }\n    var event = this.room.findEventById(eventId);\n    if (!event) {\n      // We don't know whether the user has read it - default to caution and say no.\n      // This shouldn't really happen and feels like it ought to be an exception: let's\n      // log a warn for now.\n      logger.warn(\"hasUserReadEvent event ID \".concat(eventId, \" not found in room \").concat(this.room.roomId, \": this shouldn't happen!\"));\n      return false;\n    }\n    var threadId = threadIdForReceipt(event);\n    var threaded = this.threadedReceipts.get(threadId, userId);\n    if (threaded) {\n      if (isAfterOrSame(threaded.eventId, eventId, this.room)) {\n        // The threaded receipt is after this event, so we have read it.\n        return true;\n      }\n    }\n\n    // TODO: what if they sent the second-last event in the thread?\n    if (this.userSentLatestEventInThread(threadId, userId)) {\n      // The user sent the latest message in this event's thread, so we\n      // consider everything in the thread to be read.\n      //\n      // Note: maybe we don't need this because synthetic receipts should\n      // do this job for us?\n      return true;\n    }\n\n    // Neither of the receipts were after the event, so it's unread.\n    return false;\n  }\n\n  /**\n   * @returns true if the thread with this ID can be found, and the supplied\n   *          user sent the latest message in it.\n   */\n  userSentLatestEventInThread(threadId, userId) {\n    var _this$room$getThread;\n    var timeline = threadId === MAIN_ROOM_TIMELINE ? this.room.getLiveTimeline().getEvents() : (_this$room$getThread = this.room.getThread(threadId)) === null || _this$room$getThread === void 0 ? void 0 : _this$room$getThread.timeline;\n    return !!(timeline && timeline.length > 0 && timeline[timeline.length - 1].getSender() === userId);\n  }\n}\n\n// --- implementation details ---\n\n/**\n * The information \"inside\" a receipt once it has been stored inside\n * RoomReceipts - what eventId it refers to, its type, and its ts.\n *\n * Does not contain userId or threadId since these are stored as keys of the\n * maps in RoomReceipts.\n */\nclass ReceiptInfo {\n  constructor(eventId, receiptType, ts) {\n    this.eventId = eventId;\n    this.receiptType = receiptType;\n    this.ts = ts;\n  }\n}\n\n/**\n * Everything we know about a receipt that is \"dangling\" because we can't find\n * the event to which it refers.\n */\nclass DanglingReceipt {\n  constructor(eventId, receiptType, userId, receipt, synthetic) {\n    this.eventId = eventId;\n    this.receiptType = receiptType;\n    this.userId = userId;\n    this.receipt = receipt;\n    this.synthetic = synthetic;\n  }\n}\nclass UserReceipts {\n  constructor(room) {\n    _defineProperty(this, \"room\", void 0);\n    /**\n     * The real receipt for this user.\n     */\n    _defineProperty(this, \"real\", void 0);\n    /**\n     * The synthetic receipt for this user. If this is defined, it is later than real.\n     */\n    _defineProperty(this, \"synthetic\", void 0);\n    this.room = room;\n    this.real = undefined;\n    this.synthetic = undefined;\n  }\n  set(synthetic, receiptInfo) {\n    if (synthetic) {\n      this.synthetic = receiptInfo;\n    } else {\n      this.real = receiptInfo;\n    }\n\n    // Preserve the invariant: synthetic is only defined if it's later than real\n    if (this.synthetic && this.real) {\n      if (isAfterOrSame(this.real.eventId, this.synthetic.eventId, this.room)) {\n        this.synthetic = undefined;\n      }\n    }\n  }\n\n  /**\n   * Return the latest receipt we have - synthetic if we have one (and it's\n   * later), otherwise real.\n   */\n  get() {\n    var _this$synthetic;\n    // Relies on the invariant that synthetic is only defined if it's later than real.\n    return (_this$synthetic = this.synthetic) !== null && _this$synthetic !== void 0 ? _this$synthetic : this.real;\n  }\n\n  /**\n   * Return the latest receipt we have of the specified type (synthetic or not).\n   */\n  getByType(synthetic) {\n    return synthetic ? this.synthetic : this.real;\n  }\n}\n\n/**\n * The latest receipt info we have, either for a single thread, or all the\n * unthreaded receipts for a room.\n *\n * userId: ReceiptInfo\n */\nclass ReceiptsByUser {\n  constructor(room) {\n    _defineProperty(this, \"room\", void 0);\n    /** map of userId: UserReceipts */\n    _defineProperty(this, \"data\", void 0);\n    this.room = room;\n    this.data = new Map();\n  }\n\n  /**\n   * Add the supplied receipt to our structure, if it is not earlier than the\n   * one we already hold for this user.\n   */\n  set(eventId, receiptType, userId, ts, synthetic) {\n    var userReceipts = getOrCreate(this.data, userId, () => new UserReceipts(this.room));\n    var existingReceipt = userReceipts.getByType(synthetic);\n    if (existingReceipt && isAfter(existingReceipt.eventId, eventId, this.room)) {\n      // The new receipt is before the existing one - don't store it.\n      return;\n    }\n\n    // Possibilities:\n    //\n    // 1. there was no existing receipt, or\n    // 2. the existing receipt was before this one, or\n    // 3. we were unable to compare the receipts.\n    //\n    // In the case of 3 it's difficult to decide what to do, so the\n    // most-recently-received receipt wins.\n    //\n    // Case 3 can only happen if the events for these receipts have\n    // disappeared, which is quite unlikely since the new one has just been\n    // checked, and the old one was checked before it was inserted here.\n    //\n    // We go ahead and store this receipt (replacing the other if it exists)\n    userReceipts.set(synthetic, new ReceiptInfo(eventId, receiptType, ts));\n  }\n\n  /**\n   * Find the latest receipt we have for this user. (Note - there is only one\n   * receipt per user, because we are already inside a specific thread or\n   * unthreaded list.)\n   *\n   * If there is a later synthetic receipt for this user, return that.\n   * Otherwise, return the real receipt.\n   *\n   * @returns the found receipt info, or undefined if we have no receipt for this user.\n   */\n  get(userId) {\n    var _this$data$get;\n    return (_this$data$get = this.data.get(userId)) === null || _this$data$get === void 0 ? void 0 : _this$data$get.get();\n  }\n}\n\n/**\n * The latest threaded receipts we have for a room.\n */\nclass ThreadedReceipts {\n  constructor(room) {\n    _defineProperty(this, \"room\", void 0);\n    /** map of threadId: ReceiptsByUser */\n    _defineProperty(this, \"data\", void 0);\n    this.room = room;\n    this.data = new Map();\n  }\n\n  /**\n   * Add the supplied receipt to our structure, if it is not earlier than one\n   * we already hold for this user in this thread.\n   */\n  set(threadId, eventId, receiptType, userId, ts, synthetic) {\n    var receiptsByUser = getOrCreate(this.data, threadId, () => new ReceiptsByUser(this.room));\n    receiptsByUser.set(eventId, receiptType, userId, ts, synthetic);\n  }\n\n  /**\n   * Find the latest threaded receipt for the supplied user in the supplied thread.\n   *\n   * @returns the found receipt info or undefined if we don't have one.\n   */\n  get(threadId, userId) {\n    var _this$data$get2;\n    return (_this$data$get2 = this.data.get(threadId)) === null || _this$data$get2 === void 0 ? void 0 : _this$data$get2.get(userId);\n  }\n}\n\n/**\n * All the receipts that we have received but can't process because we can't\n * find the event they refer to.\n *\n * We hold on to them so we can process them if their event arrives later.\n */\nclass DanglingReceipts {\n  constructor() {\n    /**\n     * eventId: DanglingReceipt[]\n     */\n    _defineProperty(this, \"data\", new Map());\n  }\n  /**\n   * Remember the supplied dangling receipt.\n   */\n  add(danglingReceipt) {\n    var danglingReceipts = getOrCreate(this.data, danglingReceipt.eventId, () => []);\n    danglingReceipts.push(danglingReceipt);\n  }\n\n  /**\n   * Remove and return the dangling receipts for the given event ID.\n   * @param eventId - the event ID to look for\n   * @returns the found dangling receipts, or undefined if we don't have one.\n   */\n  remove(eventId) {\n    var danglingReceipts = this.data.get(eventId);\n    this.data.delete(eventId);\n    return danglingReceipts;\n  }\n}\nfunction getOrCreate(m, key, createFn) {\n  var found = m.get(key);\n  if (found) {\n    return found;\n  } else {\n    var created = createFn();\n    m.set(key, created);\n    return created;\n  }\n}\n\n/**\n * Is left after right (or the same)?\n *\n * Only returns true if both events can be found, and left is after or the same\n * as right.\n *\n * @returns left \\>= right\n */\nfunction isAfterOrSame(leftEventId, rightEventId, room) {\n  var comparison = room.compareEventOrdering(leftEventId, rightEventId);\n  return comparison !== null && comparison >= 0;\n}\n\n/**\n * Is left strictly after right?\n *\n * Only returns true if both events can be found, and left is strictly after right.\n *\n * @returns left \\> right\n */\nfunction isAfter(leftEventId, rightEventId, room) {\n  var comparison = room.compareEventOrdering(leftEventId, rightEventId);\n  return comparison !== null && comparison > 0;\n}\n//# sourceMappingURL=room-receipts.js.map","/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { inMainTimelineForReceipt, threadIdForReceipt } from \"../client.js\";\n\n/**\n * Determine the order of two events in a room.\n *\n * In principle this should use the same order as the server, but in practice\n * this is difficult for events that were not received over the Sync API. See\n * MSC4033 for details.\n *\n * This implementation leans on the order of events within their timelines, and\n * falls back to comparing event timestamps when they are in different\n * timelines.\n *\n * See https://github.com/matrix-org/matrix-js-sdk/issues/3325 for where we are\n * tracking the work to fix this.\n *\n * @param room - the room we are looking in\n * @param leftEventId - the id of the first event\n * @param rightEventId - the id of the second event\n\n * @returns -1 if left \\< right, 1 if left \\> right, 0 if left == right, null if\n *          we can't tell (because we can't find the events).\n */\nexport function compareEventOrdering(room, leftEventId, rightEventId) {\n  var leftEvent = room.findEventById(leftEventId);\n  var rightEvent = room.findEventById(rightEventId);\n  if (!leftEvent || !rightEvent) {\n    // Without the events themselves, we can't find their thread or\n    // timeline, or guess based on timestamp, so we just don't know.\n    return null;\n  }\n\n  // Check whether the events are in the main timeline\n  var isLeftEventInMainTimeline = inMainTimelineForReceipt(leftEvent);\n  var isRightEventInMainTimeline = inMainTimelineForReceipt(rightEvent);\n  if (isLeftEventInMainTimeline && isRightEventInMainTimeline) {\n    return compareEventsInMainTimeline(room, leftEventId, rightEventId, leftEvent, rightEvent);\n  } else {\n    // At least one event is not in the timeline, so we can't use the room's\n    // unfiltered timeline set.\n    return compareEventsInThreads(leftEventId, rightEventId, leftEvent, rightEvent);\n  }\n}\nfunction compareEventsInMainTimeline(room, leftEventId, rightEventId, leftEvent, rightEvent) {\n  // Get the timeline set that contains all the events.\n  var timelineSet = room.getUnfilteredTimelineSet();\n\n  // If they are in the same timeline, compareEventOrdering does what we need\n  var compareSameTimeline = timelineSet.compareEventOrdering(leftEventId, rightEventId);\n  if (compareSameTimeline !== null) {\n    return compareSameTimeline;\n  }\n\n  // Find which timeline each event is in. Refuse to provide an ordering if we\n  // can't find either of the events.\n\n  var leftTimeline = timelineSet.getTimelineForEvent(leftEventId);\n  if (leftTimeline === timelineSet.getLiveTimeline()) {\n    // The left event is part of the live timeline, so it must be after the\n    // right event (since they are not in the same timeline or we would have\n    // returned after compareEventOrdering.\n    return 1;\n  }\n  var rightTimeline = timelineSet.getTimelineForEvent(rightEventId);\n  if (rightTimeline === timelineSet.getLiveTimeline()) {\n    // The right event is part of the live timeline, so it must be after the\n    // left event.\n    return -1;\n  }\n\n  // They are in older timeline sets (because they were fetched by paging up).\n  return guessOrderBasedOnTimestamp(leftEvent, rightEvent);\n}\nfunction compareEventsInThreads(leftEventId, rightEventId, leftEvent, rightEvent) {\n  var leftEventThreadId = threadIdForReceipt(leftEvent);\n  var rightEventThreadId = threadIdForReceipt(rightEvent);\n  var leftThread = leftEvent.getThread();\n  if (leftThread && leftEventThreadId === rightEventThreadId) {\n    // They are in the same thread, so we can ask the thread's timeline to\n    // figure it out for us\n    return leftThread.timelineSet.compareEventOrdering(leftEventId, rightEventId);\n  } else {\n    return guessOrderBasedOnTimestamp(leftEvent, rightEvent);\n  }\n}\n\n/**\n * Guess the order of events based on server timestamp. This is not good, but\n * difficult to avoid without MSC4033.\n *\n * See https://github.com/matrix-org/matrix-js-sdk/issues/3325\n */\nfunction guessOrderBasedOnTimestamp(leftEvent, rightEvent) {\n  var leftTs = leftEvent.getTs();\n  var rightTs = rightEvent.getTs();\n  if (leftTs < rightTs) {\n    return -1;\n  } else if (leftTs > rightTs) {\n    return 1;\n  } else {\n    return 0;\n  }\n}\n//# sourceMappingURL=compare-event-ordering.js.map","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport var Method = /*#__PURE__*/function (Method) {\n  Method[\"Get\"] = \"GET\";\n  Method[\"Put\"] = \"PUT\";\n  Method[\"Post\"] = \"POST\";\n  Method[\"Delete\"] = \"DELETE\";\n  Method[\"Options\"] = \"OPTIONS\";\n  Method[\"Head\"] = \"HEAD\";\n  Method[\"Patch\"] = \"PATCH\";\n  return Method;\n}({});\n//# sourceMappingURL=method.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2022 - 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { NamespacedValue } from \"../NamespacedValue.js\";\n/**\n * Construct a generic HTTP error. This is a JavaScript Error with additional information\n * specific to HTTP responses.\n * @param msg - The error message to include.\n * @param httpStatus - The HTTP response status code.\n * @param httpHeaders - The HTTP response headers.\n */\nexport class HTTPError extends Error {\n  constructor(msg, httpStatus, httpHeaders) {\n    super(msg);\n    this.httpStatus = httpStatus;\n    this.httpHeaders = httpHeaders;\n  }\n\n  /**\n   * Check if this error was due to rate-limiting on the server side (and should therefore be retried after a delay).\n   *\n   * If this returns `true`, {@link getRetryAfterMs} can be called to retrieve the server-side\n   * recommendation for the retry period.\n   *\n   * @returns Whether this error is due to rate-limiting.\n   */\n  isRateLimitError() {\n    return this.httpStatus === 429;\n  }\n\n  /**\n   * @returns The recommended delay in milliseconds to wait before retrying\n   * the request that triggered this error, or null if no delay is recommended.\n   * @throws Error if the recommended delay is an invalid value.\n   * @see {@link safeGetRetryAfterMs} for a version of this check that doesn't throw.\n   */\n  getRetryAfterMs() {\n    var _this$httpHeaders;\n    var retryAfter = (_this$httpHeaders = this.httpHeaders) === null || _this$httpHeaders === void 0 ? void 0 : _this$httpHeaders.get(\"Retry-After\");\n    if (retryAfter != null) {\n      if (/^\\d+$/.test(retryAfter)) {\n        var ms = Number.parseInt(retryAfter) * 1000;\n        if (!Number.isFinite(ms)) {\n          throw new Error(\"Retry-After header integer value is too large\");\n        }\n        return ms;\n      }\n      var date = new Date(retryAfter);\n      if (date.toUTCString() !== retryAfter) {\n        throw new Error(\"Retry-After header value is not a valid HTTP-date or non-negative decimal integer\");\n      }\n      return date.getTime() - Date.now();\n    }\n    return null;\n  }\n}\nexport class MatrixError extends HTTPError {\n  /**\n   * Construct a Matrix error. This is a JavaScript Error with additional\n   * information specific to the standard Matrix error response.\n   * @param errorJson - The Matrix error JSON returned from the homeserver.\n   * @param httpStatus - The numeric HTTP status code given\n   * @param httpHeaders - The HTTP response headers given\n   */\n  constructor() {\n    var errorJson = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n    var httpStatus = arguments.length > 1 ? arguments[1] : undefined;\n    var url = arguments.length > 2 ? arguments[2] : undefined;\n    var event = arguments.length > 3 ? arguments[3] : undefined;\n    var httpHeaders = arguments.length > 4 ? arguments[4] : undefined;\n    var message = errorJson.error || \"Unknown message\";\n    if (httpStatus) {\n      message = \"[\".concat(httpStatus, \"] \").concat(message);\n    }\n    if (url) {\n      message = \"\".concat(message, \" (\").concat(url, \")\");\n    }\n    super(\"MatrixError: \".concat(message), httpStatus, httpHeaders);\n    this.url = url;\n    this.event = event;\n    // The Matrix 'errcode' value, e.g. \"M_FORBIDDEN\".\n    _defineProperty(this, \"errcode\", void 0);\n    // The Matrix 'error' value.\n    _defineProperty(this, \"error\", void 0);\n    // The raw Matrix error JSON used to construct this object.\n    _defineProperty(this, \"data\", void 0);\n    this.errcode = errorJson.errcode;\n    this.error = errorJson.error;\n    this.name = errorJson.errcode || \"Unknown error code\";\n    this.data = errorJson;\n  }\n  isRateLimitError() {\n    return this.errcode === \"M_LIMIT_EXCEEDED\" || (this.errcode === \"M_UNKNOWN\" || this.errcode === undefined) && super.isRateLimitError();\n  }\n  getRetryAfterMs() {\n    var headerValue = super.getRetryAfterMs();\n    if (headerValue !== null) {\n      return headerValue;\n    }\n    // Note: retry_after_ms is deprecated as of spec version v1.10\n    if (this.errcode === \"M_LIMIT_EXCEEDED\" && \"retry_after_ms\" in this.data) {\n      if (!Number.isInteger(this.data.retry_after_ms)) {\n        throw new Error(\"retry_after_ms is not an integer\");\n      }\n      return this.data.retry_after_ms;\n    }\n    return null;\n  }\n\n  /**\n   * @returns this error expressed as a JSON payload\n   * for use by Widget API error responses.\n   */\n  asWidgetApiErrorData() {\n    var _this$httpStatus, _this$url, _this$errcode, _this$data$error;\n    var headers = {};\n    if (this.httpHeaders) {\n      for (var [name, value] of this.httpHeaders) {\n        headers[name] = value;\n      }\n    }\n    return {\n      http_status: (_this$httpStatus = this.httpStatus) !== null && _this$httpStatus !== void 0 ? _this$httpStatus : 400,\n      http_headers: headers,\n      url: (_this$url = this.url) !== null && _this$url !== void 0 ? _this$url : \"\",\n      response: _objectSpread({\n        errcode: (_this$errcode = this.errcode) !== null && _this$errcode !== void 0 ? _this$errcode : \"M_UNKNOWN\",\n        error: (_this$data$error = this.data.error) !== null && _this$data$error !== void 0 ? _this$data$error : \"Unknown message\"\n      }, this.data)\n    };\n  }\n\n  /**\n   * @returns a new {@link MatrixError} from a JSON payload\n   * received from Widget API error responses.\n   */\n  static fromWidgetApiErrorData(data) {\n    return new MatrixError(data.response, data.http_status, data.url, undefined, new Headers(data.http_headers));\n  }\n}\n\n/**\n * @returns The recommended delay in milliseconds to wait before retrying the request.\n * @param error - The error to check for a retry delay.\n * @param defaultMs - The delay to use if the error was not due to rate-limiting or if no valid delay is recommended.\n */\nexport function safeGetRetryAfterMs(error, defaultMs) {\n  if (!(error instanceof HTTPError) || !error.isRateLimitError()) {\n    return defaultMs;\n  }\n  try {\n    var _error$getRetryAfterM;\n    return (_error$getRetryAfterM = error.getRetryAfterMs()) !== null && _error$getRetryAfterM !== void 0 ? _error$getRetryAfterM : defaultMs;\n  } catch (_unused) {\n    return defaultMs;\n  }\n}\n\n/**\n * Construct a ConnectionError. This is a JavaScript Error indicating\n * that a request failed because of some error with the connection, either\n * CORS was not correctly configured on the server, the server didn't response,\n * the request timed out, or the internet connection on the client side went down.\n */\nexport class ConnectionError extends Error {\n  constructor(message, cause) {\n    super(message + (cause ? \": \".concat(cause.message) : \"\"));\n  }\n  get name() {\n    return \"ConnectionError\";\n  }\n}\n\n/**\n * Construct a TokenRefreshError. This indicates that a request failed due to the token being expired,\n * and attempting to refresh said token also failed but in a way which was not indicative of token invalidation.\n * Assumed to be a temporary failure.\n */\nexport class TokenRefreshError extends Error {\n  constructor(cause) {\n    var _cause$message;\n    super((_cause$message = cause === null || cause === void 0 ? void 0 : cause.message) !== null && _cause$message !== void 0 ? _cause$message : \"\");\n  }\n  get name() {\n    return \"TokenRefreshError\";\n  }\n}\n\n/**\n * Construct a TokenRefreshError. This indicates that a request failed due to the token being expired,\n * and attempting to refresh said token failed in a way indicative of token invalidation.\n */\nexport class TokenRefreshLogoutError extends Error {\n  constructor(cause) {\n    var _cause$message2;\n    super((_cause$message2 = cause === null || cause === void 0 ? void 0 : cause.message) !== null && _cause$message2 !== void 0 ? _cause$message2 : \"\");\n  }\n  get name() {\n    return \"TokenRefreshLogoutError\";\n  }\n}\nexport var MatrixSafetyErrorCode = new NamespacedValue(null, \"ORG.MATRIX.MSC4387_SAFETY\");\n\n/***\n * This error is thrown when the homeserver refuses to handle an action due to a\n * safety concern.\n * @see https://github.com/matrix-org/matrix-spec-proposals/pull/4387\n */\nexport class MatrixSafetyError extends MatrixError {\n  constructor() {\n    super(...arguments);\n    /**\n     * The kinds of harms detected by the server.\n     * @see https://github.com/matrix-org/matrix-spec-proposals/pull/4387 for a list of spec defined harms.\n     */\n    _defineProperty(this, \"harms\", void 0);\n    /**\n     * The date at which a request can be reattempted.\n     */\n    _defineProperty(this, \"expiry\", void 0);\n    var body = arguments.length <= 0 ? undefined : arguments[0];\n    this.harms = new Set(body && \"harms\" in body && Array.isArray(body.harms) ? body.harms : []);\n    this.message = \"\".concat(super.message, \" (\").concat([...this.harms].join(\", \"), \")\");\n    if (body && \"expiry\" in body && typeof body.expiry === \"number\") {\n      this.expiry = new Date(body.expiry);\n    }\n  }\n}\n//# sourceMappingURL=errors.js.map","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @experimental\n * Unencrypted access and (optional) refresh token\n */\n\n/**\n * @experimental\n * Function that performs token refresh using the given refreshToken.\n * Returns a promise that resolves to the refreshed access and (optional) refresh tokens.\n *\n * Can be passed to HttpApi instance as {@link IHttpOpts.tokenRefreshFunction} during client creation {@link ICreateClientOpts}\n */\n\n/** Options object for `FetchHttpApi` and {@link MatrixHttpApi}. */\n\n/** Options object for `FetchHttpApi.requestOtherUrl`. */\n\nexport var HttpApiEvent = /*#__PURE__*/function (HttpApiEvent) {\n  HttpApiEvent[\"SessionLoggedOut\"] = \"Session.logged_out\";\n  HttpApiEvent[\"NoConsent\"] = \"no_consent\";\n  return HttpApiEvent;\n}({});\n//# sourceMappingURL=interface.js.map","/*!\n * content-type\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict'\n\n/**\n * RegExp to match *( \";\" parameter ) in RFC 7231 sec 3.1.1.1\n *\n * parameter     = token \"=\" ( token / quoted-string )\n * token         = 1*tchar\n * tchar         = \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" / \"*\"\n *               / \"+\" / \"-\" / \".\" / \"^\" / \"_\" / \"`\" / \"|\" / \"~\"\n *               / DIGIT / ALPHA\n *               ; any VCHAR, except delimiters\n * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE\n * qdtext        = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text\n * obs-text      = %x80-FF\n * quoted-pair   = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n */\nvar PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *(\"(?:[\\u000b\\u0020\\u0021\\u0023-\\u005b\\u005d-\\u007e\\u0080-\\u00ff]|\\\\[\\u000b\\u0020-\\u00ff])*\"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g // eslint-disable-line no-control-regex\nvar TEXT_REGEXP = /^[\\u000b\\u0020-\\u007e\\u0080-\\u00ff]+$/ // eslint-disable-line no-control-regex\nvar TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/\n\n/**\n * RegExp to match quoted-pair in RFC 7230 sec 3.2.6\n *\n * quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n * obs-text    = %x80-FF\n */\nvar QESC_REGEXP = /\\\\([\\u000b\\u0020-\\u00ff])/g // eslint-disable-line no-control-regex\n\n/**\n * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6\n */\nvar QUOTE_REGEXP = /([\\\\\"])/g\n\n/**\n * RegExp to match type in RFC 7231 sec 3.1.1.1\n *\n * media-type = type \"/\" subtype\n * type       = token\n * subtype    = token\n */\nvar TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/\n\n/**\n * Module exports.\n * @public\n */\n\nexports.format = format\nexports.parse = parse\n\n/**\n * Format object to media type.\n *\n * @param {object} obj\n * @return {string}\n * @public\n */\n\nfunction format (obj) {\n  if (!obj || typeof obj !== 'object') {\n    throw new TypeError('argument obj is required')\n  }\n\n  var parameters = obj.parameters\n  var type = obj.type\n\n  if (!type || !TYPE_REGEXP.test(type)) {\n    throw new TypeError('invalid type')\n  }\n\n  var string = type\n\n  // append parameters\n  if (parameters && typeof parameters === 'object') {\n    var param\n    var params = Object.keys(parameters).sort()\n\n    for (var i = 0; i < params.length; i++) {\n      param = params[i]\n\n      if (!TOKEN_REGEXP.test(param)) {\n        throw new TypeError('invalid parameter name')\n      }\n\n      string += '; ' + param + '=' + qstring(parameters[param])\n    }\n  }\n\n  return string\n}\n\n/**\n * Parse media type to object.\n *\n * @param {string|object} string\n * @return {Object}\n * @public\n */\n\nfunction parse (string) {\n  if (!string) {\n    throw new TypeError('argument string is required')\n  }\n\n  // support req/res-like objects as argument\n  var header = typeof string === 'object'\n    ? getcontenttype(string)\n    : string\n\n  if (typeof header !== 'string') {\n    throw new TypeError('argument string is required to be a string')\n  }\n\n  var index = header.indexOf(';')\n  var type = index !== -1\n    ? header.slice(0, index).trim()\n    : header.trim()\n\n  if (!TYPE_REGEXP.test(type)) {\n    throw new TypeError('invalid media type')\n  }\n\n  var obj = new ContentType(type.toLowerCase())\n\n  // parse parameters\n  if (index !== -1) {\n    var key\n    var match\n    var value\n\n    PARAM_REGEXP.lastIndex = index\n\n    while ((match = PARAM_REGEXP.exec(header))) {\n      if (match.index !== index) {\n        throw new TypeError('invalid parameter format')\n      }\n\n      index += match[0].length\n      key = match[1].toLowerCase()\n      value = match[2]\n\n      if (value.charCodeAt(0) === 0x22 /* \" */) {\n        // remove quotes\n        value = value.slice(1, -1)\n\n        // remove escapes\n        if (value.indexOf('\\\\') !== -1) {\n          value = value.replace(QESC_REGEXP, '$1')\n        }\n      }\n\n      obj.parameters[key] = value\n    }\n\n    if (index !== header.length) {\n      throw new TypeError('invalid parameter format')\n    }\n  }\n\n  return obj\n}\n\n/**\n * Get content-type from req/res objects.\n *\n * @param {object}\n * @return {Object}\n * @private\n */\n\nfunction getcontenttype (obj) {\n  var header\n\n  if (typeof obj.getHeader === 'function') {\n    // res-like\n    header = obj.getHeader('content-type')\n  } else if (typeof obj.headers === 'object') {\n    // req-like\n    header = obj.headers && obj.headers['content-type']\n  }\n\n  if (typeof header !== 'string') {\n    throw new TypeError('content-type header is missing from object')\n  }\n\n  return header\n}\n\n/**\n * Quote a string if necessary.\n *\n * @param {string} val\n * @return {string}\n * @private\n */\n\nfunction qstring (val) {\n  var str = String(val)\n\n  // no need to quote tokens\n  if (TOKEN_REGEXP.test(str)) {\n    return str\n  }\n\n  if (str.length > 0 && !TEXT_REGEXP.test(str)) {\n    throw new TypeError('invalid parameter value')\n  }\n\n  return '\"' + str.replace(QUOTE_REGEXP, '\\\\$1') + '\"'\n}\n\n/**\n * Class to represent a content type.\n * @private\n */\nfunction ContentType (type) {\n  this.parameters = Object.create(null)\n  this.type = type\n}\n","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\n/*\nCopyright 2022 - 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { parse as parseContentType } from \"content-type\";\nimport { logger } from \"../logger.js\";\nimport { sleep } from \"../utils.js\";\nimport { ConnectionError, HTTPError, MatrixError, MatrixSafetyError, MatrixSafetyErrorCode, safeGetRetryAfterMs } from \"./errors.js\";\n\n// Ponyfill for https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout\nexport function timeoutSignal(ms) {\n  var controller = new AbortController();\n  setTimeout(() => {\n    controller.abort();\n  }, ms);\n  return controller.signal;\n}\nexport function anySignal(signals) {\n  var controller = new AbortController();\n  function cleanup() {\n    for (var signal of signals) {\n      signal.removeEventListener(\"abort\", onAbort);\n    }\n  }\n  function onAbort() {\n    controller.abort();\n    cleanup();\n  }\n  for (var signal of signals) {\n    if (signal.aborted) {\n      onAbort();\n      break;\n    }\n    signal.addEventListener(\"abort\", onAbort);\n  }\n  return {\n    signal: controller.signal,\n    cleanup\n  };\n}\n\n/**\n * Attempt to turn an HTTP error response into a Javascript Error.\n *\n * If it is a JSON response, we will parse it into a MatrixError. Otherwise\n * we return a generic Error.\n *\n * @param response - response object\n * @param body - raw body of the response\n * @returns\n */\nexport function parseErrorResponse(response, body) {\n  var _contentType, _contentType2;\n  var httpHeaders = isXhr(response) ? new Headers(response.getAllResponseHeaders().trim().split(/[\\r\\n]+/).map(header => {\n    var colonIdx = header.indexOf(\":\");\n    return [header.substring(0, colonIdx), header.substring(colonIdx + 1)];\n  })) : response.headers;\n  var contentType;\n  try {\n    contentType = getResponseContentType(httpHeaders);\n  } catch (e) {\n    return e;\n  }\n  if (((_contentType = contentType) === null || _contentType === void 0 ? void 0 : _contentType.type) === \"application/json\" && body) {\n    var errorBody = JSON.parse(body);\n    if (errorBody.errcode && MatrixSafetyErrorCode.matches(errorBody.errcode)) {\n      return new MatrixSafetyError(errorBody, response.status, isXhr(response) ? response.responseURL : response.url, undefined, httpHeaders);\n    }\n    return new MatrixError(errorBody, response.status, isXhr(response) ? response.responseURL : response.url, undefined, httpHeaders);\n  }\n  if (((_contentType2 = contentType) === null || _contentType2 === void 0 ? void 0 : _contentType2.type) === \"text/plain\") {\n    return new HTTPError(\"Server returned \".concat(response.status, \" error: \").concat(body), response.status, httpHeaders);\n  }\n  return new HTTPError(\"Server returned \".concat(response.status, \" error\"), response.status, httpHeaders);\n}\nfunction isXhr(response) {\n  return \"getResponseHeader\" in response;\n}\n\n/**\n * extract the Content-Type header from response headers, and\n * parse it to a `{type, parameters}` object.\n *\n * returns null if no content-type header could be found.\n *\n * @param response - response object\n * @returns parsed content-type header, or null if not found\n */\nfunction getResponseContentType(headers) {\n  var contentType = headers.get(\"Content-Type\");\n  if (contentType === null) return null;\n  try {\n    return parseContentType(contentType);\n  } catch (e) {\n    throw new Error(\"Error parsing Content-Type '\".concat(contentType, \"': \").concat(e));\n  }\n}\n\n/**\n * Retries a network operation run in a callback.\n * @param maxAttempts - maximum attempts to try\n * @param callback - callback that returns a promise of the network operation. If rejected with ConnectionError, it will be retried by calling the callback again.\n * @returns the result of the network operation\n * @throws {@link ConnectionError} If after maxAttempts the callback still throws ConnectionError\n */\nexport function retryNetworkOperation(_x, _x2) {\n  return _retryNetworkOperation.apply(this, arguments);\n}\n\n/**\n * Calculate the backoff time for a request retry attempt.\n * This produces wait times of 2, 4, 8, and 16 seconds (30s total) after which we give up. If the\n * failure was due to a rate limited request, the time specified in the error is returned.\n *\n * Returns -1 if the error is not retryable, or if we reach the maximum number of attempts.\n *\n * @param err - The error thrown by the http call\n * @param attempts - The number of attempts made so far, including the one that just failed.\n * @param retryConnectionError - Whether to retry on {@link ConnectionError} (CORS, connection is down, etc.)\n */\nfunction _retryNetworkOperation() {\n  _retryNetworkOperation = _asyncToGenerator(function* (maxAttempts, callback) {\n    var attempts = 0;\n    var lastConnectionError = null;\n    while (attempts < maxAttempts) {\n      try {\n        if (attempts > 0) {\n          var timeout = 1000 * Math.pow(2, attempts);\n          logger.log(\"network operation failed \".concat(attempts, \" times, retrying in \").concat(timeout, \"ms...\"));\n          yield sleep(timeout);\n        }\n        return yield callback();\n      } catch (err) {\n        if (err instanceof ConnectionError) {\n          attempts += 1;\n          lastConnectionError = err;\n        } else {\n          throw err;\n        }\n      }\n    }\n    throw lastConnectionError;\n  });\n  return _retryNetworkOperation.apply(this, arguments);\n}\nexport function calculateRetryBackoff(err, attempts, retryConnectionError) {\n  if (attempts > 4) {\n    return -1; // give up\n  }\n  if (err instanceof ConnectionError && !retryConnectionError) {\n    return -1;\n  }\n  if (err.httpStatus && Math.floor(err.httpStatus / 100) === 4 && err.httpStatus !== 429) {\n    // client error; no amount of retrying will save you now (except for rate limiting which is handled below)\n    return -1;\n  }\n  if (err.name === \"AbortError\") {\n    // this is a client timeout, that is already very high 60s/80s\n    // we don't want to retry, as it could do it for very long\n    return -1;\n  }\n\n  // If we are trying to send an event (or similar) that is too large in any way, then retrying won't help\n  if (err.name === \"M_TOO_LARGE\") {\n    return -1;\n  }\n  return safeGetRetryAfterMs(err, 1000 * Math.pow(2, attempts));\n}\n//# sourceMappingURL=utils.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2025 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixError, TokenRefreshLogoutError } from \"./errors.js\";\nimport { sleep } from \"../utils.js\";\n\n/**\n * This is an internal module. See {@link MatrixHttpApi} for the public class.\n */\n\nexport var TokenRefreshOutcome = /*#__PURE__*/function (TokenRefreshOutcome) {\n  TokenRefreshOutcome[\"Success\"] = \"success\";\n  TokenRefreshOutcome[\"Failure\"] = \"failure\";\n  TokenRefreshOutcome[\"Logout\"] = \"logout\";\n  return TokenRefreshOutcome;\n}({});\n// If the token expires in less than this time amount of time, we will eagerly refresh it before making the intended request.\nvar REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS = 500;\n// If we get an unknown token error and the token expires in less than this time amount of time, we will refresh it before making the intended request.\n// Otherwise, we will error as the token should not have expired yet and we need to avoid retrying indefinitely.\nvar REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS = 60 * 1000;\n/**\n * This class is responsible for managing the access token and refresh token for authenticated requests.\n * It will automatically refresh the access token when it is about to expire, and will handle unknown token errors.\n */\nexport class TokenRefresher {\n  constructor(opts) {\n    this.opts = opts;\n    /**\n     * Promise used to block authenticated requests during a token refresh to avoid repeated expected errors.\n     * @private\n     */\n    _defineProperty(this, \"tokenRefreshPromise\", void 0);\n    _defineProperty(this, \"latestTokenRefreshExpiry\", void 0);\n  }\n  /**\n   * This function is called before every request to ensure that the access token is valid.\n   * @returns a snapshot containing the access token and other properties which must be passed to the handleUnknownToken\n   *     handler if an M_UNKNOWN_TOKEN error is encountered.\n   */\n  prepareForRequest() {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      // Ensure our token is refreshed before we build the headers/params\n      yield _this.refreshIfNeeded();\n      return {\n        accessToken: _this.opts.accessToken,\n        refreshToken: _this.opts.refreshToken,\n        expiry: _this.latestTokenRefreshExpiry\n      };\n    })();\n  }\n  refreshIfNeeded() {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      if (_this2.tokenRefreshPromise) {\n        return _this2.tokenRefreshPromise;\n      }\n      // If we don't know the token expiry, we can't eagerly refresh\n      if (!_this2.latestTokenRefreshExpiry) return;\n      var expiresIn = _this2.latestTokenRefreshExpiry.getTime() - Date.now();\n      if (expiresIn <= REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS) {\n        yield _this2._handleUnknownToken();\n      }\n    })();\n  }\n\n  /**\n   * This function is called when an M_UNKNOWN_TOKEN error is encountered.\n   * It will attempt to refresh the access token if it is unknown, and will return a TokenRefreshOutcome.\n   * @param snapshot - the snapshot returned by prepareForRequest\n   * @param attempt - the number of attempts made for this request so far\n   * @returns a TokenRefreshOutcome indicating the result of the refresh attempt\n   */\n  handleUnknownToken(snapshot, attempt) {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      return _this3._handleUnknownToken(snapshot, attempt);\n    })();\n  }\n\n  /* eslint-disable @typescript-eslint/naming-convention */\n\n  _handleUnknownToken(snapshot, attempt) {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      if (snapshot !== null && snapshot !== void 0 && snapshot.expiry) {\n        // If our token is unknown, but it should not have expired yet, then we should not refresh\n        var expiresIn = snapshot.expiry.getTime() - Date.now();\n        // If it still has plenty of time left on the clock, we assume something else must be wrong and\n        // do not refresh. Otherwise if it's expired, or will soon, we try refreshing.\n        if (expiresIn >= REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS) {\n          return TokenRefreshOutcome.Logout;\n        }\n      }\n      if (!snapshot || (snapshot === null || snapshot === void 0 ? void 0 : snapshot.accessToken) === _this4.opts.accessToken) {\n        var _this4$tokenRefreshPr;\n        // If we have a snapshot, but the access token is the same as the current one then a refresh\n        // did not happen behind us but one may be ongoing anyway\n        (_this4$tokenRefreshPr = _this4.tokenRefreshPromise) !== null && _this4$tokenRefreshPr !== void 0 ? _this4$tokenRefreshPr : _this4.tokenRefreshPromise = _this4.doTokenRefresh(attempt);\n        try {\n          return yield _this4.tokenRefreshPromise;\n        } finally {\n          _this4.tokenRefreshPromise = undefined;\n        }\n      }\n\n      // We may end up here if the token was refreshed in the background due to another request\n      return TokenRefreshOutcome.Success;\n    })();\n  }\n\n  /**\n   * Attempt to refresh access tokens.\n   * On success, sets new access and refresh tokens in opts.\n   * @returns Promise that resolves to a boolean - true when token was refreshed successfully\n   */\n  doTokenRefresh(attempt) {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      if (!_this5.opts.refreshToken || !_this5.opts.tokenRefreshFunction) {\n        var _this5$opts$logger;\n        (_this5$opts$logger = _this5.opts.logger) === null || _this5$opts$logger === void 0 || _this5$opts$logger.error(\"Unable to refresh token - no refresh token or refresh function\");\n        return TokenRefreshOutcome.Logout;\n      }\n      if (attempt && attempt > 1) {\n        // Exponential backoff to ensure we don't trash the server, up to 2^5 seconds\n        yield sleep(1000 * Math.min(32, 2 ** attempt));\n      }\n      try {\n        var _this5$opts$logger2, _this5$opts$logger3;\n        (_this5$opts$logger2 = _this5.opts.logger) === null || _this5$opts$logger2 === void 0 || _this5$opts$logger2.debug(\"Attempting to refresh token\");\n        var {\n          accessToken,\n          refreshToken,\n          expiry\n        } = yield _this5.opts.tokenRefreshFunction(_this5.opts.refreshToken);\n        _this5.opts.accessToken = accessToken;\n        _this5.opts.refreshToken = refreshToken;\n        _this5.latestTokenRefreshExpiry = expiry;\n        (_this5$opts$logger3 = _this5.opts.logger) === null || _this5$opts$logger3 === void 0 || _this5$opts$logger3.debug(\"... token refresh complete, new token expiry:\", expiry);\n\n        // successfully got new tokens\n        return TokenRefreshOutcome.Success;\n      } catch (error) {\n        var _this5$opts$logger5;\n        // If we get a TokenError or MatrixError, we should log out, otherwise assume transient\n        if (error instanceof TokenRefreshLogoutError || error instanceof MatrixError) {\n          var _this5$opts$logger4;\n          (_this5$opts$logger4 = _this5.opts.logger) === null || _this5$opts$logger4 === void 0 || _this5$opts$logger4.error(\"Failed to refresh token\", error);\n          return TokenRefreshOutcome.Logout;\n        }\n        (_this5$opts$logger5 = _this5.opts.logger) === null || _this5$opts$logger5 === void 0 || _this5$opts$logger5.warn(\"Failed to refresh token\", error);\n        return TokenRefreshOutcome.Failure;\n      }\n    })();\n  }\n}\n//# sourceMappingURL=refresh.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixHttpApi} for the public class.\n */\n\nimport { checkObjectHasKeys, deepCopy, encodeParams } from \"../utils.js\";\nimport { Method } from \"./method.js\";\nimport { ConnectionError, MatrixError, TokenRefreshError } from \"./errors.js\";\nimport { HttpApiEvent } from \"./interface.js\";\nimport { anySignal, parseErrorResponse, timeoutSignal } from \"./utils.js\";\nimport { TokenRefresher, TokenRefreshOutcome } from \"./refresh.js\";\nexport class FetchHttpApi {\n  constructor(eventEmitter, opts) {\n    var _opts$useAuthorizatio;\n    this.eventEmitter = eventEmitter;\n    this.opts = opts;\n    _defineProperty(this, \"abortController\", new AbortController());\n    _defineProperty(this, \"tokenRefresher\", void 0);\n    checkObjectHasKeys(opts, [\"baseUrl\", \"prefix\"]);\n    if (!opts.onlyData) {\n      throw new Error(\"Constructing FetchHttpApi without `onlyData=true` is no longer supported.\");\n    }\n    opts.useAuthorizationHeader = (_opts$useAuthorizatio = opts.useAuthorizationHeader) !== null && _opts$useAuthorizatio !== void 0 ? _opts$useAuthorizatio : true;\n    this.tokenRefresher = new TokenRefresher(opts);\n  }\n  abort() {\n    this.abortController.abort();\n    this.abortController = new AbortController();\n  }\n  fetch(resource, options) {\n    if (this.opts.fetchFn) {\n      return this.opts.fetchFn(resource, options);\n    }\n    return globalThis.fetch(resource, options);\n  }\n\n  /**\n   * Sets the base URL for the identity server\n   * @param url - The new base url\n   */\n  setIdBaseUrl(url) {\n    this.opts.idBaseUrl = url;\n  }\n  idServerRequest(method, path, params, prefix, accessToken) {\n    if (!this.opts.idBaseUrl) {\n      throw new Error(\"No identity server base URL set\");\n    }\n    var queryParams = undefined;\n    var body = undefined;\n    if (method === Method.Get) {\n      queryParams = params;\n    } else {\n      body = params;\n    }\n    var fullUri = this.getUrl(path, queryParams, prefix, this.opts.idBaseUrl);\n    var opts = {\n      json: true,\n      headers: {}\n    };\n    if (accessToken) {\n      opts.headers.Authorization = \"Bearer \".concat(accessToken);\n    }\n    return this.requestOtherUrl(method, fullUri, body, opts);\n  }\n\n  /**\n   * Perform an authorised request to the homeserver.\n   * @param method - The HTTP method e.g. \"GET\".\n   * @param path - The HTTP path <b>after</b> the supplied prefix e.g.\n   * \"/createRoom\".\n   *\n   * @param queryParams - A dict of query params (these will NOT be\n   * urlencoded). If unspecified, there will be no query params.\n   *\n   * @param body - The HTTP JSON body.\n   *\n   * @param paramOpts - additional options.\n   * When `paramOpts.doNotAttemptTokenRefresh` is true, token refresh will not be attempted\n   * when an expired token is encountered. Used to only attempt token refresh once.\n   *\n   * @returns The parsed response.\n   * @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.\n   */\n  authedRequest(method, path) {\n    var queryParams = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n    var body = arguments.length > 3 ? arguments[3] : undefined;\n    var paramOpts = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};\n    return this.doAuthedRequest(1, method, path, queryParams, body, paramOpts);\n  }\n\n  // Wrapper around public method authedRequest to allow for tracking retry attempt counts\n  doAuthedRequest(attempt, method, path, queryParams, body) {\n    var _arguments = arguments,\n      _this = this;\n    return _asyncToGenerator(function* () {\n      var paramOpts = _arguments.length > 5 && _arguments[5] !== undefined ? _arguments[5] : {};\n      // avoid mutating paramOpts so they can be used on retry\n      var opts = deepCopy(paramOpts);\n      // we have to manually copy the abortSignal over as it is not a plain object\n      opts.abortSignal = paramOpts.abortSignal;\n\n      // Take a snapshot of the current token state before we start the request so we can reference it if we error\n      var requestSnapshot = yield _this.tokenRefresher.prepareForRequest();\n      if (requestSnapshot.accessToken) {\n        if (_this.opts.useAuthorizationHeader) {\n          if (!opts.headers) {\n            opts.headers = {};\n          }\n          if (!opts.headers.Authorization) {\n            opts.headers.Authorization = \"Bearer \".concat(requestSnapshot.accessToken);\n          }\n          if (queryParams.access_token) {\n            delete queryParams.access_token;\n          }\n        } else if (!queryParams.access_token) {\n          queryParams.access_token = requestSnapshot.accessToken;\n        }\n      }\n      try {\n        var response = yield _this.request(method, path, queryParams, body, opts);\n        return response;\n      } catch (error) {\n        if (!(error instanceof MatrixError)) {\n          throw error;\n        }\n        if (error.errcode === \"M_UNKNOWN_TOKEN\") {\n          var outcome = yield _this.tokenRefresher.handleUnknownToken(requestSnapshot, attempt);\n          if (outcome === TokenRefreshOutcome.Success) {\n            // if we got a new token retry the request\n            return _this.doAuthedRequest(attempt + 1, method, path, queryParams, body, paramOpts);\n          }\n          if (outcome === TokenRefreshOutcome.Failure) {\n            throw new TokenRefreshError(error);\n          }\n          if (!(opts !== null && opts !== void 0 && opts.inhibitLogoutEmit)) {\n            _this.eventEmitter.emit(HttpApiEvent.SessionLoggedOut, error);\n          }\n        } else if (error.errcode == \"M_CONSENT_NOT_GIVEN\") {\n          _this.eventEmitter.emit(HttpApiEvent.NoConsent, error.message, error.data.consent_uri);\n        }\n        throw error;\n      }\n    })();\n  }\n\n  /**\n   * Perform a request to the homeserver without any credentials.\n   * @param method - The HTTP method e.g. \"GET\".\n   * @param path - The HTTP path <b>after</b> the supplied prefix e.g.\n   * \"/createRoom\".\n   *\n   * @param queryParams - A dict of query params (these will NOT be\n   * urlencoded). If unspecified, there will be no query params.\n   *\n   * @param body - The HTTP JSON body.\n   *\n   * @param opts - additional options\n   *\n   * @returns The parsed response.\n   * @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.\n   */\n  request(method, path, queryParams, body, opts) {\n    var fullUri = this.getUrl(path, queryParams, opts === null || opts === void 0 ? void 0 : opts.prefix, opts === null || opts === void 0 ? void 0 : opts.baseUrl);\n    return this.requestOtherUrl(method, fullUri, body, opts);\n  }\n\n  /**\n   * Perform a request to an arbitrary URL.\n   * @param method - The HTTP method e.g. \"GET\".\n   * @param url - The HTTP URL object.\n   *\n   * @param body - The HTTP JSON body.\n   *\n   * @param opts - additional options\n   *\n   * @returns The parsed response.\n   * @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.\n   */\n  requestOtherUrl(method, url, body) {\n    var _arguments2 = arguments,\n      _this2 = this;\n    return _asyncToGenerator(function* () {\n      var _this2$opts$logger, _opts$localTimeoutMs, _opts$keepAlive, _body$constructor;\n      var opts = _arguments2.length > 3 && _arguments2[3] !== undefined ? _arguments2[3] : {};\n      if (opts.json !== undefined && opts.rawResponseBody !== undefined) {\n        throw new Error(\"Invalid call to `FetchHttpApi` sets both `opts.json` and `opts.rawResponseBody`\");\n      }\n      var urlForLogs = _this2.sanitizeUrlForLogs(url);\n      (_this2$opts$logger = _this2.opts.logger) === null || _this2$opts$logger === void 0 || _this2$opts$logger.debug(\"FetchHttpApi: --> \".concat(method, \" \").concat(urlForLogs));\n      var headers = Object.assign({}, opts.headers || {});\n      var jsonResponse = !opts.rawResponseBody && opts.json !== false;\n      if (jsonResponse) {\n        if (!headers[\"Accept\"]) {\n          headers[\"Accept\"] = \"application/json\";\n        }\n      }\n      var timeout = (_opts$localTimeoutMs = opts.localTimeoutMs) !== null && _opts$localTimeoutMs !== void 0 ? _opts$localTimeoutMs : _this2.opts.localTimeoutMs;\n      var keepAlive = (_opts$keepAlive = opts.keepAlive) !== null && _opts$keepAlive !== void 0 ? _opts$keepAlive : false;\n      var signals = [_this2.abortController.signal];\n      if (timeout !== undefined) {\n        signals.push(timeoutSignal(timeout));\n      }\n      if (opts.abortSignal) {\n        signals.push(opts.abortSignal);\n      }\n\n      // If the body is an object, encode it as JSON and set the `Content-Type` header,\n      // unless that has been explicitly inhibited by setting `opts.json: false`.\n      // We can't use getPrototypeOf here as objects made in other contexts e.g. over postMessage won't have same ref\n      var data;\n      if (opts.json !== false && (body === null || body === void 0 || (_body$constructor = body.constructor) === null || _body$constructor === void 0 ? void 0 : _body$constructor.name) === Object.name) {\n        data = JSON.stringify(body);\n        if (!headers[\"Content-Type\"]) {\n          headers[\"Content-Type\"] = \"application/json\";\n        }\n      } else {\n        data = body;\n      }\n      var {\n        signal,\n        cleanup\n      } = anySignal(signals);\n\n      // Set cache mode based on presence of Authorization header.\n      // Browsers/proxies do not cache responses to requests with Authorization headers.\n      // So specifying \"no-cache\" is redundant, and actually prevents caching\n      // of preflight requests in CORS scenarios. As such, we only set \"no-cache\"\n      // when there is no Authorization header.\n      var cacheMode = \"Authorization\" in headers ? undefined : \"no-cache\";\n      var res;\n      var start = Date.now();\n      try {\n        var _this2$opts$logger2;\n        res = yield _this2.fetch(url, {\n          signal,\n          method,\n          body: data,\n          headers,\n          mode: \"cors\",\n          redirect: \"follow\",\n          referrer: \"\",\n          referrerPolicy: \"no-referrer\",\n          cache: cacheMode,\n          credentials: \"omit\",\n          // we send credentials via headers\n          keepalive: keepAlive,\n          priority: opts.priority\n        });\n        (_this2$opts$logger2 = _this2.opts.logger) === null || _this2$opts$logger2 === void 0 || _this2$opts$logger2.debug(\"FetchHttpApi: <-- \".concat(method, \" \").concat(urlForLogs, \" [\").concat(Date.now() - start, \"ms \").concat(res.status, \"]\"));\n      } catch (e) {\n        var _this2$opts$logger3;\n        (_this2$opts$logger3 = _this2.opts.logger) === null || _this2$opts$logger3 === void 0 || _this2$opts$logger3.debug(\"FetchHttpApi: <-- \".concat(method, \" \").concat(urlForLogs, \" [\").concat(Date.now() - start, \"ms \").concat(e, \"]\"));\n        if (e.name === \"AbortError\") {\n          throw e;\n        }\n        throw new ConnectionError(\"fetch failed\", e);\n      } finally {\n        cleanup();\n      }\n      if (!res.ok) {\n        throw parseErrorResponse(res, yield res.text());\n      }\n      if (opts.rawResponseBody) {\n        return yield res.blob();\n      } else if (jsonResponse) {\n        return yield res.json();\n      } else {\n        return yield res.text();\n      }\n    })();\n  }\n  sanitizeUrlForLogs(url) {\n    try {\n      var asUrl;\n      if (typeof url === \"string\") {\n        asUrl = new URL(url);\n      } else {\n        asUrl = url;\n      }\n      // Remove the values of any URL params that could contain potential secrets\n      var sanitizedQs = new URLSearchParams();\n      for (var key of asUrl.searchParams.keys()) {\n        sanitizedQs.append(key, \"xxx\");\n      }\n      var sanitizedQsString = sanitizedQs.toString();\n      var sanitizedQsUrlPiece = sanitizedQsString ? \"?\".concat(sanitizedQsString) : \"\";\n      return asUrl.origin + asUrl.pathname + sanitizedQsUrlPiece;\n    } catch (_unused) {\n      // defensive coding for malformed url\n      return \"??\";\n    }\n  }\n  /**\n   * Form and return a homeserver request URL based on the given path params and prefix.\n   * @param path - The HTTP path <b>after</b> the supplied prefix e.g. \"/createRoom\".\n   * @param queryParams - A dict of query params (these will NOT be urlencoded).\n   * @param prefix - The full prefix to use e.g. \"/_matrix/client/v2_alpha\", defaulting to this.opts.prefix.\n   * @param baseUrl - The baseUrl to use e.g. \"https://matrix.org\", defaulting to this.opts.baseUrl.\n   * @returns URL\n   */\n  getUrl(path, queryParams, prefix, baseUrl) {\n    var baseUrlWithFallback = baseUrl !== null && baseUrl !== void 0 ? baseUrl : this.opts.baseUrl;\n    var baseUrlWithoutTrailingSlash = baseUrlWithFallback.endsWith(\"/\") ? baseUrlWithFallback.slice(0, -1) : baseUrlWithFallback;\n    var url = new URL(baseUrlWithoutTrailingSlash + (prefix !== null && prefix !== void 0 ? prefix : this.opts.prefix) + path);\n    // If there are any params, encode and append them to the URL.\n    if (this.opts.extraParams || queryParams) {\n      var mergedParams = _objectSpread(_objectSpread({}, this.opts.extraParams), queryParams);\n      encodeParams(mergedParams, url.searchParams);\n    }\n    return url;\n  }\n}\n//# sourceMappingURL=fetch.js.map","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport var ClientPrefix = /*#__PURE__*/function (ClientPrefix) {\n  /**\n   * A constant representing the URI path for Client-Server API endpoints versioned at v1.\n   */\n  ClientPrefix[\"V1\"] = \"/_matrix/client/v1\";\n  /**\n   * A constant representing the URI path for Client-Server API endpoints versioned at v3.\n   */\n  ClientPrefix[\"V3\"] = \"/_matrix/client/v3\";\n  /**\n   * A constant representing the URI path for as-yet unspecified Client-Server HTTP APIs.\n   */\n  ClientPrefix[\"Unstable\"] = \"/_matrix/client/unstable\";\n  return ClientPrefix;\n}({});\nexport var IdentityPrefix = /*#__PURE__*/function (IdentityPrefix) {\n  /**\n   * URI path for the v2 identity API\n   */\n  IdentityPrefix[\"V2\"] = \"/_matrix/identity/v2\";\n  return IdentityPrefix;\n}({});\nexport var MediaPrefix = /*#__PURE__*/function (MediaPrefix) {\n  /**\n   * A constant representing the URI path for Client-Server API Media endpoints versioned at v1.\n   */\n  MediaPrefix[\"V1\"] = \"/_matrix/media/v1\";\n  /**\n   * A constant representing the URI path for Client-Server API Media endpoints versioned at v3.\n   */\n  MediaPrefix[\"V3\"] = \"/_matrix/media/v3\";\n  return MediaPrefix;\n}({});\n//# sourceMappingURL=prefix.js.map","/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/* A re-implementation of the javascript callback functions (setTimeout,\n * clearTimeout; setInterval and clearInterval are not yet implemented) which\n * try to improve handling of large clock jumps (as seen when\n * suspending/resuming the system).\n *\n * In particular, if a timeout would have fired while the system was suspended,\n * it will instead fire as soon as possible after resume.\n */\n\nimport { logger } from \"./logger.js\";\n\n// we schedule a callback at least this often, to check if we've missed out on\n// some wall-clock time due to being suspended.\nvar TIMER_CHECK_PERIOD_MS = 1000;\n\n// counter, for making up ids to return from setTimeout\nvar count = 0;\n\n// the key for our callback with the real globalThis.setTimeout\nvar realCallbackKey;\n// a sorted list of the callbacks to be run.\n// each is an object with keys [runAt, func, params, key].\nvar callbackList = [];\n\n// var debuglog = logger.log.bind(logger);\n/* istanbul ignore next */\nvar debuglog = function debuglog() {};\n\n/**\n * reimplementation of window.setTimeout, which will call the callback if\n * the wallclock time goes past the deadline.\n *\n * @param func -   callback to be called after a delay\n * @param delayMs -  number of milliseconds to delay by\n *\n * @returns an identifier for this callback, which may be passed into\n *                   clearTimeout later.\n */\nexport function setTimeout(func, delayMs) {\n  for (var _len = arguments.length, params = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n    params[_key - 2] = arguments[_key];\n  }\n  delayMs = delayMs || 0;\n  if (delayMs < 0) {\n    delayMs = 0;\n  }\n  var runAt = Date.now() + delayMs;\n  var key = count++;\n  debuglog(\"setTimeout: scheduling cb\", key, \"at\", runAt, \"(delay\", delayMs, \")\");\n  var data = {\n    runAt: runAt,\n    func: func,\n    params: params,\n    key: key\n  };\n\n  // figure out where it goes in the list\n  var idx = binarySearch(callbackList, function (el) {\n    return el.runAt - runAt;\n  });\n  callbackList.splice(idx, 0, data);\n  scheduleRealCallback();\n  return key;\n}\n\n/**\n * reimplementation of window.clearTimeout, which mirrors setTimeout\n *\n * @param key -   result from an earlier setTimeout call\n */\nexport function clearTimeout(key) {\n  if (callbackList.length === 0) {\n    return;\n  }\n\n  // remove the element from the list\n  var i;\n  for (i = 0; i < callbackList.length; i++) {\n    var cb = callbackList[i];\n    if (cb.key == key) {\n      callbackList.splice(i, 1);\n      break;\n    }\n  }\n\n  // iff it was the first one in the list, reschedule our callback.\n  if (i === 0) {\n    scheduleRealCallback();\n  }\n}\n\n// use the real globalThis.setTimeout to schedule a callback to runCallbacks.\nfunction scheduleRealCallback() {\n  if (realCallbackKey) {\n    globalThis.clearTimeout(realCallbackKey);\n  }\n  var first = callbackList[0];\n  if (!first) {\n    debuglog(\"scheduleRealCallback: no more callbacks, not rescheduling\");\n    return;\n  }\n  var timestamp = Date.now();\n  var delayMs = Math.min(first.runAt - timestamp, TIMER_CHECK_PERIOD_MS);\n  debuglog(\"scheduleRealCallback: now:\", timestamp, \"delay:\", delayMs);\n  realCallbackKey = globalThis.setTimeout(runCallbacks, delayMs);\n}\nfunction runCallbacks() {\n  var timestamp = Date.now();\n  debuglog(\"runCallbacks: now:\", timestamp);\n\n  // get the list of things to call\n  var callbacksToRun = [];\n  // eslint-disable-next-line\n  while (true) {\n    var first = callbackList[0];\n    if (!first || first.runAt > timestamp) {\n      break;\n    }\n    var cb = callbackList.shift();\n    debuglog(\"runCallbacks: popping\", cb.key);\n    callbacksToRun.push(cb);\n  }\n\n  // reschedule the real callback before running our functions, to\n  // keep the codepaths the same whether or not our functions\n  // register their own setTimeouts.\n  scheduleRealCallback();\n  for (var _cb of callbacksToRun) {\n    try {\n      _cb.func.apply(globalThis, _cb.params);\n    } catch (e) {\n      logger.error(\"Uncaught exception in callback function\", e);\n    }\n  }\n}\n\n/* search in a sorted array.\n *\n * returns the index of the last element for which func returns\n * greater than zero, or array.length if no such element exists.\n */\nfunction binarySearch(array, func) {\n  // min is inclusive, max exclusive.\n  var min = 0;\n  var max = array.length;\n  while (min < max) {\n    var mid = min + max >> 1;\n    var res = func(array[mid]);\n    if (res > 0) {\n      // the element at 'mid' is too big; set it as the new max.\n      max = mid;\n    } else {\n      // the element at 'mid' is too small. 'min' is inclusive, so +1.\n      min = mid + 1;\n    }\n  }\n  // presumably, min==max now.\n  return min;\n}\n//# sourceMappingURL=realtime-callbacks.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { FetchHttpApi } from \"./fetch.js\";\nimport { MediaPrefix } from \"./prefix.js\";\nimport { removeElement } from \"../utils.js\";\nimport * as callbacks from \"../realtime-callbacks.js\";\nimport { Method } from \"./method.js\";\nimport { ConnectionError } from \"./errors.js\";\nimport { parseErrorResponse } from \"./utils.js\";\nexport * from \"./interface.js\";\nexport * from \"./prefix.js\";\nexport * from \"./errors.js\";\nexport * from \"./method.js\";\nexport * from \"./utils.js\";\nexport class MatrixHttpApi extends FetchHttpApi {\n  constructor() {\n    super(...arguments);\n    _defineProperty(this, \"uploads\", []);\n  }\n  /**\n   * Upload content to the homeserver\n   *\n   * @param file - The object to upload. On a browser, something that\n   *   can be sent to XMLHttpRequest.send (typically a File).  Under node.js,\n   *   a Buffer, String or ReadStream.\n   *\n   * @param opts - options object\n   *\n   * @returns Promise which resolves to response object, or rejects with an error (usually a MatrixError).\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  uploadContent(file) {\n    var _opts$includeFilename, _opts$abortController, _opts$type, _opts$name;\n    var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    var includeFilename = (_opts$includeFilename = opts.includeFilename) !== null && _opts$includeFilename !== void 0 ? _opts$includeFilename : true;\n    var abortController = (_opts$abortController = opts.abortController) !== null && _opts$abortController !== void 0 ? _opts$abortController : new AbortController();\n\n    // If the file doesn't have a mime type, use a default since the HS errors if we don't supply one.\n    var contentType = ((_opts$type = opts.type) !== null && _opts$type !== void 0 ? _opts$type : file.type) || \"application/octet-stream\";\n    var fileName = (_opts$name = opts.name) !== null && _opts$name !== void 0 ? _opts$name : file.name;\n    var upload = {\n      loaded: 0,\n      total: 0,\n      abortController\n    };\n    var uploadResolvers = Promise.withResolvers();\n    if (globalThis.XMLHttpRequest) {\n      var xhr = new globalThis.XMLHttpRequest();\n      var timeoutFn = function timeoutFn() {\n        xhr.abort();\n        uploadResolvers.reject(new Error(\"Timeout\"));\n      };\n\n      // set an initial timeout of 30s; we'll advance it each time we get a progress notification\n      var timeoutTimer = callbacks.setTimeout(timeoutFn, 30000);\n      xhr.onreadystatechange = function () {\n        switch (xhr.readyState) {\n          case globalThis.XMLHttpRequest.DONE:\n            callbacks.clearTimeout(timeoutTimer);\n            try {\n              if (xhr.status === 0) {\n                throw new DOMException(xhr.statusText, \"AbortError\"); // mimic fetch API\n              }\n              if (!xhr.responseText) {\n                throw new Error(\"No response body.\");\n              }\n              if (xhr.status >= 400) {\n                uploadResolvers.reject(parseErrorResponse(xhr, xhr.responseText));\n              } else {\n                uploadResolvers.resolve(JSON.parse(xhr.responseText));\n              }\n            } catch (err) {\n              if (err.name === \"AbortError\") {\n                uploadResolvers.reject(err);\n                return;\n              }\n              uploadResolvers.reject(new ConnectionError(\"request failed\", err));\n            }\n            break;\n        }\n      };\n      xhr.upload.onprogress = ev => {\n        var _opts$progressHandler;\n        callbacks.clearTimeout(timeoutTimer);\n        upload.loaded = ev.loaded;\n        upload.total = ev.total;\n        timeoutTimer = callbacks.setTimeout(timeoutFn, 30000);\n        (_opts$progressHandler = opts.progressHandler) === null || _opts$progressHandler === void 0 || _opts$progressHandler.call(opts, {\n          loaded: ev.loaded,\n          total: ev.total\n        });\n      };\n      var url = this.getUrl(\"/upload\", undefined, MediaPrefix.V3);\n      if (includeFilename && fileName) {\n        url.searchParams.set(\"filename\", encodeURIComponent(fileName));\n      }\n      if (!this.opts.useAuthorizationHeader && this.opts.accessToken) {\n        url.searchParams.set(\"access_token\", encodeURIComponent(this.opts.accessToken));\n      }\n      xhr.open(Method.Post, url.href);\n      if (this.opts.useAuthorizationHeader && this.opts.accessToken) {\n        xhr.setRequestHeader(\"Authorization\", \"Bearer \" + this.opts.accessToken);\n      }\n      xhr.setRequestHeader(\"Content-Type\", contentType);\n      xhr.send(file);\n      abortController.signal.addEventListener(\"abort\", () => {\n        xhr.abort();\n      });\n    } else {\n      var queryParams = {};\n      if (includeFilename && fileName) {\n        queryParams.filename = fileName;\n      }\n      var headers = {\n        \"Content-Type\": contentType\n      };\n      this.authedRequest(Method.Post, \"/upload\", queryParams, file, {\n        prefix: MediaPrefix.V3,\n        headers,\n        abortSignal: abortController.signal\n      }).then(uploadResolvers.resolve, uploadResolvers.reject);\n    }\n\n    // remove the upload from the list on completion\n    upload.promise = uploadResolvers.promise.finally(() => {\n      removeElement(this.uploads, elem => elem === upload);\n    });\n    abortController.signal.addEventListener(\"abort\", () => {\n      removeElement(this.uploads, elem => elem === upload);\n      uploadResolvers.reject(new DOMException(\"Aborted\", \"AbortError\"));\n    });\n    this.uploads.push(upload);\n    return upload.promise;\n  }\n  cancelUpload(promise) {\n    var upload = this.uploads.find(u => u.promise === promise);\n    if (upload) {\n      upload.abortController.abort();\n      return true;\n    }\n    return false;\n  }\n  getCurrentUploads() {\n    return this.uploads;\n  }\n\n  /**\n   * Get the content repository url with query parameters.\n   * @returns An object with a 'base', 'path' and 'params' for base URL,\n   *          path and query parameters respectively.\n   */\n  getContentUri() {\n    return {\n      base: this.opts.baseUrl,\n      path: MediaPrefix.V3 + \"/upload\",\n      params: {\n        access_token: this.opts.accessToken\n      }\n    };\n  }\n}\n//# sourceMappingURL=index.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { Method } from \"./http-api/index.js\";\n// How often we update the server capabilities.\n// 6 hours - an arbitrary value, but they should change very infrequently.\nvar CAPABILITIES_CACHE_MS = 6 * 60 * 60 * 1000;\n\n// How long we want before retrying if we couldn't fetch\nvar CAPABILITIES_RETRY_MS = 30 * 1000;\nexport var RoomVersionStability = /*#__PURE__*/function (RoomVersionStability) {\n  RoomVersionStability[\"Stable\"] = \"stable\";\n  RoomVersionStability[\"Unstable\"] = \"unstable\";\n  return RoomVersionStability;\n}({});\n\n/**\n * A representation of the capabilities advertised by a homeserver as defined by\n * [Capabilities negotiation](https://spec.matrix.org/v1.6/client-server-api/#get_matrixclientv3capabilities).\n */\n\n/**\n * Manages storing and periodically refreshing the server capabilities.\n */\nexport class ServerCapabilities {\n  constructor(logger, http) {\n    var _this = this;\n    this.logger = logger;\n    this.http = http;\n    _defineProperty(this, \"capabilities\", void 0);\n    _defineProperty(this, \"retryTimeout\", void 0);\n    _defineProperty(this, \"refreshTimeout\", void 0);\n    /**\n     * Fetches the latest server capabilities from the homeserver and returns them, or rejects\n     * on failure.\n     */\n    _defineProperty(this, \"fetchCapabilities\", /*#__PURE__*/_asyncToGenerator(function* () {\n      var resp = yield _this.http.authedRequest(Method.Get, \"/capabilities\");\n      _this.capabilities = resp[\"capabilities\"];\n      return _this.capabilities;\n    }));\n    _defineProperty(this, \"poll\", /*#__PURE__*/_asyncToGenerator(function* () {\n      try {\n        yield _this.fetchCapabilities();\n        _this.clearTimeouts();\n        _this.refreshTimeout = setTimeout(_this.poll, CAPABILITIES_CACHE_MS);\n        _this.logger.debug(\"Fetched new server capabilities\");\n      } catch (e) {\n        _this.clearTimeouts();\n        var howLong = Math.floor(CAPABILITIES_RETRY_MS + Math.random() * 5000);\n        _this.retryTimeout = setTimeout(_this.poll, howLong);\n        _this.logger.warn(\"Failed to refresh capabilities: retrying in \".concat(howLong, \"ms\"), e);\n      }\n    }));\n  }\n\n  /**\n   * Starts periodically fetching the server capabilities.\n   */\n  start() {\n    this.poll().then();\n  }\n\n  /**\n   * Stops the service\n   */\n  stop() {\n    this.clearTimeouts();\n  }\n\n  /**\n   * Returns the cached capabilities, or undefined if none are cached.\n   * @returns the current capabilities, if any.\n   */\n  getCachedCapabilities() {\n    return this.capabilities;\n  }\n  clearTimeouts() {\n    if (this.refreshTimeout) {\n      clearInterval(this.refreshTimeout);\n      this.refreshTimeout = undefined;\n    }\n    if (this.retryTimeout) {\n      clearTimeout(this.retryTimeout);\n      this.retryTimeout = undefined;\n    }\n  }\n}\n//# sourceMappingURL=serverCapabilities.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nimport { logger as loggerInstance } from \"../logger.js\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.js\";\nvar logger = loggerInstance.getChild(\"RoomStickyEvents\");\nexport var RoomStickyEventsEvent = /*#__PURE__*/function (RoomStickyEventsEvent) {\n  RoomStickyEventsEvent[\"Update\"] = \"RoomStickyEvents.Update\";\n  return RoomStickyEventsEvent;\n}({});\nfunction assertIsUserId(value) {\n  if (typeof value !== \"string\") throw new Error(\"Not a string\");\n  if (!value.startsWith(\"@\")) throw new Error(\"Not a userId\");\n}\n\n/**\n * Tracks sticky events on behalf of one room, and fires an event\n * whenever a sticky event is updated or replaced.\n */\nexport class RoomStickyEventsStore extends TypedEventEmitter {\n  constructor() {\n    super(...arguments);\n    /**\n     * Sticky event map is a nested map of:\n     *  eventType -> `content.sticky_key sender` -> StickyMatrixEvent[]\n     *\n     * The events are ordered in latest to earliest expiry, so that the first event\n     * in the array will always be the \"current\" one.\n     */\n    _defineProperty(this, \"stickyEventsMap\", new Map());\n    /**\n     * These are sticky events that have no sticky key and therefore exist outside the tuple\n     * system above. They are just held in this Set until they expire.\n     */\n    _defineProperty(this, \"unkeyedStickyEvents\", new Set());\n    _defineProperty(this, \"stickyEventTimer\", void 0);\n    _defineProperty(this, \"nextStickyEventExpiryTs\", Number.MAX_SAFE_INTEGER);\n    /**\n     * Clean out any expired sticky events.\n     */\n    _defineProperty(this, \"cleanExpiredStickyEvents\", () => {\n      var now = Date.now();\n      var removedEvents = [];\n\n      // We will recalculate this as we check all events.\n      this.nextStickyEventExpiryTs = Number.MAX_SAFE_INTEGER;\n      for (var [eventType, innerEvents] of this.stickyEventsMap.entries()) {\n        var _this$stickyEventsMap;\n        for (var [innerMapKey, [currentEvent, ...previousEvents]] of innerEvents) {\n          // we only added items with `sticky` into this map so we can assert non-null here\n          if (now >= currentEvent.unstableStickyExpiresAt) {\n            logger.debug(\"Expiring sticky event\", currentEvent.getId());\n            removedEvents.push(currentEvent);\n            this.stickyEventsMap.get(eventType).delete(innerMapKey);\n          } else {\n            // Ensure we remove any previous events which have now expired, to avoid unbounded memory consumption.\n            this.stickyEventsMap.get(eventType).set(innerMapKey, [currentEvent, ...previousEvents.filter(e => e.unstableStickyExpiresAt <= now)]);\n            // If not removing the event, check to see if it's the next lowest expiry.\n            this.nextStickyEventExpiryTs = Math.min(this.nextStickyEventExpiryTs, currentEvent.unstableStickyExpiresAt);\n          }\n        }\n        // Clean up map after use.\n        if (((_this$stickyEventsMap = this.stickyEventsMap.get(eventType)) === null || _this$stickyEventsMap === void 0 ? void 0 : _this$stickyEventsMap.size) === 0) {\n          this.stickyEventsMap.delete(eventType);\n        }\n      }\n      for (var event of this.unkeyedStickyEvents) {\n        if (now >= event.unstableStickyExpiresAt) {\n          logger.debug(\"Expiring sticky event\", event.getId());\n          this.unkeyedStickyEvents.delete(event);\n          removedEvents.push(event);\n        } else {\n          // If not removing the event, check to see if it's the next lowest expiry.\n          this.nextStickyEventExpiryTs = Math.min(this.nextStickyEventExpiryTs, event.unstableStickyExpiresAt);\n        }\n      }\n      if (removedEvents.length) {\n        this.emit(RoomStickyEventsEvent.Update, [], [], removedEvents);\n      }\n      // Finally, schedule the next run.\n      this.scheduleStickyTimer();\n    });\n  }\n  /**\n   * Sort two sticky events by order of expiry. This assumes the sticky events have the same\n   * `type`, `sticky_key` and `sender`.\n   * @returns A positive value if event A will expire sooner, or a negative value if event B will expire sooner.\n   */\n  static sortStickyEvent(eventA, eventB) {\n    var _eventB$getId, _eventA$getId;\n    // Sticky events with the same key have to use the same expiration duration.\n    // Hence, comparing via `origin_server_ts` yields the exact same result as comparing their expiration time.\n    if (eventB.getTs() !== eventA.getTs()) {\n      return eventB.getTs() - eventA.getTs();\n    }\n    if (((_eventB$getId = eventB.getId()) !== null && _eventB$getId !== void 0 ? _eventB$getId : \"\") > ((_eventA$getId = eventA.getId()) !== null && _eventA$getId !== void 0 ? _eventA$getId : \"\")) {\n      return 1;\n    }\n\n    // This should fail as we've got corruption in our sticky array.\n    throw Error(\"Comparing two sticky events with the same event ID is not allowed.\");\n  }\n\n  /**\n   * Generate the correct key for an event to be found in the inner maps of `stickyEventsMap`.\n   * @param stickyKey The sticky key of an event.\n   * @param sender The sender of the event.\n   */\n  static stickyMapKey(stickyKey, sender) {\n    return \"\".concat(stickyKey).concat(sender);\n  }\n\n  /**\n   * Get all sticky events that are currently active.\n   * @returns An iterable set of events.\n   */\n  *getStickyEvents() {\n    yield* this.unkeyedStickyEvents;\n    for (var innerMap of this.stickyEventsMap.values()) {\n      // Inner map contains a map of sender+stickykeys => all sticky events\n      for (var events of innerMap.values()) {\n        // The first sticky event is the \"current\" one in the sticky map.\n        yield events[0];\n      }\n    }\n  }\n\n  /**\n   * Get an active sticky event that match the given `type`, `sender`, and `stickyKey`\n   * @param type The event `type`.\n   * @param sender The sender of the sticky event.\n   * @param stickyKey The sticky key used by the event.\n   * @returns A matching active sticky event, or undefined.\n   */\n  getKeyedStickyEvent(sender, type, stickyKey) {\n    var _this$stickyEventsMap2;\n    assertIsUserId(sender);\n    return (_this$stickyEventsMap2 = this.stickyEventsMap.get(type)) === null || _this$stickyEventsMap2 === void 0 || (_this$stickyEventsMap2 = _this$stickyEventsMap2.get(RoomStickyEventsStore.stickyMapKey(stickyKey, sender))) === null || _this$stickyEventsMap2 === void 0 ? void 0 : _this$stickyEventsMap2[0];\n  }\n\n  /**\n   * Get active sticky events without a sticky key that match the given `type` and `sender`.\n   * @param type The event `type`.\n   * @param sender The sender of the sticky event.\n   * @returns An array of matching sticky events.\n   */\n  getUnkeyedStickyEvent(sender, type) {\n    return [...this.unkeyedStickyEvents].filter(ev => ev.getType() === type && ev.getSender() === sender);\n  }\n\n  /**\n   * Adds a sticky event into the local sticky event map.\n   *\n   * NOTE: This will not cause `RoomEvent.StickyEvents` to be emitted.\n   *\n   * @throws If the `event` does not contain valid sticky data.\n   * @param event The MatrixEvent that contains sticky data.\n   * @returns An object describing whether the event was added to the map,\n   *          and the previous event it may have replaced.\n   */\n  addStickyEvent(event) {\n    var _this$stickyEventsMap3, _this$stickyEventsMap4, _this$stickyEventsMap5;\n    var stickyKey = event.getContent().msc4354_sticky_key;\n    if (typeof stickyKey !== \"string\" && stickyKey !== undefined) {\n      throw new Error(\"\".concat(event.getId(), \" is missing msc4354_sticky_key\"));\n    }\n\n    // With this we have the guarantee, that all events in stickyEventsMap are correctly formatted\n    if (event.unstableStickyExpiresAt === undefined) {\n      throw new Error(\"\".concat(event.getId(), \" is missing msc4354_sticky.duration_ms\"));\n    }\n    var sender = event.getSender();\n    var type = event.getType();\n    assertIsUserId(sender);\n    if (event.unstableStickyExpiresAt <= Date.now()) {\n      logger.info(\"ignored sticky event with older expiration time than current time\", stickyKey);\n      return {\n        added: false\n      };\n    }\n\n    // While we fully expect the server to always provide the correct value,\n    // this is just insurance to protect against attacks on our Map.\n    if (!sender.startsWith(\"@\")) {\n      throw new Error(\"Expected sender to start with @\");\n    }\n    var stickyEvent = event;\n    if (stickyKey === undefined) {\n      this.unkeyedStickyEvents.add(stickyEvent);\n      // Recalculate the next expiry time.\n      this.nextStickyEventExpiryTs = Math.min(event.unstableStickyExpiresAt, this.nextStickyEventExpiryTs);\n      this.scheduleStickyTimer();\n      return {\n        added: true\n      };\n    }\n\n    // Why this is safe:\n    // A type may contain anything but the *sender* is tightly\n    // constrained so that a key will always end with a @<user_id>\n    // E.g. Where a malicious event type might be \"rtc.member.event@foo:bar\" the key becomes:\n    // \"rtc.member.event.@foo:bar@bar:baz\"\n    var innerMapKey = RoomStickyEventsStore.stickyMapKey(stickyKey, sender);\n    var currentEventSet = [stickyEvent, ...((_this$stickyEventsMap3 = (_this$stickyEventsMap4 = this.stickyEventsMap.get(type)) === null || _this$stickyEventsMap4 === void 0 ? void 0 : _this$stickyEventsMap4.get(innerMapKey)) !== null && _this$stickyEventsMap3 !== void 0 ? _this$stickyEventsMap3 : [])].sort(RoomStickyEventsStore.sortStickyEvent);\n    if (!this.stickyEventsMap.has(type)) {\n      this.stickyEventsMap.set(type, new Map());\n    }\n    (_this$stickyEventsMap5 = this.stickyEventsMap.get(type)) === null || _this$stickyEventsMap5 === void 0 || _this$stickyEventsMap5.set(innerMapKey, currentEventSet);\n\n    // Recalculate the next expiry time.\n    this.nextStickyEventExpiryTs = Math.min(stickyEvent.unstableStickyExpiresAt, this.nextStickyEventExpiryTs);\n    this.scheduleStickyTimer();\n    return {\n      added: currentEventSet[0] === stickyEvent,\n      prevEvent: currentEventSet === null || currentEventSet === void 0 ? void 0 : currentEventSet[1]\n    };\n  }\n\n  /**\n   * Add a series of sticky events, emitting `RoomEvent.StickyEvents` if any\n   * changes were made.\n   * @param events A set of new sticky events.\n   */\n  addStickyEvents(events) {\n    var added = [];\n    var updated = [];\n    for (var event of events) {\n      try {\n        var result = this.addStickyEvent(event);\n        if (result.added) {\n          if (result.prevEvent) {\n            // e is validated as a StickyMatrixEvent by virtue of `addStickyEvent` returning added: true.\n            updated.push({\n              current: event,\n              previous: result.prevEvent\n            });\n          } else {\n            added.push(event);\n          }\n        }\n      } catch (ex) {\n        logger.warn(\"ignored invalid sticky event\", ex);\n      }\n    }\n    if (added.length || updated.length) this.emit(RoomStickyEventsEvent.Update, added, updated, []);\n    this.scheduleStickyTimer();\n  }\n\n  /**\n   * Schedule the sticky event expiry timer. The timer will\n   * run immediately if an event has already expired.\n   */\n  scheduleStickyTimer() {\n    if (this.stickyEventTimer) {\n      clearTimeout(this.stickyEventTimer);\n      this.stickyEventTimer = undefined;\n    }\n    if (this.nextStickyEventExpiryTs === Number.MAX_SAFE_INTEGER) {\n      // We have no events due to expire.\n      return;\n    } // otherwise, schedule in the future\n    this.stickyEventTimer = setTimeout(this.cleanExpiredStickyEvents, this.nextStickyEventExpiryTs - Date.now());\n  }\n  /**\n   * Handles incoming event redactions. Checks the sticky map\n   * for any active sticky events being redacted.\n   * @param redactedEvent The MatrixEvent OR event ID of the event being redacted. MAY not be a sticky event.\n   */\n  handleRedaction(redactedEvent) {\n    // Note, we do not adjust`nextStickyEventExpiryTs` here.\n    // If this event happens to be the most recent expiring event\n    // then we may do one extra iteration of cleanExpiredStickyEvents\n    // but this saves us having to iterate over all events here to calculate\n    // the next expiry time.\n\n    // Note, as soon as we find a positive match on an event in this function\n    // we can return. There is no need to continue iterating on a positive match\n    // as an event can only appear in one map.\n\n    // Handle unkeyedStickyEvents first since it's *quick*.\n    var redactEventId = typeof redactedEvent === \"string\" ? redactedEvent : redactedEvent.getId();\n    for (var event of this.unkeyedStickyEvents) {\n      if (event.getId() === redactEventId) {\n        this.unkeyedStickyEvents.delete(event);\n        this.emit(RoomStickyEventsEvent.Update, [], [], [event]);\n        return;\n      }\n    }\n\n    // Faster method of finding the event since we have the event cached.\n    if (typeof redactedEvent !== \"string\" && !redactedEvent.isRedacted()) {\n      var _innerMap$get, _this$stickyEventsMap6;\n      var stickyKey = redactedEvent.getContent().msc4354_sticky_key;\n      if (typeof stickyKey !== \"string\" && stickyKey !== undefined) {\n        return; // Not a sticky event.\n      }\n      var eventType = redactedEvent.getType();\n      var sender = redactedEvent.getSender();\n      assertIsUserId(sender);\n      var innerMap = this.stickyEventsMap.get(eventType);\n      if (!innerMap) {\n        return;\n      }\n      var mapKey = RoomStickyEventsStore.stickyMapKey(stickyKey, sender);\n      var [currentEvent, ...previousEvents] = (_innerMap$get = innerMap.get(mapKey)) !== null && _innerMap$get !== void 0 ? _innerMap$get : [];\n      if (!currentEvent) {\n        // No event current in the map so ignore.\n        return;\n      }\n      logger.debug(\"Redaction for \".concat(redactEventId, \" under sticky key \").concat(stickyKey));\n      // Revert to previous state, taking care to skip any other redacted events.\n      var newEvents = previousEvents.filter(e => !e.isRedacted()).sort(RoomStickyEventsStore.sortStickyEvent);\n      (_this$stickyEventsMap6 = this.stickyEventsMap.get(eventType)) === null || _this$stickyEventsMap6 === void 0 || _this$stickyEventsMap6.set(mapKey, newEvents);\n      if (newEvents.length) {\n        this.emit(RoomStickyEventsEvent.Update, [], [{\n          // This looks confusing. This emits that the newer event\n          // has been redacted and the previous event has taken it's place.\n          previous: currentEvent,\n          current: newEvents[0]\n        }], []);\n      } else {\n        // We did not find a previous event, so just expire.\n        innerMap.delete(mapKey);\n        if (innerMap.size === 0) {\n          this.stickyEventsMap.delete(eventType);\n        }\n        this.emit(RoomStickyEventsEvent.Update, [], [], [currentEvent]);\n      }\n      return;\n    }\n\n    // We only know the event ID of the redacted event, so we need to\n    // traverse the map to find our event.\n    for (var _innerMap of this.stickyEventsMap.values()) {\n      for (var [_currentEvent] of _innerMap.values()) {\n        if (_currentEvent.getId() !== redactEventId) {\n          continue;\n        }\n        // Found the event.\n        return this.handleRedaction(_currentEvent);\n      }\n    }\n  }\n\n  /**\n   * Clear all events and stop the timer from firing.\n   */\n  clear() {\n    this.stickyEventsMap.clear();\n    // Unschedule timer.\n    this.nextStickyEventExpiryTs = Number.MAX_SAFE_INTEGER;\n    this.scheduleStickyTimer();\n  }\n}\n//# sourceMappingURL=room-sticky-events.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2015 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { M_POLL_START } from \"matrix-events-sdk\";\nimport { DuplicateStrategy, EventTimelineSet } from \"./event-timeline-set.js\";\nimport { Direction, EventTimeline } from \"./event-timeline.js\";\nimport { getHttpUriForMxc } from \"../content-repo.js\";\nimport * as utils from \"../utils.js\";\nimport { normalize, noUnsafeEventProps, removeElement } from \"../utils.js\";\nimport { MatrixEvent, MatrixEventEvent } from \"./event.js\";\nimport { EventStatus } from \"./event-status.js\";\nimport { RoomMember } from \"./room-member.js\";\nimport { RoomSummary } from \"./room-summary.js\";\nimport { logger } from \"../logger.js\";\nimport { TypedReEmitter } from \"../ReEmitter.js\";\nimport { EVENT_VISIBILITY_CHANGE_TYPE, EventType, RelationType, RoomCreateTypeField, RoomType, UNSIGNED_THREAD_ID_FIELD, UNSTABLE_ELEMENT_FUNCTIONAL_USERS } from \"../@types/event.js\";\nimport { PendingEventOrdering } from \"../client.js\";\nimport { Filter } from \"../filter.js\";\nimport { RoomStateEvent } from \"./room-state.js\";\nimport { BeaconEvent } from \"./beacon.js\";\nimport { FILTER_RELATED_BY_REL_TYPES, FILTER_RELATED_BY_SENDERS, Thread, THREAD_RELATION_TYPE, ThreadEvent, ThreadFilterType } from \"./thread.js\";\nimport { MAIN_ROOM_TIMELINE, ReceiptType } from \"../@types/read_receipts.js\";\nimport { RelationsContainer } from \"./relations-container.js\";\nimport { ReadReceipt, synthesizeReceipt } from \"./read-receipt.js\";\nimport { isPollEvent, Poll, PollEvent } from \"./poll.js\";\nimport { RoomReceipts } from \"./room-receipts.js\";\nimport { compareEventOrdering } from \"./compare-event-ordering.js\";\nimport { KnownMembership } from \"../@types/membership.js\";\nimport { RoomVersionStability } from \"../serverCapabilities.js\";\nimport { RoomStickyEventsStore, RoomStickyEventsEvent } from \"./room-sticky-events.js\";\n\n// These constants are used as sane defaults when the homeserver doesn't support\n// the m.room_versions capability. In practice, KNOWN_SAFE_ROOM_VERSION should be\n// the same as the common default room version whereas SAFE_ROOM_VERSIONS are the\n// room versions which are considered okay for people to run without being asked\n// to upgrade (ie: \"stable\"). Eventually, we should remove these when all homeservers\n// return an m.room_versions capability.\nexport var KNOWN_SAFE_ROOM_VERSION = \"10\";\nvar SAFE_ROOM_VERSIONS = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\"];\n// When inserting a visibility event affecting event `eventId`, we\n// need to scan through existing visibility events for `eventId`.\n// In theory, this could take an unlimited amount of time if:\n//\n// - the visibility event was sent by a moderator; and\n// - `eventId` already has many visibility changes (usually, it should\n//   be 2 or less); and\n// - for some reason, the visibility changes are received out of order\n//   (usually, this shouldn't happen at all).\n//\n// For this reason, we limit the number of events to scan through,\n// expecting that a broken visibility change for a single event in\n// an extremely uncommon case (possibly a DoS) is a small\n// price to pay to keep matrix-js-sdk responsive.\nvar MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH = 30;\nexport var NotificationCountType = /*#__PURE__*/function (NotificationCountType) {\n  NotificationCountType[\"Highlight\"] = \"highlight\";\n  NotificationCountType[\"Total\"] = \"total\";\n  return NotificationCountType;\n}({});\nexport var RoomEvent = /*#__PURE__*/function (RoomEvent) {\n  RoomEvent[\"MyMembership\"] = \"Room.myMembership\";\n  RoomEvent[\"Tags\"] = \"Room.tags\";\n  RoomEvent[\"AccountData\"] = \"Room.accountData\";\n  RoomEvent[\"Receipt\"] = \"Room.receipt\";\n  RoomEvent[\"Name\"] = \"Room.name\";\n  RoomEvent[\"Redaction\"] = \"Room.redaction\";\n  RoomEvent[\"RedactionCancelled\"] = \"Room.redactionCancelled\";\n  RoomEvent[\"LocalEchoUpdated\"] = \"Room.localEchoUpdated\";\n  RoomEvent[\"Timeline\"] = \"Room.timeline\";\n  RoomEvent[\"TimelineReset\"] = \"Room.timelineReset\";\n  RoomEvent[\"TimelineRefresh\"] = \"Room.TimelineRefresh\";\n  RoomEvent[\"OldStateUpdated\"] = \"Room.OldStateUpdated\";\n  RoomEvent[\"CurrentStateUpdated\"] = \"Room.CurrentStateUpdated\";\n  RoomEvent[\"HistoryImportedWithinTimeline\"] = \"Room.historyImportedWithinTimeline\";\n  RoomEvent[\"UnreadNotifications\"] = \"Room.UnreadNotifications\";\n  RoomEvent[\"Summary\"] = \"Room.Summary\";\n  return RoomEvent;\n}({});\nexport class Room extends ReadReceipt {\n  /**\n   * Construct a new Room.\n   *\n   * <p>For a room, we store an ordered sequence of timelines, which may or may not\n   * be continuous. Each timeline lists a series of events, as well as tracking\n   * the room state at the start and the end of the timeline. It also tracks\n   * forward and backward pagination tokens, as well as containing links to the\n   * next timeline in the sequence.\n   *\n   * <p>There is one special timeline - the 'live' timeline, which represents the\n   * timeline to which events are being added in real-time as they are received\n   * from the /sync API. Note that you should not retain references to this\n   * timeline - even if it is the current timeline right now, it may not remain\n   * so if the server gives us a timeline gap in /sync.\n   *\n   * <p>In order that we can find events from their ids later, we also maintain a\n   * map from event_id to timeline and index.\n   *\n   * @param roomId - Required. The ID of this room.\n   * @param client - Required. The client, used to lazy load members.\n   * @param myUserId - Required. The ID of the syncing user.\n   * @param opts - Configuration options\n   */\n  constructor(roomId, client, myUserId) {\n    var _this;\n    var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n    // In some cases, we add listeners for every displayed Matrix event, so it's\n    // common to have quite a few more than the default limit.\n    super();\n    _this = this;\n    this.roomId = roomId;\n    this.client = client;\n    this.myUserId = myUserId;\n    this.opts = opts;\n    _defineProperty(this, \"reEmitter\", void 0);\n    _defineProperty(this, \"txnToEvent\", new Map());\n    // Pending in-flight requests { string: MatrixEvent }\n    _defineProperty(this, \"notificationCounts\", {});\n    _defineProperty(this, \"bumpStamp\", undefined);\n    _defineProperty(this, \"threadNotifications\", new Map());\n    _defineProperty(this, \"cachedThreadReadReceipts\", new Map());\n    // Useful to know at what point the current user has started using threads in this room\n    _defineProperty(this, \"oldestThreadedReceiptTs\", Infinity);\n    /**\n     * A record of the latest unthread receipts per user\n     * This is useful in determining whether a user has read a thread or not\n     */\n    _defineProperty(this, \"unthreadedReceipts\", new Map());\n    _defineProperty(this, \"timelineSets\", void 0);\n    _defineProperty(this, \"polls\", new Map());\n    /**\n     * Empty array if the timeline sets have not been initialised. After initialisation:\n     * 0: All threads\n     * 1: Threads the current user has participated in\n     */\n    _defineProperty(this, \"threadsTimelineSets\", []);\n    // any filtered timeline sets we're maintaining for this room\n    _defineProperty(this, \"filteredTimelineSets\", {});\n    // filter_id: timelineSet\n    _defineProperty(this, \"timelineNeedsRefresh\", false);\n    _defineProperty(this, \"pendingEventList\", void 0);\n    // read by megolm via getter; boolean value - null indicates \"use global value\"\n    _defineProperty(this, \"blacklistUnverifiedDevices\", void 0);\n    _defineProperty(this, \"selfMembership\", void 0);\n    /**\n     * A `Hero` is a stripped `m.room.member` event which contains the important renderable fields from the event.\n     *\n     * It is used in MSC4186 (Simplified Sliding Sync) as a replacement for the old `summary` field.\n     *\n     * When we are doing old-style (`/v3/sync`) sync, we simulate the SSS behaviour by constructing\n     * a `Hero` object based on the user id we get from the summary. Obviously, in that case,\n     * the `Hero` will lack a `displayName` or `avatarUrl`.\n     */\n    _defineProperty(this, \"heroes\", null);\n    // flags to stop logspam about missing m.room.create events\n    _defineProperty(this, \"getTypeWarning\", false);\n    _defineProperty(this, \"membersPromise\", void 0);\n    // XXX: These should be read-only\n    /**\n     * The human-readable display name for this room.\n     */\n    _defineProperty(this, \"name\", void 0);\n    /**\n     * The un-homoglyphed name for this room.\n     */\n    _defineProperty(this, \"normalizedName\", void 0);\n    /**\n     * Dict of room tags; the keys are the tag name and the values\n     * are any metadata associated with the tag - e.g. `{ \"fav\" : { order: 1 } }`\n     */\n    _defineProperty(this, \"tags\", {});\n    // $tagName: { $metadata: $value }\n    /**\n     * accountData Dict of per-room account_data events; the keys are the\n     * event type and the values are the events.\n     */\n    _defineProperty(this, \"accountData\", new Map());\n    // $eventType: $event\n    /**\n     * The room summary.\n     */\n    _defineProperty(this, \"summary\", null);\n    /**\n     * oldState The state of the room at the time of the oldest event in the live timeline.\n     *\n     * @deprecated Present for backwards compatibility.\n     *             Use getLiveTimeline().getState(EventTimeline.BACKWARDS) instead\n     */\n    _defineProperty(this, \"oldState\", void 0);\n    /**\n     * currentState The state of the room at the time of the newest event in the timeline.\n     *\n     * @deprecated Present for backwards compatibility.\n     *             Use getLiveTimeline().getState(EventTimeline.FORWARDS) instead.\n     */\n    _defineProperty(this, \"currentState\", void 0);\n    _defineProperty(this, \"relations\", void 0);\n    /**\n     * A collection of events known by the client\n     * This is not a comprehensive list of the threads that exist in this room\n     */\n    _defineProperty(this, \"threads\", new Map());\n    /**\n     * A mapping of eventId to all visibility changes to apply\n     * to the event, by chronological order, as per\n     * https://github.com/matrix-org/matrix-doc/pull/3531\n     *\n     * # Invariants\n     *\n     * - within each list, all events are classed by\n     *   chronological order;\n     * - all events are events such that\n     *  `asVisibilityEvent()` returns a non-null `IVisibilityChange`;\n     * - within each list with key `eventId`, all events\n     *   are in relation to `eventId`.\n     *\n     * @experimental\n     */\n    _defineProperty(this, \"visibilityEvents\", new Map());\n    /**\n     * The latest receipts (synthetic and real) for each user in each thread\n     * (and unthreaded).\n     */\n    _defineProperty(this, \"roomReceipts\", new RoomReceipts(this));\n    /**\n     * Stores and tracks sticky events\n     */\n    _defineProperty(this, \"stickyEvents\", new RoomStickyEventsStore());\n    _defineProperty(this, \"threadTimelineSetsPromise\", null);\n    _defineProperty(this, \"threadsReady\", false);\n    _defineProperty(this, \"updateThreadRootEvents\", (thread, toStartOfTimeline, recreateEvent) => {\n      if (thread.length) {\n        var _this$threadsTimeline;\n        this.updateThreadRootEvent((_this$threadsTimeline = this.threadsTimelineSets) === null || _this$threadsTimeline === void 0 ? void 0 : _this$threadsTimeline[0], thread, toStartOfTimeline, recreateEvent);\n        if (thread.hasCurrentUserParticipated) {\n          var _this$threadsTimeline2;\n          this.updateThreadRootEvent((_this$threadsTimeline2 = this.threadsTimelineSets) === null || _this$threadsTimeline2 === void 0 ? void 0 : _this$threadsTimeline2[1], thread, toStartOfTimeline, recreateEvent);\n        }\n      }\n    });\n    _defineProperty(this, \"updateThreadRootEvent\", (timelineSet, thread, toStartOfTimeline, recreateEvent) => {\n      if (timelineSet && thread.rootEvent) {\n        if (recreateEvent) {\n          timelineSet.removeEvent(thread.id);\n        }\n        if (Thread.hasServerSideSupport) {\n          timelineSet.addLiveEvent(thread.rootEvent, {\n            duplicateStrategy: DuplicateStrategy.Replace,\n            fromCache: false,\n            roomState: this.currentState,\n            addToState: false\n          });\n        } else {\n          timelineSet.addEventToTimeline(thread.rootEvent, timelineSet.getLiveTimeline(), {\n            toStartOfTimeline,\n            addToState: false\n          });\n        }\n      }\n    });\n    _defineProperty(this, \"tryApplyRedaction\", event => {\n      // FIXME: apply redactions to notification list\n\n      // NB: We continue to add the redaction event to the timeline at the\n      // end of this function so clients can say \"so and so redacted an event\"\n      // if they wish to. Also this may be needed to trigger an update.\n\n      if (event.isRedaction()) {\n        var redactId = event.event.redacts;\n\n        // if we know about this event, redact its contents now.\n        var redactedEvent = redactId ? this.findEventById(redactId) : undefined;\n        if (redactId) {\n          try {\n            this.stickyEvents.handleRedaction(redactedEvent || redactId);\n          } catch (ex) {\n            // Non-critical failure, but we should warn.\n            logger.error(\"Failed to handle redaction for sticky event\", ex);\n          }\n        }\n        if (redactedEvent) {\n          this.applyEventAsRedaction(event, redactedEvent);\n        }\n      } else if (event.getType() === EventType.RoomMember) {\n        var membership = event.getContent()[\"membership\"];\n        if (membership !== KnownMembership.Ban && !(membership === KnownMembership.Leave && event.getStateKey() !== event.getSender())) {\n          // Not a ban or kick, therefore not a membership event we care about here.\n          return;\n        }\n        var redactEvents = event.getContent()[\"org.matrix.msc4293.redact_events\"];\n        if (redactEvents !== true) {\n          // Invalid or not set - nothing to redact.\n          return;\n        }\n        var state = this.getLiveTimeline().getState(Direction.Forward);\n        if (!state.maySendRedactionForEvent(event, event.getSender())) {\n          // If the sender can't redact the membership event, then they won't be able to\n          // redact any of the target's events either, so skip.\n          return;\n        }\n\n        // The redaction is possible, so let's find all the events and apply it.\n        var events = this.getTimelineSets().map(s => s.getTimelines()).reduce((p, c) => {\n          p.push(...c);\n          return p;\n        }, []).map(t => t.getEvents().filter(e => e.getSender() === event.getStateKey())).reduce((p, c) => {\n          p.push(...c);\n          return c;\n        }, []);\n        for (var toRedact of events) {\n          this.applyEventAsRedaction(event, toRedact);\n        }\n      }\n    });\n    this.setMaxListeners(100);\n    this.reEmitter = new TypedReEmitter(this);\n    opts.pendingEventOrdering = opts.pendingEventOrdering || PendingEventOrdering.Chronological;\n    this.name = roomId;\n    this.normalizedName = roomId;\n    this.relations = new RelationsContainer(this.client, this);\n\n    // Listen to our own receipt event as a more modular way of processing our own\n    // receipts. No need to remove the listener: it's on ourself anyway.\n    this.on(RoomEvent.Receipt, this.onReceipt);\n    this.reEmitter.reEmit(this.stickyEvents, [RoomStickyEventsEvent.Update]);\n\n    // all our per-room timeline sets. the first one is the unfiltered ones;\n    // the subsequent ones are the filtered ones in no particular order.\n    this.timelineSets = [new EventTimelineSet(this, opts)];\n    this.reEmitter.reEmit(this.getUnfilteredTimelineSet(), [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n    this.fixUpLegacyTimelineFields();\n    if (this.opts.pendingEventOrdering === PendingEventOrdering.Detached) {\n      this.pendingEventList = [];\n      this.client.store.getPendingEvents(this.roomId).then(events => {\n        var mapper = this.client.getEventMapper({\n          decrypt: false\n        });\n        events.forEach(/*#__PURE__*/function () {\n          var _ref = _asyncToGenerator(function* (serializedEvent) {\n            var event = mapper(serializedEvent);\n            yield client.decryptEventIfNeeded(event);\n            event.setStatus(EventStatus.NOT_SENT);\n            _this.addPendingEvent(event, event.getTxnId());\n          });\n          return function (_x) {\n            return _ref.apply(this, arguments);\n          };\n        }());\n      });\n    }\n\n    // awaited by getEncryptionTargetMembers while room members are loading\n    if (!this.opts.lazyLoadMembers) {\n      this.membersPromise = Promise.resolve(false);\n    } else {\n      this.membersPromise = undefined;\n    }\n  }\n  createThreadsTimelineSets() {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      var _this2$client;\n      if (_this2.threadTimelineSetsPromise) {\n        return _this2.threadTimelineSetsPromise;\n      }\n      if ((_this2$client = _this2.client) !== null && _this2$client !== void 0 && _this2$client.supportsThreads()) {\n        try {\n          _this2.threadTimelineSetsPromise = Promise.all([_this2.createThreadTimelineSet(), _this2.createThreadTimelineSet(ThreadFilterType.My)]);\n          var timelineSets = yield _this2.threadTimelineSetsPromise;\n          _this2.threadsTimelineSets[0] = timelineSets[0];\n          _this2.threadsTimelineSets[1] = timelineSets[1];\n          return timelineSets;\n        } catch (_unused) {\n          _this2.threadTimelineSetsPromise = null;\n          return null;\n        }\n      }\n      return null;\n    })();\n  }\n\n  /**\n   * Bulk decrypt critical events in a room\n   *\n   * Critical events represents the minimal set of events to decrypt\n   * for a typical UI to function properly\n   *\n   * - Last event of every room (to generate likely message preview)\n   * - All events up to the read receipt (to calculate an accurate notification count)\n   *\n   * @returns Signals when all events have been decrypted\n   */\n  decryptCriticalEvents() {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      if (!_this3.client.getCrypto()) return;\n      var readReceiptEventId = _this3.getEventReadUpTo(_this3.client.getUserId(), true);\n      var events = _this3.getLiveTimeline().getEvents();\n      var readReceiptTimelineIndex = events.findIndex(matrixEvent => {\n        return matrixEvent.event.event_id === readReceiptEventId;\n      });\n      var decryptionPromises = events.slice(readReceiptTimelineIndex).reverse().map(event => _this3.client.decryptEventIfNeeded(event));\n      yield Promise.allSettled(decryptionPromises);\n    })();\n  }\n\n  /**\n   * Bulk decrypt events in a room\n   *\n   * @returns Signals when all events have been decrypted\n   */\n  decryptAllEvents() {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      if (!_this4.client.getCrypto()) return;\n      var decryptionPromises = _this4.getUnfilteredTimelineSet().getLiveTimeline().getEvents().slice(0) // copy before reversing\n      .reverse().map(event => _this4.client.decryptEventIfNeeded(event));\n      yield Promise.allSettled(decryptionPromises);\n    })();\n  }\n\n  /**\n   * Gets the creator of the room\n   * @returns The creator of the room, or null if it could not be determined\n   */\n  getCreator() {\n    var _createEvent$getSende;\n    var createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n    return (_createEvent$getSende = createEvent === null || createEvent === void 0 ? void 0 : createEvent.getSender()) !== null && _createEvent$getSende !== void 0 ? _createEvent$getSende : null;\n  }\n\n  /**\n   * Gets the version of the room\n   * @returns The version of the room\n   */\n  getVersion() {\n    return this.currentState.getRoomVersion();\n  }\n\n  /**\n   * Determines the recommended room version for the room. This returns an\n   * object with 3 properties: `version` as the new version the\n   * room should be upgraded to (may be the same as the current version);\n   * `needsUpgrade` to indicate if the room actually can be\n   * upgraded (ie: does the current version not match?); and `urgent`\n   * to indicate if the new version patches a vulnerability in a previous\n   * version.\n   * @returns\n   * Resolves to the version the room should be upgraded to.\n   */\n  getRecommendedVersion() {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      var capabilities = {};\n      try {\n        capabilities = yield _this5.client.getCapabilities();\n      } catch (_unused2) {}\n      var versionCap = capabilities[\"m.room_versions\"];\n      if (!versionCap) {\n        versionCap = {\n          default: KNOWN_SAFE_ROOM_VERSION,\n          available: {}\n        };\n        for (var safeVer of SAFE_ROOM_VERSIONS) {\n          versionCap.available[safeVer] = RoomVersionStability.Stable;\n        }\n      }\n      var result = _this5.checkVersionAgainstCapability(versionCap);\n      if (result.urgent && result.needsUpgrade) {\n        // Something doesn't feel right: we shouldn't need to update\n        // because the version we're on should be in the protocol's\n        // namespace. This usually means that the server was updated\n        // before the client was, making us think the newest possible\n        // room version is not stable. As a solution, we'll refresh\n        // the capability we're using to determine this.\n        logger.warn(\"Refreshing room version capability because the server looks \" + \"to be supporting a newer room version we don't know about.\");\n        try {\n          capabilities = yield _this5.client.fetchCapabilities();\n        } catch (e) {\n          logger.warn(\"Failed to refresh room version capabilities\", e);\n        }\n        versionCap = capabilities[\"m.room_versions\"];\n        if (!versionCap) {\n          logger.warn(\"No room version capability - assuming upgrade required.\");\n          return result;\n        } else {\n          result = _this5.checkVersionAgainstCapability(versionCap);\n        }\n      }\n      return result;\n    })();\n  }\n  checkVersionAgainstCapability(versionCap) {\n    var currentVersion = this.getVersion();\n    logger.log(\"[\".concat(this.roomId, \"] Current version: \").concat(currentVersion));\n    logger.log(\"[\".concat(this.roomId, \"] Version capability: \"), versionCap);\n    var result = {\n      version: currentVersion,\n      needsUpgrade: false,\n      urgent: false\n    };\n\n    // If the room is on the default version then nothing needs to change\n    if (currentVersion === versionCap.default) return result;\n    var stableVersions = Object.keys(versionCap.available).filter(v => versionCap.available[v] === \"stable\");\n\n    // Check if the room is on an unstable version. We determine urgency based\n    // off the version being in the Matrix spec namespace or not (if the version\n    // is in the current namespace and unstable, the room is probably vulnerable).\n    if (!stableVersions.includes(currentVersion)) {\n      result.version = versionCap.default;\n      result.needsUpgrade = true;\n      result.urgent = !!this.getVersion().match(/^[0-9]+[0-9.]*$/g);\n      if (result.urgent) {\n        logger.warn(\"URGENT upgrade required on \".concat(this.roomId));\n      } else {\n        logger.warn(\"Non-urgent upgrade required on \".concat(this.roomId));\n      }\n      return result;\n    }\n\n    // The room is on a stable, but non-default, version by this point.\n    // No upgrade needed.\n    return result;\n  }\n\n  /**\n   * Determines whether the given user is permitted to perform a room upgrade\n   * @param userId - The ID of the user to test against\n   * @returns True if the given user is permitted to upgrade the room\n   */\n  userMayUpgradeRoom(userId) {\n    return this.currentState.maySendStateEvent(EventType.RoomTombstone, userId);\n  }\n\n  /**\n   * Get the list of pending sent events for this room\n   *\n   * @returns A list of the sent events\n   * waiting for remote echo.\n   *\n   * @throws If `opts.pendingEventOrdering` was not 'detached'\n   */\n  getPendingEvents() {\n    if (!this.pendingEventList) {\n      throw new Error(\"Cannot call getPendingEvents with pendingEventOrdering == \" + this.opts.pendingEventOrdering);\n    }\n    return this.pendingEventList;\n  }\n\n  /**\n   * Removes a pending event for this room\n   *\n   * @returns True if an element was removed.\n   */\n  removePendingEvent(eventId) {\n    if (!this.pendingEventList) {\n      throw new Error(\"Cannot call removePendingEvent with pendingEventOrdering == \" + this.opts.pendingEventOrdering);\n    }\n    var removed = removeElement(this.pendingEventList, function (ev) {\n      return ev.getId() == eventId;\n    }, false);\n    this.savePendingEvents();\n    return removed;\n  }\n\n  /**\n   * Check whether the pending event list contains a given event by ID.\n   * If pending event ordering is not \"detached\" then this returns false.\n   *\n   * @param eventId - The event ID to check for.\n   */\n  hasPendingEvent(eventId) {\n    var _this$pendingEventLis, _this$pendingEventLis2;\n    return (_this$pendingEventLis = (_this$pendingEventLis2 = this.pendingEventList) === null || _this$pendingEventLis2 === void 0 ? void 0 : _this$pendingEventLis2.some(event => event.getId() === eventId)) !== null && _this$pendingEventLis !== void 0 ? _this$pendingEventLis : false;\n  }\n\n  /**\n   * Get a specific event from the pending event list, if configured, null otherwise.\n   *\n   * @param eventId - The event ID to check for.\n   */\n  getPendingEvent(eventId) {\n    var _this$pendingEventLis3, _this$pendingEventLis4;\n    return (_this$pendingEventLis3 = (_this$pendingEventLis4 = this.pendingEventList) === null || _this$pendingEventLis4 === void 0 ? void 0 : _this$pendingEventLis4.find(event => event.getId() === eventId)) !== null && _this$pendingEventLis3 !== void 0 ? _this$pendingEventLis3 : null;\n  }\n\n  /**\n   * Get the live unfiltered timeline for this room.\n   *\n   * @returns live timeline\n   */\n  getLiveTimeline() {\n    return this.getUnfilteredTimelineSet().getLiveTimeline();\n  }\n\n  /**\n   * The live event timeline for this room, with the oldest event at index 0.\n   *\n   * @deprecated Present for backwards compatibility.\n   *             Use getLiveTimeline().getEvents() instead\n   */\n  get timeline() {\n    return this.getLiveTimeline().getEvents();\n  }\n\n  /**\n   * Get the timestamp of the last message in the room\n   *\n   * @returns the timestamp of the last message in the room\n   */\n  getLastActiveTimestamp() {\n    var timeline = this.getLiveTimeline();\n    var events = timeline.getEvents();\n    if (events.length) {\n      var lastEvent = events[events.length - 1];\n      return lastEvent.getTs();\n    } else {\n      return Number.MIN_SAFE_INTEGER;\n    }\n  }\n\n  /**\n   * Returns the last live event of this room.\n   * \"last\" means latest timestamp.\n   * Instead of using timestamps, it would be better to do the comparison based on the order of the homeserver DAG.\n   * Unfortunately, this information is currently not available in the client.\n   * See {@link https://github.com/matrix-org/matrix-js-sdk/issues/3325}.\n   * \"live of this room\" means from all live timelines: the room and the threads.\n   *\n   * @returns MatrixEvent if there is a last event; else undefined.\n   */\n  getLastLiveEvent() {\n    var _lastRoomEvent$getTs, _lastThreadEvent$getT;\n    var roomEvents = this.getLiveTimeline().getEvents();\n    var lastRoomEvent = roomEvents[roomEvents.length - 1];\n    var lastThread = this.getLastThread();\n    if (!lastThread) return lastRoomEvent;\n    var lastThreadEvent = lastThread.events[lastThread.events.length - 1];\n    return ((_lastRoomEvent$getTs = lastRoomEvent === null || lastRoomEvent === void 0 ? void 0 : lastRoomEvent.getTs()) !== null && _lastRoomEvent$getTs !== void 0 ? _lastRoomEvent$getTs : 0) > ((_lastThreadEvent$getT = lastThreadEvent === null || lastThreadEvent === void 0 ? void 0 : lastThreadEvent.getTs()) !== null && _lastThreadEvent$getT !== void 0 ? _lastThreadEvent$getT : 0) ? lastRoomEvent : lastThreadEvent;\n  }\n\n  /**\n   * Returns the last thread of this room.\n   * \"last\" means latest timestamp of the last thread event.\n   * Instead of using timestamps, it would be better to do the comparison based on the order of the homeserver DAG.\n   * Unfortunately, this information is currently not available in the client.\n   * See {@link https://github.com/matrix-org/matrix-js-sdk/issues/3325}.\n   *\n   * @returns the thread with the most recent event in its live time line. undefined if there is no thread.\n   */\n  getLastThread() {\n    return this.getThreads().reduce((lastThread, thread) => {\n      var _threadEvent$getTs, _lastThreadEvent$getT2;\n      if (!lastThread) return thread;\n      var threadEvent = thread.events[thread.events.length - 1];\n      var lastThreadEvent = lastThread.events[lastThread.events.length - 1];\n      if (((_threadEvent$getTs = threadEvent === null || threadEvent === void 0 ? void 0 : threadEvent.getTs()) !== null && _threadEvent$getTs !== void 0 ? _threadEvent$getTs : 0) >= ((_lastThreadEvent$getT2 = lastThreadEvent === null || lastThreadEvent === void 0 ? void 0 : lastThreadEvent.getTs()) !== null && _lastThreadEvent$getT2 !== void 0 ? _lastThreadEvent$getT2 : 0)) {\n        // Last message of current thread is newer → new last thread.\n        // Equal also means newer, because it was added to the thread map later.\n        return thread;\n      }\n      return lastThread;\n    }, undefined);\n  }\n\n  /**\n   * @returns the membership type (join | leave | invite | knock) for the logged in user\n   */\n  getMyMembership() {\n    var _this$selfMembership;\n    return (_this$selfMembership = this.selfMembership) !== null && _this$selfMembership !== void 0 ? _this$selfMembership : KnownMembership.Leave;\n  }\n\n  /**\n   * If this room is a DM we're invited to,\n   * try to find out who invited us\n   * @returns user id of the inviter\n   */\n  getDMInviter() {\n    var me = this.getMember(this.myUserId);\n    if (me) {\n      return me.getDMInviter();\n    }\n    if (this.selfMembership === KnownMembership.Invite) {\n      // fall back to summary information\n      var memberCount = this.getInvitedAndJoinedMemberCount();\n      if (memberCount === 2) {\n        var _this$heroes;\n        return (_this$heroes = this.heroes) === null || _this$heroes === void 0 || (_this$heroes = _this$heroes[0]) === null || _this$heroes === void 0 ? void 0 : _this$heroes.userId;\n      }\n    }\n  }\n\n  /**\n   * Assuming this room is a DM room, tries to guess with which user.\n   * @returns user id of the other member (could be syncing user)\n   */\n  guessDMUserId() {\n    var me = this.getMember(this.myUserId);\n    if (me) {\n      var inviterId = me.getDMInviter();\n      if (inviterId) {\n        return inviterId;\n      }\n    }\n    // Remember, we're assuming this room is a DM, so returning the first member we find should be fine\n    if (Array.isArray(this.heroes) && this.heroes.length) {\n      return this.heroes[0].userId;\n    }\n    var members = this.currentState.getMembers();\n    var anyMember = members.find(m => m.userId !== this.myUserId);\n    if (anyMember) {\n      return anyMember.userId;\n    }\n    // it really seems like I'm the only user in the room\n    // so I probably created a room with just me in it\n    // and marked it as a DM. Ok then\n    return this.myUserId;\n  }\n\n  /**\n   * Gets the \"functional members\" in this room.\n   *\n   * Returns the list of userIDs from the `io.element.functional_members` event. Does not consider the\n   * current membership states of those users.\n   *\n   * @see https://github.com/element-hq/element-meta/blob/develop/spec/functional_members.md.\n   */\n  getFunctionalMembers() {\n    var mFunctionalMembers = this.currentState.getStateEvents(UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, \"\");\n    if (Array.isArray(mFunctionalMembers === null || mFunctionalMembers === void 0 ? void 0 : mFunctionalMembers.getContent().service_members)) {\n      return mFunctionalMembers.getContent().service_members;\n    }\n    return [];\n  }\n  getAvatarFallbackMember() {\n    var _this$heroes2;\n    var functionalMembers = this.getFunctionalMembers();\n\n    // Only generate a fallback avatar if the conversation is with a single specific other user (a \"DM\").\n    var nonFunctionalMemberCount = 0;\n    this.getMembers().forEach(m => {\n      if (m.membership !== \"join\" && m.membership !== \"invite\") return;\n      if (functionalMembers.includes(m.userId)) return;\n      nonFunctionalMemberCount++;\n    });\n    if (nonFunctionalMemberCount > 2) return;\n\n    // Prefer the list of heroes, if present. It should only include the single other user in the DM.\n    var nonFunctionalHeroes = (_this$heroes2 = this.heroes) === null || _this$heroes2 === void 0 ? void 0 : _this$heroes2.filter(h => !functionalMembers.includes(h.userId));\n    var hasHeroes = Array.isArray(nonFunctionalHeroes) && nonFunctionalHeroes.length;\n    if (hasHeroes) {\n      // use first hero that has a display name or avatar url, or whose user ID\n      // can be looked up as a member of the room\n      for (var hero of nonFunctionalHeroes) {\n        // If the hero was from a legacy sync (`/v3/sync`), we will need to look the user ID up in the room\n        // the display name and avatar URL will not be set.\n        if (!hero.fromMSC4186) {\n          // attempt to look up renderable fields from the m.room.member event if it exists\n          var member = this.getMember(hero.userId);\n          if (member) {\n            return member;\n          }\n        } else {\n          // use the Hero supplied values for the room member.\n          // TODO: It's unfortunate that this function, which clearly only cares about the\n          //       avatar url, returns the entire RoomMember event. We need to fake an event\n          //       to meet this API shape.\n          var heroMember = new RoomMember(this.roomId, hero.userId);\n          // set the display name and avatar url\n          heroMember.setMembershipEvent(new MatrixEvent({\n            // ensure it's unique even if we hit the same millisecond\n            event_id: \"$\" + this.roomId + hero.userId + new Date().getTime(),\n            type: EventType.RoomMember,\n            state_key: hero.userId,\n            content: {\n              displayname: hero.displayName,\n              avatar_url: hero.avatarUrl\n            }\n          }));\n          return heroMember;\n        }\n      }\n      var availableMember = nonFunctionalHeroes.map(hero => {\n        return this.getMember(hero.userId);\n      }).find(member => !!member);\n      if (availableMember) {\n        return availableMember;\n      }\n    }\n\n    // Consider *all*, including previous, members, to generate the avatar for DMs where the other user left.\n    // Needed to generate a matching avatar for rooms named \"Empty Room (was Alice)\".\n    var members = this.getMembers();\n    var nonFunctionalMembers = members === null || members === void 0 ? void 0 : members.filter(m => !functionalMembers.includes(m.userId));\n    if (nonFunctionalMembers.length <= 2) {\n      var _availableMember = nonFunctionalMembers.find(m => {\n        return m.userId !== this.myUserId;\n      });\n      if (_availableMember) {\n        return _availableMember;\n      }\n    }\n\n    // If all else failed, but the homeserver gave us heroes that previously could not be found in the room members,\n    // trust and try falling back to a hero, creating a one-off member for it\n    if (hasHeroes) {\n      var availableUser = nonFunctionalHeroes.map(hero => {\n        return this.client.getUser(hero.userId);\n      }).find(user => !!user);\n      if (availableUser) {\n        var _member = new RoomMember(this.roomId, availableUser.userId);\n        _member.user = availableUser;\n        return _member;\n      }\n    }\n  }\n\n  /**\n   * Sets the membership this room was received as during sync\n   * @param membership - join | leave | invite\n   */\n  updateMyMembership(membership) {\n    var prevMembership = this.selfMembership;\n    this.selfMembership = membership;\n    if (prevMembership !== membership) {\n      if (membership === KnownMembership.Leave) {\n        this.cleanupAfterLeaving();\n      }\n      this.emit(RoomEvent.MyMembership, this, membership, prevMembership);\n    }\n  }\n  loadMembersFromServer() {\n    var _this6 = this;\n    return _asyncToGenerator(function* () {\n      var lastSyncToken = _this6.client.store.getSyncToken();\n      var response = yield _this6.client.members(_this6.roomId, undefined, KnownMembership.Leave, lastSyncToken !== null && lastSyncToken !== void 0 ? lastSyncToken : undefined);\n      return response.chunk;\n    })();\n  }\n  loadMembers() {\n    var _this7 = this;\n    return _asyncToGenerator(function* () {\n      // were the members loaded from the server?\n      var fromServer = false;\n      var rawMembersEvents = yield _this7.client.store.getOutOfBandMembers(_this7.roomId);\n      // If the room is encrypted, we always fetch members from the server at\n      // least once, in case the latest state wasn't persisted properly. Note\n      // that this function is only called once (unless loading the members\n      // fails), since loadMembersIfNeeded always returns this.membersPromise\n      // if set, which will be the result of the first (successful) call.\n      if (rawMembersEvents === null || _this7.hasEncryptionStateEvent()) {\n        fromServer = true;\n        rawMembersEvents = yield _this7.loadMembersFromServer();\n        logger.log(\"LL: got \".concat(rawMembersEvents.length, \" \") + \"members from server for room \".concat(_this7.roomId));\n      }\n      var memberEvents = rawMembersEvents.filter(noUnsafeEventProps).map(_this7.client.getEventMapper());\n      return {\n        memberEvents,\n        fromServer\n      };\n    })();\n  }\n\n  /**\n   * Check if loading of out-of-band-members has completed\n   *\n   * @returns true if the full membership list of this room has been loaded (including if lazy-loading is disabled).\n   *    False if the load is not started or is in progress.\n   */\n  membersLoaded() {\n    if (!this.opts.lazyLoadMembers) {\n      return true;\n    }\n    return this.currentState.outOfBandMembersReady();\n  }\n\n  /**\n   * Preloads the member list in case lazy loading\n   * of memberships is in use. Can be called multiple times,\n   * it will only preload once.\n   * @returns when preloading is done and\n   * accessing the members on the room will take\n   * all members in the room into account\n   */\n  loadMembersIfNeeded() {\n    if (this.membersPromise) {\n      return this.membersPromise;\n    }\n\n    // mark the state so that incoming messages while\n    // the request is in flight get marked as superseding\n    // the OOB members\n    this.currentState.markOutOfBandMembersStarted();\n    var inMemoryUpdate = this.loadMembers().then(result => {\n      this.currentState.setOutOfBandMembers(result.memberEvents);\n      // recalculate the room name: it may have been based on members, so may have changed\n      this.recalculate();\n      return result.fromServer;\n    }).catch(err => {\n      // allow retries on fail\n      this.membersPromise = undefined;\n      this.currentState.markOutOfBandMembersFailed();\n      throw err;\n    });\n    // update members in storage, but don't wait for it\n    inMemoryUpdate.then(fromServer => {\n      if (fromServer) {\n        var oobMembers = this.currentState.getMembers().filter(m => m.isOutOfBand()).map(m => {\n          var _m$events$member;\n          return (_m$events$member = m.events.member) === null || _m$events$member === void 0 ? void 0 : _m$events$member.event;\n        });\n        logger.log(\"LL: telling store to write \".concat(oobMembers.length) + \" members for room \".concat(this.roomId));\n        var store = this.client.store;\n        return store.setOutOfBandMembers(this.roomId, oobMembers)\n        // swallow any IDB error as we don't want to fail\n        // because of this\n        .catch(err => {\n          logger.log(\"LL: storing OOB room members failed, oh well\", err);\n        });\n      }\n    }).catch(err => {\n      // as this is not awaited anywhere,\n      // at least show the error in the console\n      logger.error(err);\n    });\n    this.membersPromise = inMemoryUpdate;\n    return this.membersPromise;\n  }\n\n  /**\n   * Removes the lazily loaded members from storage if needed\n   */\n  clearLoadedMembersIfNeeded() {\n    var _this8 = this;\n    return _asyncToGenerator(function* () {\n      if (_this8.opts.lazyLoadMembers && _this8.membersPromise) {\n        yield _this8.loadMembersIfNeeded();\n        yield _this8.client.store.clearOutOfBandMembers(_this8.roomId);\n        _this8.currentState.clearOutOfBandMembers();\n        _this8.membersPromise = undefined;\n      }\n    })();\n  }\n\n  /**\n   * called when sync receives this room in the leave section\n   * to do cleanup after leaving a room. Possibly called multiple times.\n   */\n  cleanupAfterLeaving() {\n    this.clearLoadedMembersIfNeeded().catch(err => {\n      logger.error(\"error after clearing loaded members from \" + \"room \".concat(this.roomId, \" after leaving\"));\n      logger.log(err);\n    });\n  }\n\n  /**\n   * Empty out the current live timeline and re-request it. This is used when\n   * historical messages are imported into the room via MSC2716 `/batch_send`\n   * because the client may already have that section of the timeline loaded.\n   * We need to force the client to throw away their current timeline so that\n   * when they back paginate over the area again with the historical messages\n   * in between, it grabs the newly imported messages. We can listen for\n   * `UNSTABLE_MSC2716_MARKER`, in order to tell when historical messages are ready\n   * to be discovered in the room and the timeline needs a refresh. The SDK\n   * emits a `RoomEvent.HistoryImportedWithinTimeline` event when we detect a\n   * valid marker and can check the needs refresh status via\n   * `room.getTimelineNeedsRefresh()`.\n   */\n  refreshLiveTimeline() {\n    var _this9 = this;\n    return _asyncToGenerator(function* () {\n      var liveTimelineBefore = _this9.getLiveTimeline();\n      var forwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.FORWARDS);\n      var backwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.BACKWARDS);\n      var eventsBefore = liveTimelineBefore.getEvents();\n      var mostRecentEventInTimeline = eventsBefore[eventsBefore.length - 1];\n      logger.log(\"[refreshLiveTimeline for \".concat(_this9.roomId, \"] at \") + \"mostRecentEventInTimeline=\".concat(mostRecentEventInTimeline && mostRecentEventInTimeline.getId(), \" \") + \"liveTimelineBefore=\".concat(liveTimelineBefore.toString(), \" \") + \"forwardPaginationToken=\".concat(forwardPaginationToken, \" \") + \"backwardPaginationToken=\".concat(backwardPaginationToken));\n\n      // Get the main TimelineSet\n      var timelineSet = _this9.getUnfilteredTimelineSet();\n      var newTimeline = null;\n      // If there isn't any event in the timeline, let's go fetch the latest\n      // event and construct a timeline from it.\n      //\n      // This should only really happen if the user ran into an error\n      // with refreshing the timeline before which left them in a blank\n      // timeline from `resetLiveTimeline`.\n      if (!mostRecentEventInTimeline) {\n        newTimeline = yield _this9.client.getLatestTimeline(timelineSet);\n      } else {\n        // Empty out all of `this.timelineSets`. But we also need to keep the\n        // same `timelineSet` references around so the React code updates\n        // properly and doesn't ignore the room events we emit because it checks\n        // that the `timelineSet` references are the same. We need the\n        // `timelineSet` empty so that the `client.getEventTimeline(...)` call\n        // later, will call `/context` and create a new timeline instead of\n        // returning the same one.\n        _this9.resetLiveTimeline(null, null);\n\n        // Make the UI timeline show the new blank live timeline we just\n        // reset so that if the network fails below it's showing the\n        // accurate state of what we're working with instead of the\n        // disconnected one in the TimelineWindow which is just hanging\n        // around by reference.\n        _this9.emit(RoomEvent.TimelineRefresh, _this9, timelineSet);\n\n        // Use `client.getEventTimeline(...)` to construct a new timeline from a\n        // `/context` response state and events for the most recent event before\n        // we reset everything. The `timelineSet` we pass in needs to be empty\n        // in order for this function to call `/context` and generate a new\n        // timeline.\n        newTimeline = yield _this9.client.getEventTimeline(timelineSet, mostRecentEventInTimeline.getId());\n      }\n\n      // If a racing `/sync` beat us to creating a new timeline, use that\n      // instead because it's the latest in the room and any new messages in\n      // the scrollback will include the history.\n      var liveTimeline = timelineSet.getLiveTimeline();\n      if (!liveTimeline || liveTimeline.getPaginationToken(Direction.Forward) === null && liveTimeline.getPaginationToken(Direction.Backward) === null && liveTimeline.getEvents().length === 0) {\n        logger.log(\"[refreshLiveTimeline for \".concat(_this9.roomId, \"] using our new live timeline\"));\n        // Set the pagination token back to the live sync token (`null`) instead\n        // of using the `/context` historical token (ex. `t12-13_0_0_0_0_0_0_0_0`)\n        // so that it matches the next response from `/sync` and we can properly\n        // continue the timeline.\n        newTimeline.setPaginationToken(forwardPaginationToken, EventTimeline.FORWARDS);\n\n        // Set our new fresh timeline as the live timeline to continue syncing\n        // forwards and back paginating from.\n        timelineSet.setLiveTimeline(newTimeline);\n        // Fixup `this.oldstate` so that `scrollback` has the pagination tokens\n        // available\n        _this9.fixUpLegacyTimelineFields();\n      } else {\n        logger.log(\"[refreshLiveTimeline for \".concat(_this9.roomId, \"] `/sync` or some other request beat us to creating a new \") + \"live timeline after we reset it. We'll use that instead since any events in the scrollback from \" + \"this timeline will include the history.\");\n      }\n\n      // The timeline has now been refreshed ✅\n      _this9.setTimelineNeedsRefresh(false);\n\n      // Emit an event which clients can react to and re-load the timeline\n      // from the SDK\n      _this9.emit(RoomEvent.TimelineRefresh, _this9, timelineSet);\n    })();\n  }\n\n  /**\n   * Reset the live timeline of all timelineSets, and start new ones.\n   *\n   * <p>This is used when /sync returns a 'limited' timeline.\n   *\n   * @param backPaginationToken -   token for back-paginating the new timeline\n   * @param forwardPaginationToken - token for forward-paginating the old live timeline,\n   * if absent or null, all timelines are reset, removing old ones (including the previous live\n   * timeline which would otherwise be unable to paginate forwards without this token).\n   * Removing just the old live timeline whilst preserving previous ones is not supported.\n   */\n  resetLiveTimeline(backPaginationToken, forwardPaginationToken) {\n    for (var timelineSet of this.timelineSets) {\n      timelineSet.resetLiveTimeline(backPaginationToken !== null && backPaginationToken !== void 0 ? backPaginationToken : undefined, forwardPaginationToken !== null && forwardPaginationToken !== void 0 ? forwardPaginationToken : undefined);\n    }\n    for (var thread of this.threads.values()) {\n      thread.resetLiveTimeline(backPaginationToken, forwardPaginationToken);\n    }\n    this.fixUpLegacyTimelineFields();\n  }\n\n  /**\n   * Fix up this.timeline, this.oldState and this.currentState\n   *\n   * @internal\n   */\n  fixUpLegacyTimelineFields() {\n    var previousOldState = this.oldState;\n    var previousCurrentState = this.currentState;\n\n    // maintain this.oldState and this.currentState as references to the\n    // state at the start and end of that timeline. These are more\n    // for backwards-compatibility than anything else.\n    this.oldState = this.getLiveTimeline().getState(EventTimeline.BACKWARDS);\n    this.currentState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);\n\n    // Let people know to register new listeners for the new state\n    // references. The reference won't necessarily change every time so only\n    // emit when we see a change.\n    if (previousOldState !== this.oldState) {\n      this.emit(RoomEvent.OldStateUpdated, this, previousOldState, this.oldState);\n    }\n    if (previousCurrentState !== this.currentState) {\n      this.emit(RoomEvent.CurrentStateUpdated, this, previousCurrentState, this.currentState);\n\n      // Re-emit various events on the current room state\n      // TODO: If currentState really only exists for backwards\n      // compatibility, shouldn't we be doing this some other way?\n      this.reEmitter.stopReEmitting(previousCurrentState, [RoomStateEvent.Events, RoomStateEvent.Members, RoomStateEvent.NewMember, RoomStateEvent.Update, RoomStateEvent.Marker, BeaconEvent.New, BeaconEvent.Update, BeaconEvent.Destroy, BeaconEvent.LivenessChange]);\n      this.reEmitter.reEmit(this.currentState, [RoomStateEvent.Events, RoomStateEvent.Members, RoomStateEvent.NewMember, RoomStateEvent.Update, RoomStateEvent.Marker, BeaconEvent.New, BeaconEvent.Update, BeaconEvent.Destroy, BeaconEvent.LivenessChange]);\n    }\n  }\n  onReceipt(event) {\n    if (this.hasEncryptionStateEvent()) {\n      this.clearNotificationsOnReceipt(event);\n    }\n  }\n  clearNotificationsOnReceipt(event) {\n    // Like above, we have to listen for read receipts from ourselves in order to\n    // correctly handle notification counts on encrypted rooms.\n    // This fixes https://github.com/vector-im/element-web/issues/9421\n\n    // Figure out if we've read something or if it's just informational\n    // We need to work out what threads we've just recieved receipts for, so we\n    // know which ones to update. If we've received an unthreaded receipt, we'll\n    // need to update all threads.\n    var threadIds = [];\n    var hasUnthreadedReceipt = false;\n    var content = event.getContent();\n    for (var receiptGroup of Object.values(content)) {\n      for (var [receiptType, userReceipt] of Object.entries(receiptGroup)) {\n        if (!utils.isSupportedReceiptType(receiptType)) continue;\n        if (!userReceipt) continue;\n        for (var [userId, singleReceipt] of Object.entries(userReceipt)) {\n          if (!singleReceipt || typeof singleReceipt !== \"object\") continue;\n          var typedSingleReceipt = singleReceipt;\n          if (userId !== this.client.getUserId()) continue;\n          if (typedSingleReceipt.thread_id === undefined) {\n            hasUnthreadedReceipt = true;\n          } else if (typeof typedSingleReceipt.thread_id === \"string\") {\n            threadIds.push(typedSingleReceipt.thread_id);\n          }\n        }\n      }\n    }\n    if (hasUnthreadedReceipt) {\n      // If we have an unthreaded receipt, we need to update any threads that have a notification\n      // in them (because we know the receipt can't go backwards so we don't need to check any with\n      // no notifications: the number can only decrease from a receipt).\n      threadIds = this.getThreads().filter(thread => this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total) > 0 || this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Highlight) > 0).map(thread => thread.id);\n      threadIds.push(\"main\");\n    }\n    for (var threadId of threadIds) {\n      var _this$getThread;\n      // Work backwards to determine how many events are unread. We also set\n      // a limit for how back we'll look to avoid spinning CPU for too long.\n      // If we hit the limit, we assume the count is unchanged.\n      var maxHistory = 20;\n      var timeline = threadId === \"main\" ? this.getLiveTimeline() : (_this$getThread = this.getThread(threadId)) === null || _this$getThread === void 0 ? void 0 : _this$getThread.liveTimeline;\n      if (!timeline) {\n        logger.warn(\"Couldn't find timeline for thread ID \".concat(threadId, \" in room \").concat(this.roomId));\n        continue;\n      }\n      var events = timeline.getEvents();\n      var highlightCount = 0;\n      for (var i = events.length - 1; i >= 0; i--) {\n        var _pushActions$tweaks;\n        if (i === events.length - maxHistory) return; // limit reached\n\n        var _event = events[i];\n        if (this.hasUserReadEvent(this.client.getUserId(), _event.getId())) {\n          // If the user has read the event, then the counting is done.\n          break;\n        }\n        var pushActions = this.client.getPushActionsForEvent(_event);\n        highlightCount += pushActions !== null && pushActions !== void 0 && (_pushActions$tweaks = pushActions.tweaks) !== null && _pushActions$tweaks !== void 0 && _pushActions$tweaks.highlight ? 1 : 0;\n      }\n\n      // Note: we don't need to handle 'total' notifications because the counts\n      // will come from the server.\n      if (threadId === \"main\") {\n        this.setUnreadNotificationCount(NotificationCountType.Highlight, highlightCount);\n      } else {\n        this.setThreadUnreadNotificationCount(threadId, NotificationCountType.Highlight, highlightCount);\n      }\n    }\n  }\n\n  /**\n   * Return the timeline sets for this room.\n   * @returns array of timeline sets for this room\n   */\n  getTimelineSets() {\n    return this.timelineSets;\n  }\n\n  /**\n   * Helper to return the main unfiltered timeline set for this room\n   * @returns room's unfiltered timeline set\n   */\n  getUnfilteredTimelineSet() {\n    return this.timelineSets[0];\n  }\n\n  /**\n   * Get the timeline which contains the given event from the unfiltered set, if any\n   *\n   * @param eventId -  event ID to look for\n   * @returns timeline containing\n   * the given event, or null if unknown\n   */\n  getTimelineForEvent(eventId) {\n    var event = this.findEventById(eventId);\n    var thread = this.findThreadForEvent(event);\n    if (thread) {\n      return thread.timelineSet.getTimelineForEvent(eventId);\n    } else {\n      return this.getUnfilteredTimelineSet().getTimelineForEvent(eventId);\n    }\n  }\n\n  /**\n   * Add a new timeline to this room's unfiltered timeline set\n   *\n   * @returns newly-created timeline\n   */\n  addTimeline() {\n    return this.getUnfilteredTimelineSet().addTimeline();\n  }\n\n  /**\n   * Whether the timeline needs to be refreshed in order to pull in new\n   * historical messages that were imported.\n   * @param value - The value to set\n   */\n  setTimelineNeedsRefresh(value) {\n    this.timelineNeedsRefresh = value;\n  }\n\n  /**\n   * Whether the timeline needs to be refreshed in order to pull in new\n   * historical messages that were imported.\n   * @returns .\n   */\n  getTimelineNeedsRefresh() {\n    return this.timelineNeedsRefresh;\n  }\n\n  /**\n   * Get an event which is stored in our unfiltered timeline set, or in a thread\n   *\n   * @param eventId - event ID to look for\n   * @returns the given event, or undefined if unknown\n   */\n  findEventById(eventId) {\n    var event = this.getUnfilteredTimelineSet().findEventById(eventId);\n    if (!event) {\n      var threads = this.getThreads();\n      for (var i = 0; i < threads.length; i++) {\n        var thread = threads[i];\n        event = thread.findEventById(eventId);\n        if (event) {\n          return event;\n        }\n      }\n    }\n    return event;\n  }\n\n  /**\n   * Get one of the notification counts for this room\n   * @param type - The type of notification count to get. default: 'total'\n   * @returns The notification count, or undefined if there is no count\n   *                  for this type.\n   */\n  getUnreadNotificationCount() {\n    var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : NotificationCountType.Total;\n    var count = this.getRoomUnreadNotificationCount(type);\n    for (var threadNotification of this.threadNotifications.values()) {\n      var _threadNotification$t;\n      count += (_threadNotification$t = threadNotification[type]) !== null && _threadNotification$t !== void 0 ? _threadNotification$t : 0;\n    }\n    return count;\n  }\n\n  /**\n   * Get the notification for the event context (room or thread timeline)\n   */\n  getUnreadCountForEventContext() {\n    var _ref2;\n    var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : NotificationCountType.Total;\n    var event = arguments.length > 1 ? arguments[1] : undefined;\n    var isThreadEvent = !!event.threadRootId && !event.isThreadRoot;\n    return (_ref2 = isThreadEvent ? this.getThreadUnreadNotificationCount(event.threadRootId, type) : this.getRoomUnreadNotificationCount(type)) !== null && _ref2 !== void 0 ? _ref2 : 0;\n  }\n\n  /**\n   * Get one of the notification counts for this room\n   * @param type - The type of notification count to get. default: 'total'\n   * @returns The notification count, or undefined if there is no count\n   *                  for this type.\n   */\n  getRoomUnreadNotificationCount() {\n    var _this$notificationCou;\n    var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : NotificationCountType.Total;\n    return (_this$notificationCou = this.notificationCounts[type]) !== null && _this$notificationCou !== void 0 ? _this$notificationCou : 0;\n  }\n\n  /**\n   * Get one of the notification counts for a thread\n   * @param threadId - the root event ID\n   * @param type - The type of notification count to get. default: 'total'\n   * @returns The notification count, or undefined if there is no count\n   *          for this type.\n   */\n  getThreadUnreadNotificationCount(threadId) {\n    var _this$threadNotificat, _this$threadNotificat2;\n    var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : NotificationCountType.Total;\n    return (_this$threadNotificat = (_this$threadNotificat2 = this.threadNotifications.get(threadId)) === null || _this$threadNotificat2 === void 0 ? void 0 : _this$threadNotificat2[type]) !== null && _this$threadNotificat !== void 0 ? _this$threadNotificat : 0;\n  }\n\n  /**\n   * Checks if the current room has unread thread notifications\n   * @returns\n   */\n  hasThreadUnreadNotification() {\n    for (var notification of this.threadNotifications.values()) {\n      var _notification$highlig, _notification$total;\n      if (((_notification$highlig = notification.highlight) !== null && _notification$highlig !== void 0 ? _notification$highlig : 0) > 0 || ((_notification$total = notification.total) !== null && _notification$total !== void 0 ? _notification$total : 0) > 0) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /**\n   * Swet one of the notification count for a thread\n   * @param threadId - the root event ID\n   * @param type - The type of notification count to get. default: 'total'\n   * @returns\n   */\n  setThreadUnreadNotificationCount(threadId, type, count) {\n    var _this$threadNotificat3, _this$threadNotificat4;\n    var notification = _objectSpread({\n      highlight: (_this$threadNotificat3 = this.threadNotifications.get(threadId)) === null || _this$threadNotificat3 === void 0 ? void 0 : _this$threadNotificat3.highlight,\n      total: (_this$threadNotificat4 = this.threadNotifications.get(threadId)) === null || _this$threadNotificat4 === void 0 ? void 0 : _this$threadNotificat4.total\n    }, {\n      [type]: count\n    });\n    this.threadNotifications.set(threadId, notification);\n    this.emit(RoomEvent.UnreadNotifications, notification, threadId);\n  }\n\n  /**\n   * @returns the notification count type for all the threads in the room\n   */\n  get threadsAggregateNotificationType() {\n    var type = null;\n    for (var threadNotification of this.threadNotifications.values()) {\n      var _threadNotification$h, _threadNotification$t2;\n      if (((_threadNotification$h = threadNotification.highlight) !== null && _threadNotification$h !== void 0 ? _threadNotification$h : 0) > 0) {\n        return NotificationCountType.Highlight;\n      } else if (((_threadNotification$t2 = threadNotification.total) !== null && _threadNotification$t2 !== void 0 ? _threadNotification$t2 : 0) > 0 && !type) {\n        type = NotificationCountType.Total;\n      }\n    }\n    return type;\n  }\n\n  /**\n   * Resets the total thread notifications for all threads in this room to zero,\n   * excluding any threads whose IDs are given in `exceptThreadIds`.\n   *\n   * If the room is not encrypted, also resets the highlight notification count to zero\n   * for the same set of threads.\n   *\n   * This is intended for use from the sync code since we calculate highlight notification\n   * counts locally from decrypted messages. We want to partially trust the total from the\n   * server such that we clear notifications when read receipts arrive. The weird name is\n   * intended to reflect this. You probably do not want to use this.\n   *\n   * @param exceptThreadIds - The thread IDs to exclude from the reset.\n   */\n  resetThreadUnreadNotificationCountFromSync() {\n    var exceptThreadIds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n    var isEncrypted = this.hasEncryptionStateEvent();\n    for (var [threadId, notifs] of this.threadNotifications) {\n      if (!exceptThreadIds.includes(threadId)) {\n        notifs.total = 0;\n        if (!isEncrypted) {\n          notifs.highlight = 0;\n        }\n      }\n    }\n    this.emit(RoomEvent.UnreadNotifications);\n  }\n\n  /**\n   * Set the bump stamp for this room. This can be used for sorting rooms when the timeline\n   * entries are unknown. Used in MSC4186: Simplified Sliding Sync.\n   * @param bumpStamp The bump_stamp value from the server\n   */\n  setBumpStamp(bumpStamp) {\n    this.bumpStamp = bumpStamp;\n  }\n\n  /**\n   * Get the bump stamp for this room. This can be used for sorting rooms when the timeline\n   * entries are unknown. Used in MSC4186: Simplified Sliding Sync.\n   * @returns The bump stamp for the room, if it exists.\n   */\n  getBumpStamp() {\n    return this.bumpStamp;\n  }\n\n  /**\n   * Set one of the notification counts for this room\n   * @param type - The type of notification count to set.\n   * @param count - The new count\n   */\n  setUnreadNotificationCount(type, count) {\n    this.notificationCounts[type] = count;\n    this.emit(RoomEvent.UnreadNotifications, this.notificationCounts);\n  }\n  setUnread(type, count) {\n    return this.setUnreadNotificationCount(type, count);\n  }\n\n  /**\n   * Takes a legacy room summary (/v3/sync as opposed to MSC4186) and updates the room with it.\n   *\n   * @param summary - The room summary to update the room with\n   */\n  setSummary(summary) {\n    var _summary$mHeroes;\n    var heroes = (_summary$mHeroes = summary[\"m.heroes\"]) === null || _summary$mHeroes === void 0 ? void 0 : _summary$mHeroes.map(h => ({\n      userId: h,\n      fromMSC4186: false\n    }));\n    var joinedCount = summary[\"m.joined_member_count\"];\n    var invitedCount = summary[\"m.invited_member_count\"];\n    if (Number.isInteger(joinedCount)) {\n      this.currentState.setJoinedMemberCount(joinedCount);\n    }\n    if (Number.isInteger(invitedCount)) {\n      this.currentState.setInvitedMemberCount(invitedCount);\n    }\n    if (Array.isArray(heroes)) {\n      // filter out ourselves just in case\n      this.heroes = heroes.filter(h => {\n        return h.userId != this.myUserId;\n      });\n    }\n    this.emit(RoomEvent.Summary, summary);\n  }\n\n  /**\n   * Takes information from the MSC4186 room summary and updates the room with it.\n   *\n   * @param heroes - The room's hero members\n   * @param joinedCount - The number of joined members\n   * @param invitedCount - The number of invited members\n   */\n  setMSC4186SummaryData(heroes, joinedCount, invitedCount) {\n    if (heroes) {\n      this.heroes = heroes.filter(h => h.user_id !== this.myUserId).map(h => ({\n        userId: h.user_id,\n        displayName: h.displayname,\n        avatarUrl: h.avatar_url,\n        fromMSC4186: true\n      }));\n    }\n    if (joinedCount !== undefined && Number.isInteger(joinedCount)) {\n      this.currentState.setJoinedMemberCount(joinedCount);\n    }\n    if (invitedCount !== undefined && Number.isInteger(invitedCount)) {\n      this.currentState.setInvitedMemberCount(invitedCount);\n    }\n\n    // Construct a summary object to emit as the event wants the info in a single object\n    // more like old-style (/v3/sync) summaries.\n    this.emit(RoomEvent.Summary, {\n      \"m.heroes\": this.heroes ? this.heroes.map(h => h.userId) : [],\n      \"m.joined_member_count\": joinedCount,\n      \"m.invited_member_count\": invitedCount\n    });\n  }\n\n  /**\n   * Whether to send encrypted messages to devices within this room.\n   * @param value - true to blacklist unverified devices, null\n   * to use the global value for this room.\n   */\n  setBlacklistUnverifiedDevices(value) {\n    this.blacklistUnverifiedDevices = value;\n  }\n\n  /**\n   * Whether to send encrypted messages to devices within this room.\n   * @returns true if blacklisting unverified devices, null\n   * if the global value should be used for this room.\n   */\n  getBlacklistUnverifiedDevices() {\n    if (this.blacklistUnverifiedDevices === undefined) return null;\n    return this.blacklistUnverifiedDevices;\n  }\n\n  /**\n   * Get the avatar URL for a room if one was set.\n   * @param baseUrl - The homeserver base URL. See\n   * {@link MatrixClient#getHomeserverUrl}.\n   * @param width - The desired width of the thumbnail.\n   * @param height - The desired height of the thumbnail.\n   * @param resizeMethod - The thumbnail resize method to use, either\n   * \"crop\" or \"scale\".\n   * @param allowDefault - True to allow an identicon for this room if an\n   * avatar URL wasn't explicitly set. Default: true. (Deprecated)\n   * @param useAuthentication - (optional) If true, the caller supports authenticated\n   * media and wants an authentication-required URL. Note that server support for\n   * authenticated media will not be checked - it is the caller's responsibility\n   * to do so before calling this function. Note also that useAuthentication\n   * implies allowRedirects. Defaults to false (unauthenticated endpoints).\n   * @returns the avatar URL or null.\n   */\n  getAvatarUrl(baseUrl, width, height, resizeMethod) {\n    var allowDefault = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n    var useAuthentication = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;\n    var mainUrl = this.getMxcAvatarUrl();\n    if (!mainUrl && !allowDefault) {\n      return null;\n    }\n    if (mainUrl) {\n      return getHttpUriForMxc(baseUrl, mainUrl, width, height, resizeMethod, undefined, undefined, useAuthentication);\n    }\n    return null;\n  }\n\n  /**\n   * Get the mxc avatar url for the room, if one was set.\n   * @returns the mxc avatar url or falsy\n   */\n  getMxcAvatarUrl() {\n    var _this$currentState$ge;\n    var url = (_this$currentState$ge = this.currentState.getStateEvents(EventType.RoomAvatar, \"\")) === null || _this$currentState$ge === void 0 ? void 0 : _this$currentState$ge.getContent().url;\n    return url && typeof url === \"string\" ? url : null;\n  }\n\n  /**\n   * Get this room's canonical alias\n   * The alias returned by this function may not necessarily\n   * still point to this room.\n   * @returns The room's canonical alias, or null if there is none\n   */\n  getCanonicalAlias() {\n    var _this$currentState$ge2;\n    var canonicalAlias = (_this$currentState$ge2 = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, \"\")) === null || _this$currentState$ge2 === void 0 ? void 0 : _this$currentState$ge2.getContent().alias;\n    return canonicalAlias && typeof canonicalAlias === \"string\" ? canonicalAlias : null;\n  }\n\n  /**\n   * Get this room's alternative aliases\n   * @returns The room's alternative aliases, or an empty array\n   */\n  getAltAliases() {\n    var _this$currentState$ge3;\n    var altAliases = (_this$currentState$ge3 = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, \"\")) === null || _this$currentState$ge3 === void 0 ? void 0 : _this$currentState$ge3.getContent().alt_aliases;\n    if (Array.isArray(altAliases)) {\n      return altAliases.filter(alias => typeof alias === \"string\");\n    }\n    return [];\n  }\n\n  /**\n   * Add events to a timeline\n   *\n   * <p>Will fire \"Room.timeline\" for each event added.\n   *\n   * @param events - A list of events to add.\n   *\n   * @param toStartOfTimeline -   True to add these events to the start\n   * (oldest) instead of the end (newest) of the timeline. If true, the oldest\n   * event will be the <b>last</b> element of 'events'.\n   *\n   * @param timeline -   timeline to\n   *    add events to.\n   *\n   * @param paginationToken -   token for the next batch of events\n   *\n   * @remarks\n   * Fires {@link RoomEvent.Timeline}\n   */\n  addEventsToTimeline(events, toStartOfTimeline, addToState, timeline, paginationToken) {\n    timeline.getTimelineSet().addEventsToTimeline(events, toStartOfTimeline, addToState, timeline, paginationToken);\n  }\n\n  /**\n   * Get the instance of the thread associated with the current event\n   * @param eventId - the ID of the current event\n   * @returns a thread instance if known\n   */\n  getThread(eventId) {\n    var _this$threads$get;\n    return (_this$threads$get = this.threads.get(eventId)) !== null && _this$threads$get !== void 0 ? _this$threads$get : null;\n  }\n\n  /**\n   * Get all the known threads in the room\n   */\n  getThreads() {\n    return Array.from(this.threads.values());\n  }\n\n  /**\n   * Get a member from the current room state.\n   * @param userId - The user ID of the member.\n   * @returns The member or `null`.\n   */\n  getMember(userId) {\n    return this.currentState.getMember(userId);\n  }\n\n  /**\n   * Get all currently loaded members from the current\n   * room state.\n   * @returns Room members\n   */\n  getMembers() {\n    return this.currentState.getMembers();\n  }\n\n  /**\n   * Get a list of members whose membership state is \"join\".\n   * @returns A list of currently joined members.\n   */\n  getJoinedMembers() {\n    return this.getMembersWithMembership(KnownMembership.Join);\n  }\n\n  /**\n   * Returns the number of joined members in this room\n   * This method caches the result.\n   * This is a wrapper around the method of the same name in roomState, returning\n   * its result for the room's current state.\n   * @returns The number of members in this room whose membership is 'join'\n   */\n  getJoinedMemberCount() {\n    return this.currentState.getJoinedMemberCount();\n  }\n\n  /**\n   * Returns the number of invited members in this room\n   * @returns The number of members in this room whose membership is 'invite'\n   */\n  getInvitedMemberCount() {\n    return this.currentState.getInvitedMemberCount();\n  }\n\n  /**\n   * Returns the number of invited + joined members in this room\n   * @returns The number of members in this room whose membership is 'invite' or 'join'\n   */\n  getInvitedAndJoinedMemberCount() {\n    return this.getInvitedMemberCount() + this.getJoinedMemberCount();\n  }\n\n  /**\n   * Get a list of members with given membership state.\n   * @param membership - The membership state.\n   * @returns A list of members with the given membership state.\n   */\n  getMembersWithMembership(membership) {\n    return this.currentState.getMembers().filter(function (m) {\n      return m.membership === membership;\n    });\n  }\n\n  /**\n   * Get a list of members we should be encrypting for in this room\n   * @returns A list of members who\n   * we should encrypt messages for in this room.\n   */\n  getEncryptionTargetMembers() {\n    var _this0 = this;\n    return _asyncToGenerator(function* () {\n      yield _this0.loadMembersIfNeeded();\n      var members = _this0.getMembersWithMembership(KnownMembership.Join);\n      if (_this0.shouldEncryptForInvitedMembers()) {\n        members = members.concat(_this0.getMembersWithMembership(KnownMembership.Invite));\n      }\n      return members;\n    })();\n  }\n\n  /**\n   * Determine whether we should encrypt messages for invited users in this room\n   * @returns if we should encrypt messages for invited users\n   */\n  shouldEncryptForInvitedMembers() {\n    var _ev$getContent;\n    var ev = this.currentState.getStateEvents(EventType.RoomHistoryVisibility, \"\");\n    return (ev === null || ev === void 0 || (_ev$getContent = ev.getContent()) === null || _ev$getContent === void 0 ? void 0 : _ev$getContent.history_visibility) !== \"joined\";\n  }\n\n  /**\n   * Get the default room name (i.e. what a given user would see if the\n   * room had no m.room.name)\n   * @param userId - The userId from whose perspective we want\n   * to calculate the default name\n   * @returns The default room name\n   */\n  getDefaultRoomName(userId) {\n    return this.calculateRoomName(userId, true);\n  }\n\n  /**\n   * Check if the given user_id has the given membership state.\n   * @param userId - The user ID to check.\n   * @param membership - The membership e.g. `'join'`\n   * @returns True if this user_id has the given membership state.\n   */\n  hasMembershipState(userId, membership) {\n    var member = this.getMember(userId);\n    if (!member) {\n      return false;\n    }\n    return member.membership === membership;\n  }\n\n  /**\n   * Add a timelineSet for this room with the given filter\n   * @param filter - The filter to be applied to this timelineSet\n   * @param opts - Configuration options\n   * @returns The timelineSet\n   */\n  getOrCreateFilteredTimelineSet(filter) {\n    var {\n      prepopulateTimeline = true,\n      useSyncEvents = true,\n      pendingEvents = true\n    } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    if (this.filteredTimelineSets[filter.filterId]) {\n      return this.filteredTimelineSets[filter.filterId];\n    }\n    var opts = Object.assign({\n      filter,\n      pendingEvents\n    }, this.opts);\n    var timelineSet = new EventTimelineSet(this, opts);\n    this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n    if (useSyncEvents) {\n      this.filteredTimelineSets[filter.filterId] = timelineSet;\n      this.timelineSets.push(timelineSet);\n    }\n    var unfilteredLiveTimeline = this.getLiveTimeline();\n    // Not all filter are possible to replicate client-side only\n    // When that's the case we do not want to prepopulate from the live timeline\n    // as we would get incorrect results compared to what the server would send back\n    if (prepopulateTimeline) {\n      // populate up the new timelineSet with filtered events from our live\n      // unfiltered timeline.\n      //\n      // XXX: This is risky as our timeline\n      // may have grown huge and so take a long time to filter.\n      // see https://github.com/vector-im/vector-web/issues/2109\n\n      unfilteredLiveTimeline.getEvents().forEach(function (event) {\n        timelineSet.addLiveEvent(event, {\n          addToState: false\n        }); // Filtered timeline sets should not track state\n      });\n\n      // find the earliest unfiltered timeline\n      var timeline = unfilteredLiveTimeline;\n      while (timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)) {\n        timeline = timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS);\n      }\n      timelineSet.getLiveTimeline().setPaginationToken(timeline.getPaginationToken(EventTimeline.BACKWARDS), EventTimeline.BACKWARDS);\n    } else if (useSyncEvents) {\n      var livePaginationToken = unfilteredLiveTimeline.getPaginationToken(Direction.Forward);\n      timelineSet.getLiveTimeline().setPaginationToken(livePaginationToken, Direction.Backward);\n    }\n\n    // alternatively, we could try to do something like this to try and re-paginate\n    // in the filtered events from nothing, but Mark says it's an abuse of the API\n    // to do so:\n    //\n    // timelineSet.resetLiveTimeline(\n    //      unfilteredLiveTimeline.getPaginationToken(EventTimeline.FORWARDS)\n    // );\n\n    return timelineSet;\n  }\n  getThreadListFilter() {\n    var _arguments = arguments,\n      _this1 = this;\n    return _asyncToGenerator(function* () {\n      var filterType = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : ThreadFilterType.All;\n      var myUserId = _this1.client.getUserId();\n      var filter = new Filter(myUserId);\n      var definition = {\n        room: {\n          timeline: {\n            [FILTER_RELATED_BY_REL_TYPES.name]: [THREAD_RELATION_TYPE.name]\n          }\n        }\n      };\n      if (filterType === ThreadFilterType.My) {\n        definition.room.timeline[FILTER_RELATED_BY_SENDERS.name] = [myUserId];\n      }\n      filter.setDefinition(definition);\n      var filterId = yield _this1.client.getOrCreateFilter(\"THREAD_PANEL_\".concat(_this1.roomId, \"_\").concat(filterType), filter);\n      filter.filterId = filterId;\n      return filter;\n    })();\n  }\n  createThreadTimelineSet(filterType) {\n    var _this10 = this;\n    return _asyncToGenerator(function* () {\n      var timelineSet;\n      if (Thread.hasServerSideListSupport) {\n        timelineSet = new EventTimelineSet(_this10, _objectSpread(_objectSpread({}, _this10.opts), {}, {\n          pendingEvents: false\n        }), undefined, undefined, filterType !== null && filterType !== void 0 ? filterType : ThreadFilterType.All);\n        _this10.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n      } else if (Thread.hasServerSideSupport) {\n        var filter = yield _this10.getThreadListFilter(filterType);\n        timelineSet = _this10.getOrCreateFilteredTimelineSet(filter, {\n          prepopulateTimeline: false,\n          useSyncEvents: false,\n          pendingEvents: false\n        });\n      } else {\n        timelineSet = new EventTimelineSet(_this10, {\n          pendingEvents: false\n        });\n        Array.from(_this10.threads).forEach(_ref3 => {\n          var [, thread] = _ref3;\n          if (thread.length === 0) return;\n          var currentUserParticipated = thread.timeline.some(event => {\n            return event.getSender() === _this10.client.getUserId();\n          });\n          if (filterType !== ThreadFilterType.My || currentUserParticipated) {\n            timelineSet.getLiveTimeline().addEvent(thread.rootEvent, {\n              toStartOfTimeline: false,\n              addToState: false\n            });\n          }\n        });\n      }\n      return timelineSet;\n    })();\n  }\n  /**\n   * Takes the given thread root events and creates threads for them.\n   */\n  processThreadRoots(events, toStartOfTimeline) {\n    if (!this.client.supportsThreads()) return;\n    for (var rootEvent of events) {\n      EventTimeline.setEventMetadata(rootEvent, this.currentState, toStartOfTimeline);\n      if (!this.getThread(rootEvent.getId())) {\n        this.createThread(rootEvent.getId(), rootEvent, [], toStartOfTimeline);\n      }\n    }\n  }\n\n  /**\n   * Fetch the bare minimum of room threads required for the thread list to work reliably.\n   * With server support that means fetching one page.\n   * Without server support that means fetching as much at once as the server allows us to.\n   */\n  fetchRoomThreads() {\n    var _this11 = this;\n    return _asyncToGenerator(function* () {\n      if (_this11.threadsReady || !_this11.client.supportsThreads()) {\n        return;\n      }\n      if (Thread.hasServerSideListSupport) {\n        yield Promise.all([_this11.fetchRoomThreadList(ThreadFilterType.All), _this11.fetchRoomThreadList(ThreadFilterType.My)]);\n      } else {\n        var allThreadsFilter = yield _this11.getThreadListFilter();\n        var {\n          chunk: events\n        } = yield _this11.client.createMessagesRequest(_this11.roomId, \"\", Number.MAX_SAFE_INTEGER, Direction.Backward, allThreadsFilter);\n        if (!events.length) return;\n\n        // Sorted by last_reply origin_server_ts\n        var threadRoots = events.map(_this11.client.getEventMapper()).sort((eventA, eventB) => {\n          /**\n           * `origin_server_ts` in a decentralised world is far from ideal\n           * but for lack of any better, we will have to use this\n           * Long term the sorting should be handled by homeservers and this\n           * is only meant as a short term patch\n           */\n          var threadAMetadata = eventA.getServerAggregatedRelation(THREAD_RELATION_TYPE.name);\n          var threadBMetadata = eventB.getServerAggregatedRelation(THREAD_RELATION_TYPE.name);\n          return threadAMetadata.latest_event.origin_server_ts - threadBMetadata.latest_event.origin_server_ts;\n        });\n        var latestMyThreadsRootEvent;\n        var roomState = _this11.getLiveTimeline().getState(EventTimeline.FORWARDS);\n        for (var rootEvent of threadRoots) {\n          var _this11$threadsTimeli;\n          var _opts = {\n            duplicateStrategy: DuplicateStrategy.Ignore,\n            fromCache: false,\n            addToState: false,\n            roomState\n          };\n          (_this11$threadsTimeli = _this11.threadsTimelineSets[0]) === null || _this11$threadsTimeli === void 0 || _this11$threadsTimeli.addLiveEvent(rootEvent, _opts);\n          var threadRelationship = rootEvent.getServerAggregatedRelation(THREAD_RELATION_TYPE.name);\n          if (threadRelationship !== null && threadRelationship !== void 0 && threadRelationship.current_user_participated) {\n            var _this11$threadsTimeli2;\n            (_this11$threadsTimeli2 = _this11.threadsTimelineSets[1]) === null || _this11$threadsTimeli2 === void 0 || _this11$threadsTimeli2.addLiveEvent(rootEvent, _opts);\n            latestMyThreadsRootEvent = rootEvent;\n          }\n        }\n        _this11.processThreadRoots(threadRoots, true);\n        _this11.client.decryptEventIfNeeded(threadRoots[threadRoots.length - 1]);\n        if (latestMyThreadsRootEvent) {\n          _this11.client.decryptEventIfNeeded(latestMyThreadsRootEvent);\n        }\n      }\n      _this11.on(ThreadEvent.NewReply, _this11.onThreadReply);\n      _this11.on(ThreadEvent.Update, _this11.onThreadUpdate);\n      _this11.on(ThreadEvent.Delete, _this11.onThreadDelete);\n      _this11.threadsReady = true;\n    })();\n  }\n\n  /**\n   * Process a list of poll events.\n   *\n   * @param events - List of events\n   */\n  processPollEvents(events) {\n    var _this12 = this;\n    return _asyncToGenerator(function* () {\n      for (var event of events) {\n        try {\n          // Continue if the event is a clear text, non-poll event.\n          if (!event.isEncrypted() && !isPollEvent(event)) continue;\n\n          /**\n           * Try to decrypt the event. Promise resolution does not guarantee a successful decryption.\n           * Retry is handled in {@link processPollEvent}.\n           */\n          yield _this12.client.decryptEventIfNeeded(event);\n          _this12.processPollEvent(event);\n        } catch (err) {\n          logger.warn(\"Error processing poll event\", event.getId(), err);\n        }\n      }\n    })();\n  }\n\n  /**\n   * Processes poll events:\n   * If the event has a decryption failure, it will listen for decryption and tries again.\n   * If it is a poll start event (`m.poll.start`),\n   * it creates and stores a Poll model and emits a PollEvent.New event.\n   * If the event is related to a poll, it will add it to the poll.\n   * Noop for other cases.\n   *\n   * @param event - Event that could be a poll event\n   */\n  processPollEvent(event) {\n    var _this13 = this;\n    return _asyncToGenerator(function* () {\n      if (event.isDecryptionFailure()) {\n        event.once(MatrixEventEvent.Decrypted, maybeDecryptedEvent => {\n          _this13.processPollEvent(maybeDecryptedEvent);\n        });\n        return;\n      }\n      if (M_POLL_START.matches(event.getType())) {\n        try {\n          var poll = new Poll(event, _this13.client, _this13);\n          _this13.polls.set(event.getId(), poll);\n          _this13.emit(PollEvent.New, poll);\n\n          // remove the poll when redacted\n          event.once(MatrixEventEvent.BeforeRedaction, redactedEvent => {\n            _this13.polls.delete(redactedEvent.getId());\n          });\n        } catch (_unused3) {}\n        // poll creation can fail for malformed poll start events\n        return;\n      }\n      var relationEventId = event.relationEventId;\n      if (relationEventId && _this13.polls.has(relationEventId)) {\n        var _poll = _this13.polls.get(relationEventId);\n        _poll === null || _poll === void 0 || _poll.onNewRelation(event);\n      }\n    })();\n  }\n\n  /**\n   * Fetch a single page of threadlist messages for the specific thread filter\n   * @internal\n   */\n  fetchRoomThreadList(filter) {\n    var _this14 = this;\n    return _asyncToGenerator(function* () {\n      if (!_this14.client.supportsThreads()) return;\n      if (_this14.threadsTimelineSets.length === 0) return;\n      var timelineSet = filter === ThreadFilterType.My ? _this14.threadsTimelineSets[1] : _this14.threadsTimelineSets[0];\n      var {\n        chunk: events,\n        end\n      } = yield _this14.client.createThreadListMessagesRequest(_this14.roomId, null, undefined, Direction.Backward, timelineSet.threadListType, timelineSet.getFilter());\n      timelineSet.getLiveTimeline().setPaginationToken(end !== null && end !== void 0 ? end : null, Direction.Backward);\n      if (!events.length) return;\n      var matrixEvents = events.map(_this14.client.getEventMapper());\n      _this14.processThreadRoots(matrixEvents, true);\n      var roomState = _this14.getLiveTimeline().getState(EventTimeline.FORWARDS);\n      for (var rootEvent of matrixEvents) {\n        timelineSet.addLiveEvent(rootEvent, {\n          duplicateStrategy: DuplicateStrategy.Replace,\n          fromCache: false,\n          roomState,\n          addToState: false\n        });\n      }\n    })();\n  }\n  onThreadUpdate(thread) {\n    this.updateThreadRootEvents(thread, false, false);\n  }\n  onThreadReply(thread) {\n    this.updateThreadRootEvents(thread, false, true);\n  }\n  onThreadDelete(thread) {\n    var _timeline$getEvents;\n    this.threads.delete(thread.id);\n    var timeline = this.getTimelineForEvent(thread.id);\n    var roomEvent = timeline === null || timeline === void 0 || (_timeline$getEvents = timeline.getEvents()) === null || _timeline$getEvents === void 0 ? void 0 : _timeline$getEvents.find(it => it.getId() === thread.id);\n    if (roomEvent) {\n      thread.clearEventMetadata(roomEvent);\n    } else {\n      logger.debug(\"onThreadDelete: Could not find root event in room timeline\");\n    }\n    for (var timelineSet of this.threadsTimelineSets) {\n      timelineSet.removeEvent(thread.id);\n    }\n  }\n\n  /**\n   * Forget the timelineSet for this room with the given filter\n   *\n   * @param filter - the filter whose timelineSet is to be forgotten\n   */\n  removeFilteredTimelineSet(filter) {\n    var timelineSet = this.filteredTimelineSets[filter.filterId];\n    delete this.filteredTimelineSets[filter.filterId];\n    var i = this.timelineSets.indexOf(timelineSet);\n    if (i > -1) {\n      this.timelineSets.splice(i, 1);\n    }\n  }\n\n  /**\n   * Determine which timeline(s) a given event should live in\n   * Thread roots live in both the main timeline and their corresponding thread timeline\n   * Relations, redactions, replies to thread relation events live only in the thread timeline\n   * Relations (other than m.thread), redactions, replies to a thread root live only in the main timeline\n   * Relations, redactions, replies where the parent cannot be found live in no timelines but should be aggregated regardless.\n   * Otherwise, the event lives in the main timeline only.\n   *\n   * Note: when a redaction is applied, the redacted event, events relating\n   * to it, and the redaction event itself, will all move to the main thread.\n   * This method classifies them as inside the thread of the redacted event.\n   * They are moved later as part of makeRedacted.\n   * This will change if MSC3389 is merged.\n   */\n  eventShouldLiveIn(event, events, roots) {\n    var _this$client;\n    if (!((_this$client = this.client) !== null && _this$client !== void 0 && _this$client.supportsThreads())) {\n      return {\n        shouldLiveInRoom: true,\n        shouldLiveInThread: false\n      };\n    }\n\n    // A thread root is the only event shown in both timelines\n    if (event.isThreadRoot || roots !== null && roots !== void 0 && roots.has(event.getId())) {\n      return {\n        shouldLiveInRoom: true,\n        shouldLiveInThread: true,\n        threadId: event.getId()\n      };\n    }\n    var isThreadRelation = event.isRelation(THREAD_RELATION_TYPE.name);\n    var parentEventId = event.getAssociatedId();\n    var threadRootId = event.threadRootId;\n\n    // Where the parent is the thread root and this is a non-thread relation this should live only in the main timeline\n    if (!!parentEventId && !isThreadRelation && (threadRootId === parentEventId || roots !== null && roots !== void 0 && roots.has(parentEventId))) {\n      return {\n        shouldLiveInRoom: true,\n        shouldLiveInThread: false\n      };\n    }\n    var parentEvent;\n    if (parentEventId) {\n      var _this$findEventById;\n      parentEvent = (_this$findEventById = this.findEventById(parentEventId)) !== null && _this$findEventById !== void 0 ? _this$findEventById : events === null || events === void 0 ? void 0 : events.find(e => e.getId() === parentEventId);\n    }\n\n    // Treat non-thread-relations, redactions, and replies as extensions of their parents so evaluate parentEvent instead\n    if (parentEvent && !isThreadRelation) {\n      return this.eventShouldLiveIn(parentEvent, events, roots);\n    }\n\n    // A thread relation (1st and 2nd order) is always only shown in a thread\n    if (threadRootId != undefined) {\n      return {\n        shouldLiveInRoom: false,\n        shouldLiveInThread: true,\n        threadId: threadRootId\n      };\n    }\n\n    // Due to replies not being typical relations and being used as fallbacks for threads relations\n    // If we bypass the if case above then we know we are not a thread, so if we are still a reply\n    // then we know that we must be in the main timeline. Same goes if we have no associated parent event.\n    if (!parentEventId || !!event.replyEventId) {\n      return {\n        shouldLiveInRoom: true,\n        shouldLiveInThread: false\n      };\n    }\n\n    // We've exhausted all scenarios,\n    // we cannot assume that it lives in the main timeline as this may be a relation for an unknown thread\n    // adding the event in the wrong timeline causes stuck notifications and can break ability to send read receipts\n    return {\n      shouldLiveInRoom: false,\n      shouldLiveInThread: false\n    };\n  }\n  findThreadForEvent(event) {\n    if (!event) return null;\n    var {\n      threadId\n    } = this.eventShouldLiveIn(event);\n    return threadId ? this.getThread(threadId) : null;\n  }\n  addThreadedEvents(threadId, events) {\n    var toStartOfTimeline = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n    var thread = this.getThread(threadId);\n    if (thread) {\n      thread.addEvents(events, toStartOfTimeline);\n    } else {\n      var _this$findEventById2;\n      var rootEvent = (_this$findEventById2 = this.findEventById(threadId)) !== null && _this$findEventById2 !== void 0 ? _this$findEventById2 : events.find(e => e.getId() === threadId);\n      this.createThread(threadId, rootEvent, events, toStartOfTimeline);\n    }\n  }\n\n  /**\n   * Adds events to a thread's timeline. Will fire \"Thread.update\"\n   */\n  processThreadedEvents(events, toStartOfTimeline) {\n    events.forEach(this.tryApplyRedaction);\n    var eventsByThread = {};\n    for (var event of events) {\n      var _eventsByThread;\n      var {\n        threadId,\n        shouldLiveInThread\n      } = this.eventShouldLiveIn(event);\n      if (shouldLiveInThread && !eventsByThread[threadId]) {\n        eventsByThread[threadId] = [];\n      }\n      (_eventsByThread = eventsByThread[threadId]) === null || _eventsByThread === void 0 || _eventsByThread.push(event);\n    }\n    Object.entries(eventsByThread).map(_ref4 => {\n      var [threadId, threadEvents] = _ref4;\n      return this.addThreadedEvents(threadId, threadEvents, toStartOfTimeline);\n    });\n  }\n  createThread(threadId, rootEvent) {\n    var _this$cachedThreadRea;\n    var events = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];\n    var toStartOfTimeline = arguments.length > 3 ? arguments[3] : undefined;\n    if (this.threads.has(threadId)) {\n      return this.threads.get(threadId);\n    }\n    if (rootEvent) {\n      var relatedEvents = this.relations.getAllChildEventsForEvent(rootEvent.getId());\n      if (relatedEvents !== null && relatedEvents !== void 0 && relatedEvents.length) {\n        // Include all relations of the root event, given it'll be visible in both timelines,\n        // except `m.replace` as that will already be applied atop the event using `MatrixEvent::makeReplaced`\n        events = events.concat(relatedEvents.filter(e => !e.isRelation(RelationType.Replace)));\n      }\n    }\n    var thread = new Thread(threadId, rootEvent, {\n      room: this,\n      client: this.client,\n      pendingEventOrdering: this.opts.pendingEventOrdering,\n      receipts: (_this$cachedThreadRea = this.cachedThreadReadReceipts.get(threadId)) !== null && _this$cachedThreadRea !== void 0 ? _this$cachedThreadRea : []\n    });\n\n    // Add the re-emitter before we start adding events to the thread so we don't miss events\n    this.reEmitter.reEmit(thread, [ThreadEvent.Delete, ThreadEvent.Update, ThreadEvent.NewReply, RoomEvent.Timeline, RoomEvent.TimelineReset]);\n\n    // All read receipts should now come down from sync, we do not need to keep\n    // a reference to the cached receipts anymore.\n    this.cachedThreadReadReceipts.delete(threadId);\n\n    // If we managed to create a thread and figure out its `id` then we can use it\n    // This has to happen before thread.addEvents, because that adds events to the eventtimeline, and the\n    // eventtimeline sometimes looks up thread information via the room.\n    this.threads.set(thread.id, thread);\n\n    // This is necessary to be able to jump to events in threads:\n    // If we jump to an event in a thread where neither the event, nor the root,\n    // nor any thread event are loaded yet, we'll load the event as well as the thread root, create the thread,\n    // and pass the event through this.\n    thread.addEvents(events, false);\n\n    // We need to update the thread root events, but the thread may not be ready yet.\n    // If it isn't, it will fire ThreadEvent.Update when it is and we'll call updateThreadRootEvents then.\n    if (this.threadsReady && thread.initialEventsFetched) {\n      this.updateThreadRootEvents(thread, toStartOfTimeline, false);\n    }\n    this.emit(ThreadEvent.New, thread, toStartOfTimeline);\n    return thread;\n  }\n\n  /**\n   * Applies an event as a redaction of another event, regardless of whether the redacting\n   * event is actually a redaction.\n   *\n   * Callers should use tryApplyRedaction instead.\n   *\n   * @param redactionEvent The event which redacts an event.\n   * @param redactedEvent The event being redacted.\n   * @private\n   */\n  applyEventAsRedaction(redactionEvent, redactedEvent) {\n    var threadRootId = redactedEvent.threadRootId;\n    redactedEvent.makeRedacted(redactionEvent, this);\n\n    // If this is in the current state, replace it with the redacted version\n    if (redactedEvent.isState()) {\n      var currentStateEvent = this.currentState.getStateEvents(redactedEvent.getType(), redactedEvent.getStateKey());\n      if ((currentStateEvent === null || currentStateEvent === void 0 ? void 0 : currentStateEvent.getId()) === redactedEvent.getId()) {\n        this.currentState.setStateEvents([redactedEvent]);\n      }\n    }\n    this.emit(RoomEvent.Redaction, redactionEvent, this, threadRootId);\n\n    // TODO: we stash user displaynames (among other things) in\n    // RoomMember objects which are then attached to other events\n    // (in the sender and target fields). We should get those\n    // RoomMember objects to update themselves when the events that\n    // they are based on are changed.\n\n    // Remove any visibility change on this event.\n    this.visibilityEvents.delete(redactedEvent.getId());\n\n    // If this event is a visibility change event, remove it from the\n    // list of visibility changes and update any event affected by it.\n    if (redactedEvent.isVisibilityEvent()) {\n      this.redactVisibilityChangeEvent(redactionEvent);\n    }\n  }\n  processLiveEvent(event) {\n    this.tryApplyRedaction(event);\n\n    // Implement MSC3531: hiding messages.\n    if (event.isVisibilityEvent()) {\n      // This event changes the visibility of another event, record\n      // the visibility change, inform clients if necessary.\n      this.applyNewVisibilityEvent(event);\n    }\n    // If any pending visibility change is waiting for this (older) event,\n    this.applyPendingVisibilityEvents(event);\n\n    // Sliding Sync modifications:\n    // The proxy cannot guarantee every sent event will have a transaction_id field, so we need\n    // to check the event ID against the list of pending events if there is no transaction ID\n    // field. Only do this for events sent by us though as it's potentially expensive to loop\n    // the pending events map.\n    var txnId = event.getUnsigned().transaction_id;\n    if (!txnId && event.getSender() === this.myUserId) {\n      // check the txn map for a matching event ID\n      for (var [tid, localEvent] of this.txnToEvent) {\n        if (localEvent.getId() === event.getId()) {\n          logger.debug(\"processLiveEvent: found sent event without txn ID: \", tid, event.getId());\n          // update the unsigned field so we can re-use the same codepaths\n          var unsigned = event.getUnsigned();\n          unsigned.transaction_id = tid;\n          event.setUnsigned(unsigned);\n          break;\n        }\n      }\n    }\n  }\n\n  /**\n   * Add an event to the end of this room's live timelines. Will fire\n   * \"Room.timeline\".\n   *\n   * @param event - Event to be added\n   * @param addLiveEventOptions - addLiveEvent options\n   * @internal\n   *\n   * @remarks\n   * Fires {@link RoomEvent.Timeline}\n   */\n  addLiveEvent(event, addLiveEventOptions) {\n    var {\n      duplicateStrategy,\n      timelineWasEmpty,\n      fromCache,\n      addToState\n    } = addLiveEventOptions;\n\n    // add to our timeline sets\n    for (var timelineSet of this.timelineSets) {\n      timelineSet.addLiveEvent(event, {\n        duplicateStrategy,\n        fromCache,\n        timelineWasEmpty,\n        addToState\n      });\n    }\n\n    // synthesize and inject implicit read receipts\n    // Done after adding the event because otherwise the app would get a read receipt\n    // pointing to an event that wasn't yet in the timeline\n    // Don't synthesize RR for m.room.redaction as this causes the RR to go missing.\n    if (event.sender && event.getType() !== EventType.RoomRedaction) {\n      this.addReceipt(synthesizeReceipt(event.sender.userId, event, ReceiptType.Read), true);\n\n      // Any live events from a user could be taken as implicit\n      // presence information: evidence that they are currently active.\n      // ...except in a world where we use 'user.currentlyActive' to reduce\n      // presence spam, this isn't very useful - we'll get a transition when\n      // they are no longer currently active anyway. So don't bother to\n      // reset the lastActiveAgo and lastPresenceTs from the RoomState's user.\n    }\n  }\n\n  /**\n   * Add a pending outgoing event to this room.\n   *\n   * <p>The event is added to either the pendingEventList, or the live timeline,\n   * depending on the setting of opts.pendingEventOrdering.\n   *\n   * <p>This is an internal method, intended for use by MatrixClient.\n   *\n   * @param event - The event to add.\n   *\n   * @param txnId - Transaction id for this outgoing event\n   *\n   * @throws if the event doesn't have status SENDING, or we aren't given a\n   * unique transaction id.\n   *\n   * @remarks\n   * Fires {@link RoomEvent.LocalEchoUpdated}\n   */\n  addPendingEvent(event, txnId) {\n    if (event.status !== EventStatus.SENDING && event.status !== EventStatus.NOT_SENT) {\n      throw new Error(\"addPendingEvent called on an event with status \" + event.status);\n    }\n    if (this.txnToEvent.get(txnId)) {\n      throw new Error(\"addPendingEvent called on an event with known txnId \" + txnId);\n    }\n\n    // call setEventMetadata to set up event.sender etc\n    // as event is shared over all timelineSets, we set up its metadata based\n    // on the unfiltered timelineSet.\n    EventTimeline.setEventMetadata(event, this.getLiveTimeline().getState(EventTimeline.FORWARDS), false);\n    this.txnToEvent.set(txnId, event);\n    if (this.pendingEventList) {\n      if (this.pendingEventList.some(e => e.status === EventStatus.NOT_SENT)) {\n        logger.warn(\"Setting event as NOT_SENT due to messages in the same state\");\n        event.setStatus(EventStatus.NOT_SENT);\n      }\n      this.pendingEventList.push(event);\n      this.savePendingEvents();\n      if (event.isRelation()) {\n        // For pending events, add them to the relations collection immediately.\n        // (The alternate case below already covers this as part of adding to\n        // the timeline set.)\n        this.aggregateNonLiveRelation(event);\n      }\n      if (event.isRedaction()) {\n        var redactId = event.event.redacts;\n        var redactedEvent = this.pendingEventList.find(e => e.getId() === redactId);\n        if (!redactedEvent && redactId) {\n          redactedEvent = this.findEventById(redactId);\n        }\n        if (redactedEvent) {\n          redactedEvent.markLocallyRedacted(event);\n          this.emit(RoomEvent.Redaction, event, this, redactedEvent.threadRootId);\n        }\n      }\n    } else {\n      for (var timelineSet of this.timelineSets) {\n        if (timelineSet.getFilter()) {\n          if (timelineSet.getFilter().filterRoomTimeline([event]).length) {\n            timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {\n              toStartOfTimeline: false,\n              addToState: false // We don't support localEcho of state events yet\n            });\n          }\n        } else {\n          timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {\n            toStartOfTimeline: false,\n            addToState: false // We don't support localEcho of state events yet\n          });\n        }\n      }\n    }\n    this.emit(RoomEvent.LocalEchoUpdated, event, this);\n  }\n\n  /**\n   * Persists all pending events to local storage\n   *\n   * If the current room is encrypted only encrypted events will be persisted\n   * all messages that are not yet encrypted will be discarded\n   *\n   * This is because the flow of EVENT_STATUS transition is\n   * `queued => sending => encrypting => sending => sent`\n   *\n   * Steps 3 and 4 are skipped for unencrypted room.\n   * It is better to discard an unencrypted message rather than persisting\n   * it locally for everyone to read\n   */\n  savePendingEvents() {\n    if (this.pendingEventList) {\n      var pendingEvents = this.pendingEventList.map(event => {\n        return _objectSpread(_objectSpread({}, event.event), {}, {\n          txn_id: event.getTxnId()\n        });\n      }).filter(event => {\n        // Filter out the unencrypted messages if the room is encrypted\n        var isEventEncrypted = event.type === EventType.RoomMessageEncrypted;\n        var isRoomEncrypted = this.hasEncryptionStateEvent();\n        return isEventEncrypted || !isRoomEncrypted;\n      });\n      this.client.store.setPendingEvents(this.roomId, pendingEvents);\n    }\n  }\n\n  /**\n   * Used to aggregate the local echo for a relation, and also\n   * for re-applying a relation after it's redaction has been cancelled,\n   * as the local echo for the redaction of the relation would have\n   * un-aggregated the relation. Note that this is different from regular messages,\n   * which are just kept detached for their local echo.\n   *\n   * Also note that live events are aggregated in the live EventTimelineSet.\n   * @param event - the relation event that needs to be aggregated.\n   */\n  aggregateNonLiveRelation(event) {\n    this.relations.aggregateChildEvent(event);\n  }\n  getEventForTxnId(txnId) {\n    return this.txnToEvent.get(txnId);\n  }\n\n  /**\n   * Deal with the echo of a message we sent.\n   *\n   * <p>We move the event to the live timeline if it isn't there already, and\n   * update it.\n   *\n   * @param remoteEvent -   The event received from\n   *    /sync\n   * @param localEvent -    The local echo, which\n   *    should be either in the pendingEventList or the timeline.\n   *\n   * @internal\n   *\n   * @remarks\n   * Fires {@link RoomEvent.LocalEchoUpdated}\n   */\n  handleRemoteEcho(remoteEvent, localEvent) {\n    var oldEventId = localEvent.getId();\n    var newEventId = remoteEvent.getId();\n    var oldStatus = localEvent.status;\n    logger.debug(\"Got remote echo for event \".concat(oldEventId, \" -> \").concat(newEventId, \" old status \").concat(oldStatus));\n\n    // no longer pending\n    this.txnToEvent.delete(remoteEvent.getUnsigned().transaction_id);\n\n    // if it's in the pending list, remove it\n    if (this.pendingEventList) {\n      this.removePendingEvent(oldEventId);\n    }\n\n    // replace the event source (this will preserve the plaintext payload if\n    // any, which is good, because we don't want to try decoding it again).\n    localEvent.handleRemoteEcho(remoteEvent.event);\n    var {\n      shouldLiveInRoom,\n      threadId\n    } = this.eventShouldLiveIn(remoteEvent);\n    var thread = threadId ? this.getThread(threadId) : null;\n    thread === null || thread === void 0 || thread.setEventMetadata(localEvent);\n    thread === null || thread === void 0 || thread.timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);\n    if (shouldLiveInRoom) {\n      for (var timelineSet of this.timelineSets) {\n        // if it's already in the timeline, update the timeline map. If it's not, add it.\n        timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);\n      }\n    }\n    this.emit(RoomEvent.LocalEchoUpdated, localEvent, this, oldEventId, oldStatus);\n  }\n\n  /**\n   * Update the status / event id on a pending event, to reflect its transmission\n   * progress.\n   *\n   * <p>This is an internal method.\n   *\n   * @param event -      local echo event\n   * @param newStatus -  status to assign\n   * @param newEventId -      new event id to assign. Ignored unless newStatus == EventStatus.SENT.\n   *\n   * @remarks\n   * Fires {@link RoomEvent.LocalEchoUpdated}\n   */\n  updatePendingEvent(event, newStatus, newEventId) {\n    logger.log(\"setting pendingEvent status to \".concat(newStatus, \" in \").concat(event.getRoomId(), \" \") + \"event ID \".concat(event.getId(), \" -> \").concat(newEventId));\n\n    // if the message was sent, we expect an event id\n    if (newStatus == EventStatus.SENT && !newEventId) {\n      throw new Error(\"updatePendingEvent called with status=SENT, but no new event id\");\n    }\n\n    // SENT races against /sync, so we have to special-case it.\n    if (newStatus == EventStatus.SENT) {\n      var timeline = this.getTimelineForEvent(newEventId);\n      if (timeline) {\n        // we've already received the event via the event stream.\n        // nothing more to do here, assuming the transaction ID was correctly matched.\n        // Let's check that.\n        var remoteEvent = this.findEventById(newEventId);\n        var remoteTxnId = remoteEvent === null || remoteEvent === void 0 ? void 0 : remoteEvent.getUnsigned().transaction_id;\n        if (!remoteTxnId && remoteEvent) {\n          // This code path is mostly relevant for the Sliding Sync proxy.\n          // The remote event did not contain a transaction ID, so we did not handle\n          // the remote echo yet. Handle it now.\n          var unsigned = remoteEvent.getUnsigned();\n          unsigned.transaction_id = event.getTxnId();\n          remoteEvent.setUnsigned(unsigned);\n          // the remote event is _already_ in the timeline, so we need to remove it so\n          // we can convert the local event into the final event.\n          this.removeEvent(remoteEvent.getId());\n          this.handleRemoteEcho(remoteEvent, event);\n        }\n        return;\n      }\n    }\n    var oldStatus = event.status;\n    var oldEventId = event.getId();\n    if (!oldStatus) {\n      throw new Error(\"updatePendingEventStatus called on an event which is not a local echo.\");\n    }\n    var allowed = ALLOWED_TRANSITIONS[oldStatus];\n    if (!(allowed !== null && allowed !== void 0 && allowed.includes(newStatus))) {\n      throw new Error(\"Invalid EventStatus transition \".concat(oldStatus, \"->\").concat(newStatus));\n    }\n    event.setStatus(newStatus);\n    if (newStatus == EventStatus.SENT) {\n      // update the event id\n      event.replaceLocalEventId(newEventId);\n      var {\n        shouldLiveInRoom,\n        threadId\n      } = this.eventShouldLiveIn(event);\n      var thread = threadId ? this.getThread(threadId) : undefined;\n      thread === null || thread === void 0 || thread.setEventMetadata(event);\n      thread === null || thread === void 0 || thread.timelineSet.replaceEventId(oldEventId, newEventId);\n      if (shouldLiveInRoom) {\n        // if the event was already in the timeline (which will be the case if\n        // opts.pendingEventOrdering==chronological), we need to update the\n        // timeline map.\n        for (var timelineSet of this.timelineSets) {\n          timelineSet.replaceEventId(oldEventId, newEventId);\n        }\n      }\n    } else if (newStatus == EventStatus.CANCELLED) {\n      // remove it from the pending event list, or the timeline.\n      if (this.pendingEventList) {\n        var removedEvent = this.getPendingEvent(oldEventId);\n        this.removePendingEvent(oldEventId);\n        if (removedEvent !== null && removedEvent !== void 0 && removedEvent.isRedaction()) {\n          this.revertRedactionLocalEcho(removedEvent);\n        }\n      }\n      this.removeEvent(oldEventId);\n    }\n    this.savePendingEvents();\n    this.emit(RoomEvent.LocalEchoUpdated, event, this, oldEventId, oldStatus);\n  }\n  revertRedactionLocalEcho(redactionEvent) {\n    var redactId = redactionEvent.event.redacts;\n    if (!redactId) {\n      return;\n    }\n    var redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId);\n    if (redactedEvent) {\n      redactedEvent.unmarkLocallyRedacted();\n      // re-render after undoing redaction\n      this.emit(RoomEvent.RedactionCancelled, redactionEvent, this);\n      // reapply relation now redaction failed\n      if (redactedEvent.isRelation()) {\n        this.aggregateNonLiveRelation(redactedEvent);\n      }\n    }\n  }\n  assertTimelineSetsAreLive() {\n    for (var i = 0; i < this.timelineSets.length; i++) {\n      var liveTimeline = this.timelineSets[i].getLiveTimeline();\n      if (liveTimeline.getPaginationToken(EventTimeline.FORWARDS)) {\n        throw new Error(\"live timeline \" + i + \" is no longer live - it has a pagination token \" + \"(\" + liveTimeline.getPaginationToken(EventTimeline.FORWARDS) + \")\");\n      }\n      if (liveTimeline.getNeighbouringTimeline(EventTimeline.FORWARDS)) {\n        throw new Error(\"live timeline \".concat(i, \" is no longer live - it has a neighbouring timeline\"));\n      }\n    }\n  }\n\n  /**\n   * Add some events to this room. This can include state events, message\n   * events and typing notifications. These events are treated as \"live\" so\n   * they will go to the end of the timeline.\n   *\n   * @param events - A list of events to add.\n   * @param addLiveEventOptions - addLiveEvent options\n   * @throws If `duplicateStrategy` is not falsey, 'replace' or 'ignore'.\n   */\n  addLiveEvents(events, addLiveEventOptions) {\n    var _this15 = this;\n    return _asyncToGenerator(function* () {\n      var {\n        duplicateStrategy,\n        fromCache,\n        timelineWasEmpty = false,\n        addToState\n      } = addLiveEventOptions;\n      if (duplicateStrategy && [\"replace\", \"ignore\"].indexOf(duplicateStrategy) === -1) {\n        throw new Error(\"duplicateStrategy MUST be either 'replace' or 'ignore'\");\n      }\n\n      // sanity check that the live timeline is still live\n      _this15.assertTimelineSetsAreLive();\n      var threadRoots = _this15.findThreadRoots(events);\n      var eventsByThread = {};\n      var options = {\n        duplicateStrategy,\n        fromCache,\n        timelineWasEmpty,\n        addToState\n      };\n\n      // List of extra events to check for being parents of any relations encountered\n      var neighbouringEvents = [...events];\n      for (var event of events) {\n        var _eventsByThread$threa;\n        // TODO: We should have a filter to say \"only add state event types X Y Z to the timeline\".\n        _this15.processLiveEvent(event);\n        if (event.getUnsigned().transaction_id) {\n          var existingEvent = _this15.txnToEvent.get(event.getUnsigned().transaction_id);\n          if (existingEvent) {\n            // remote echo of an event we sent earlier\n            _this15.handleRemoteEcho(event, existingEvent);\n            continue; // we can skip adding the event to the timeline sets, it is already there\n          }\n        }\n        var {\n          shouldLiveInRoom,\n          shouldLiveInThread,\n          threadId = \"\"\n        } = _this15.eventShouldLiveIn(event, neighbouringEvents, threadRoots);\n        if (!shouldLiveInThread && !shouldLiveInRoom && event.isRelation()) {\n          try {\n            var parentEvent = new MatrixEvent(yield _this15.client.fetchRoomEvent(_this15.roomId, event.relationEventId));\n            neighbouringEvents.push(parentEvent);\n            if (parentEvent.threadRootId) {\n              threadRoots.add(parentEvent.threadRootId);\n              var unsigned = event.getUnsigned();\n              unsigned[UNSIGNED_THREAD_ID_FIELD.name] = parentEvent.threadRootId;\n              event.setUnsigned(unsigned);\n            }\n            ({\n              shouldLiveInRoom,\n              shouldLiveInThread,\n              threadId = \"\"\n            } = _this15.eventShouldLiveIn(event, neighbouringEvents, threadRoots));\n          } catch (e) {\n            logger.error(\"Failed to load parent event of unhandled relation\", e);\n          }\n        }\n        if (shouldLiveInThread && !eventsByThread[threadId]) {\n          eventsByThread[threadId] = [];\n        }\n        (_eventsByThread$threa = eventsByThread[threadId]) === null || _eventsByThread$threa === void 0 || _eventsByThread$threa.push(event);\n        if (shouldLiveInRoom) {\n          _this15.addLiveEvent(event, options);\n        } else if (!shouldLiveInThread && event.isRelation()) {\n          _this15.relations.aggregateChildEvent(event);\n        }\n      }\n      Object.entries(eventsByThread).forEach(_ref5 => {\n        var [threadId, threadEvents] = _ref5;\n        _this15.addThreadedEvents(threadId, threadEvents, false);\n      });\n    })();\n  }\n  partitionThreadedEvents(events) {\n    // Indices to the events array, for readability\n    var ROOM = 0;\n    var THREAD = 1;\n    var UNKNOWN_RELATION = 2;\n    if (this.client.supportsThreads()) {\n      var threadRoots = this.findThreadRoots(events);\n      return events.reduce((memo, event) => {\n        var {\n          shouldLiveInRoom,\n          shouldLiveInThread,\n          threadId\n        } = this.eventShouldLiveIn(event, events, threadRoots);\n        if (shouldLiveInRoom) {\n          memo[ROOM].push(event);\n        }\n        if (shouldLiveInThread) {\n          event.setThreadId(threadId !== null && threadId !== void 0 ? threadId : \"\");\n          memo[THREAD].push(event);\n        }\n        if (!shouldLiveInThread && !shouldLiveInRoom) {\n          memo[UNKNOWN_RELATION].push(event);\n        }\n        return memo;\n      }, [[], [], []]);\n    } else {\n      // When `threadSupport` is disabled treat all events as timelineEvents\n      return [events, [], []];\n    }\n  }\n\n  /**\n   * Given some events, find the IDs of all the thread roots that are referred to by them.\n   */\n  findThreadRoots(events) {\n    var threadRoots = new Set();\n    for (var event of events) {\n      var threadRootId = event.threadRootId;\n      if (threadRootId != undefined) {\n        threadRoots.add(threadRootId);\n      }\n    }\n    return threadRoots;\n  }\n\n  /**\n   * Add a receipt event to the room.\n   * @param event - The m.receipt event.\n   * @param synthetic - True if this event is implicit.\n   */\n  addReceipt(event) {\n    var synthetic = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n    var content = event.getContent();\n    this.roomReceipts.add(content, synthetic);\n\n    // TODO: delete the following code when it has been replaced by RoomReceipts\n    Object.keys(content).forEach(eventId => {\n      Object.keys(content[eventId]).forEach(receiptType => {\n        Object.keys(content[eventId][receiptType]).forEach(userId => {\n          var _receipt$thread_id, _this$unthreadedRecei, _this$unthreadedRecei2;\n          var receipt = content[eventId][receiptType][userId];\n          var receiptForMainTimeline = !receipt.thread_id || receipt.thread_id === MAIN_ROOM_TIMELINE;\n          var receiptDestination = receiptForMainTimeline ? this : this.threads.get((_receipt$thread_id = receipt.thread_id) !== null && _receipt$thread_id !== void 0 ? _receipt$thread_id : \"\");\n          if (receiptDestination) {\n            receiptDestination.addReceiptToStructure(eventId, receiptType, userId, receipt, synthetic);\n\n            // If the read receipt sent for the logged in user matches\n            // the last event of the live timeline, then we know for a fact\n            // that the user has read that message, so we can mark the room\n            // as read and not wait for the remote echo from synapse.\n            //\n            // This needs to be done after the initial sync as we do not want this\n            // logic to run whilst the room is being initialised\n            //\n            // We only do this for non-synthetic receipts, because\n            // our intention is to do this when the user really did\n            // just read a message, not when we are e.g. receiving\n            // an event during the sync. More explanation at:\n            // https://github.com/matrix-org/matrix-js-sdk/issues/3684\n            if (!synthetic && this.client.isInitialSyncComplete() && userId === this.client.getUserId()) {\n              var lastEvent = receiptDestination.timeline[receiptDestination.timeline.length - 1];\n              if (lastEvent && eventId === lastEvent.getId() && userId === lastEvent.getSender()) {\n                receiptDestination.setUnread(NotificationCountType.Total, 0);\n                receiptDestination.setUnread(NotificationCountType.Highlight, 0);\n              }\n            }\n          } else {\n            var _this$cachedThreadRea2;\n            // The thread does not exist locally, keep the read receipt\n            // in a cache locally, and re-apply  the `addReceipt` logic\n            // when the thread is created\n            this.cachedThreadReadReceipts.set(receipt.thread_id, [...((_this$cachedThreadRea2 = this.cachedThreadReadReceipts.get(receipt.thread_id)) !== null && _this$cachedThreadRea2 !== void 0 ? _this$cachedThreadRea2 : []), {\n              eventId,\n              receiptType,\n              userId,\n              receipt,\n              synthetic\n            }]);\n          }\n          var me = this.client.getUserId();\n          // Track the time of the current user's oldest threaded receipt in the room.\n          if (userId === me && !receiptForMainTimeline && receipt.ts < this.oldestThreadedReceiptTs) {\n            this.oldestThreadedReceiptTs = receipt.ts;\n          }\n\n          // Track each user's unthreaded read receipt.\n          if (!receipt.thread_id && receipt.ts > ((_this$unthreadedRecei = (_this$unthreadedRecei2 = this.unthreadedReceipts.get(userId)) === null || _this$unthreadedRecei2 === void 0 ? void 0 : _this$unthreadedRecei2.ts) !== null && _this$unthreadedRecei !== void 0 ? _this$unthreadedRecei : 0)) {\n            this.unthreadedReceipts.set(userId, receipt);\n          }\n        });\n      });\n    });\n    // End of code to delete when replaced by RoomReceipts\n\n    // send events after we've regenerated the structure & cache, otherwise things that\n    // listened for the event would read stale data.\n    this.emit(RoomEvent.Receipt, event, this);\n  }\n\n  /**\n   * Adds/handles ephemeral events such as typing notifications and read receipts.\n   * @param events - A list of events to process\n   */\n  addEphemeralEvents(events) {\n    for (var event of events) {\n      if (event.getType() === EventType.Typing) {\n        this.currentState.setTypingEvent(event);\n      } else if (event.getType() === EventType.Receipt) {\n        this.addReceipt(event);\n      } // else ignore - life is too short for us to care about these events\n    }\n  }\n\n  /**\n   * Removes events from this room.\n   * @param eventIds - A list of eventIds to remove.\n   */\n  removeEvents(eventIds) {\n    for (var eventId of eventIds) {\n      this.removeEvent(eventId);\n    }\n  }\n\n  /**\n   * Removes a single event from this room.\n   *\n   * @param eventId -  The id of the event to remove\n   *\n   * @returns true if the event was removed from any of the room's timeline sets\n   */\n  removeEvent(eventId) {\n    var removedAny = false;\n    for (var timelineSet of this.timelineSets) {\n      var removed = timelineSet.removeEvent(eventId);\n      if (removed) {\n        if (removed.isRedaction()) {\n          this.revertRedactionLocalEcho(removed);\n        }\n        removedAny = true;\n      }\n    }\n    return removedAny;\n  }\n\n  /**\n   * Recalculate various aspects of the room, including the room name and\n   * room summary. Call this any time the room's current state is modified.\n   * May fire \"Room.name\" if the room name is updated.\n   *\n   * @remarks\n   * Fires {@link RoomEvent.Name}\n   */\n  recalculate() {\n    // set fake stripped state events if this is an invite room so logic remains\n    // consistent elsewhere.\n    var membershipEvent = this.currentState.getStateEvents(EventType.RoomMember, this.myUserId);\n    if (membershipEvent) {\n      var membership = membershipEvent.getContent().membership;\n      this.updateMyMembership(membership);\n      if (membership === KnownMembership.Invite) {\n        var strippedStateEvents = membershipEvent.getUnsigned().invite_room_state || [];\n        strippedStateEvents.forEach(strippedEvent => {\n          var existingEvent = this.currentState.getStateEvents(strippedEvent.type, strippedEvent.state_key);\n          if (!existingEvent) {\n            // set the fake stripped event instead\n            this.currentState.setStateEvents([new MatrixEvent({\n              type: strippedEvent.type,\n              state_key: strippedEvent.state_key,\n              content: strippedEvent.content,\n              event_id: \"$fake\" + Date.now(),\n              room_id: this.roomId,\n              sender: this.myUserId // technically a lie\n            })]);\n          }\n        });\n      }\n    }\n    var oldName = this.name;\n    this.name = this.calculateRoomName(this.myUserId);\n    this.normalizedName = normalize(this.name);\n    this.summary = new RoomSummary(this.roomId, {\n      title: this.name\n    });\n    if (oldName !== this.name) {\n      this.emit(RoomEvent.Name, this);\n    }\n  }\n\n  /**\n   * Update the room-tag event for the room.  The previous one is overwritten.\n   * @param event - the m.tag event\n   */\n  addTags(event) {\n    // event content looks like:\n    // content: {\n    //    tags: {\n    //       $tagName: { $metadata: $value },\n    //       $tagName: { $metadata: $value },\n    //    }\n    // }\n\n    // XXX: do we need to deep copy here?\n    this.tags = event.getContent().tags || {};\n\n    // XXX: we could do a deep-comparison to see if the tags have really\n    // changed - but do we want to bother?\n    this.emit(RoomEvent.Tags, event, this);\n  }\n\n  /**\n   * Update the account_data events for this room, overwriting events of the same type.\n   * @param events - an array of account_data events to add\n   */\n  addAccountData(events) {\n    for (var event of events) {\n      if (event.getType() === \"m.tag\") {\n        this.addTags(event);\n      }\n      var eventType = event.getType();\n      var lastEvent = this.accountData.get(eventType);\n      this.accountData.set(eventType, event);\n      this.emit(RoomEvent.AccountData, event, this, lastEvent);\n    }\n  }\n\n  /**\n   * Access account_data event of given event type for this room\n   * @param type - the type of account_data event to be accessed\n   * @returns the account_data event in question\n   */\n  getAccountData(type) {\n    return this.accountData.get(type);\n  }\n\n  /**\n   * Get an iterator of currently active sticky events.\n   */\n  // eslint-disable-next-line\n  _unstable_getStickyEvents() {\n    return this.stickyEvents.getStickyEvents();\n  }\n\n  /**\n   * Get a sticky event that match the given `type`, `sender`, and `stickyKey`\n   * @param type The event `type`.\n   * @param sender The sender of the sticky event.\n   * @param stickyKey The sticky key used by the event.\n   * @returns A matching active sticky event, or undefined.\n   */\n  // eslint-disable-next-line\n  _unstable_getKeyedStickyEvent(sender, type, stickyKey) {\n    return this.stickyEvents.getKeyedStickyEvent(sender, type, stickyKey);\n  }\n\n  /**\n   * Get active sticky events without a sticky key that match the given `type` and `sender`.\n   * @param type The event `type`.\n   * @param sender The sender of the sticky event.\n   * @returns An array of matching sticky events.\n   */\n  // eslint-disable-next-line\n  _unstable_getUnkeyedStickyEvent(sender, type) {\n    return this.stickyEvents.getUnkeyedStickyEvent(sender, type);\n  }\n\n  /**\n   * Add a series of sticky events, emitting `RoomEvent.StickyEvents` if any\n   * changes were made.\n   * @param events A set of new sticky events.\n   * @internal\n   */\n  // eslint-disable-next-line\n  _unstable_addStickyEvents(events) {\n    return this.stickyEvents.addStickyEvents(events);\n  }\n\n  /**\n   * Returns whether the syncing user has permission to send a message in the room\n   * @returns true if the user should be permitted to send\n   *                   message events into the room.\n   */\n  maySendMessage() {\n    return this.getMyMembership() === KnownMembership.Join && (this.hasEncryptionStateEvent() ? this.currentState.maySendEvent(EventType.RoomMessageEncrypted, this.myUserId) : this.currentState.maySendEvent(EventType.RoomMessage, this.myUserId));\n  }\n\n  /**\n   * Returns whether the given user has permissions to issue an invite for this room.\n   * @param userId - the ID of the Matrix user to check permissions for\n   * @returns true if the user should be permitted to issue invites for this room.\n   */\n  canInvite(userId) {\n    var canInvite = this.getMyMembership() === KnownMembership.Join;\n    var powerLevelsEvent = this.currentState.getStateEvents(EventType.RoomPowerLevels, \"\");\n    var powerLevels = powerLevelsEvent && powerLevelsEvent.getContent();\n    var me = this.getMember(userId);\n    if (powerLevels && me && powerLevels.invite > me.powerLevel) {\n      canInvite = false;\n    }\n    return canInvite;\n  }\n\n  /**\n   * Returns the join rule based on the m.room.join_rule state event, defaulting to `invite`.\n   * @returns the join_rule applied to this room\n   */\n  getJoinRule() {\n    return this.currentState.getJoinRule();\n  }\n\n  /**\n   * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.\n   * @returns the history_visibility applied to this room\n   */\n  getHistoryVisibility() {\n    return this.currentState.getHistoryVisibility();\n  }\n\n  /**\n   * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.\n   * @returns the history_visibility applied to this room\n   */\n  getGuestAccess() {\n    return this.currentState.getGuestAccess();\n  }\n\n  /**\n   * Returns the type of the room from the `m.room.create` event content or undefined if none is set\n   * @returns the type of the room.\n   */\n  getType() {\n    var createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n    if (!createEvent) {\n      if (!this.getTypeWarning) {\n        logger.warn(\"[getType] Room \" + this.roomId + \" does not have an m.room.create event\");\n        this.getTypeWarning = true;\n      }\n      return undefined;\n    }\n    return createEvent.getContent()[RoomCreateTypeField];\n  }\n\n  /**\n   * Returns whether the room is a space-room as defined by MSC1772.\n   * @returns true if the room's type is RoomType.Space\n   */\n  isSpaceRoom() {\n    return this.getType() === RoomType.Space;\n  }\n\n  /**\n   * Returns whether the room is a call-room as defined by MSC3417.\n   * @returns true if the room's type is RoomType.UnstableCall\n   */\n  isCallRoom() {\n    return this.getType() === RoomType.UnstableCall;\n  }\n\n  /**\n   * Returns whether the room is a video room.\n   * @returns true if the room's type is RoomType.ElementVideo\n   */\n  isElementVideoRoom() {\n    return this.getType() === RoomType.ElementVideo;\n  }\n\n  /**\n   * Find the predecessor of this room.\n   *\n   * @param msc3946ProcessDynamicPredecessor - if true, look for an\n   * m.room.predecessor state event and use it if found (MSC3946).\n   * @returns null if this room has no predecessor. Otherwise, returns\n   * the roomId, last eventId and viaServers of the predecessor room.\n   *\n   * If msc3946ProcessDynamicPredecessor is true, use m.predecessor events\n   * as well as m.room.create events to find predecessors.\n   *\n   * Note: if an m.predecessor event is used, eventId may be undefined\n   * since last_known_event_id is optional.\n   *\n   * Note: viaServers may be undefined, and will definitely be undefined if\n   * this predecessor comes from a RoomCreate event (rather than a\n   * RoomPredecessor, which has the optional via_servers property).\n   */\n  findPredecessor() {\n    var msc3946ProcessDynamicPredecessor = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n    var currentState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);\n    if (!currentState) {\n      return null;\n    }\n    return currentState.findPredecessor(msc3946ProcessDynamicPredecessor);\n  }\n  roomNameGenerator(state) {\n    if (this.client.roomNameGenerator) {\n      var name = this.client.roomNameGenerator(this.roomId, state);\n      if (name !== null) {\n        return name;\n      }\n    }\n    switch (state.type) {\n      case RoomNameType.Actual:\n        return state.name;\n      case RoomNameType.Generated:\n        switch (state.subtype) {\n          case \"Inviting\":\n            return \"Inviting \".concat(memberNamesToRoomName(state.names, state.count));\n          default:\n            return memberNamesToRoomName(state.names, state.count);\n        }\n      case RoomNameType.EmptyRoom:\n        if (state.oldName) {\n          return \"Empty room (was \".concat(state.oldName, \")\");\n        } else {\n          return \"Empty room\";\n        }\n    }\n  }\n\n  /**\n   * This is an internal method. Calculates the name of the room from the current\n   * room state.\n   * @param userId - The client's user ID. Used to filter room members\n   * correctly.\n   * @param ignoreRoomNameEvent - Return the implicit room name that we'd see if there\n   * was no m.room.name event.\n   * @returns The calculated room name.\n   */\n  calculateRoomName(userId) {\n    var ignoreRoomNameEvent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n    if (!ignoreRoomNameEvent) {\n      var _this$currentState$ge4;\n      var name = (_this$currentState$ge4 = this.currentState.getStateEvents(EventType.RoomName, \"\")) === null || _this$currentState$ge4 === void 0 ? void 0 : _this$currentState$ge4.getContent().name;\n      if (name && typeof name === \"string\") {\n        return this.roomNameGenerator({\n          type: RoomNameType.Actual,\n          name\n        });\n      }\n    }\n    var alias = this.getCanonicalAlias();\n    if (alias) {\n      return this.roomNameGenerator({\n        type: RoomNameType.Actual,\n        name: alias\n      });\n    }\n    var joinedMemberCount = this.currentState.getJoinedMemberCount();\n    var invitedMemberCount = this.currentState.getInvitedMemberCount();\n    // -1 because these numbers include the syncing user\n    var inviteJoinCount = joinedMemberCount + invitedMemberCount - 1;\n\n    // get service members (e.g. helper bots) for exclusion\n    var excludedUserIds = this.getFunctionalMembers();\n\n    // get members from heroes that are NOT ourselves\n    var otherNames = [];\n    if (this.heroes) {\n      // if we have heroes, use those as the names\n      this.heroes.forEach(hero => {\n        // filter service members\n        if (excludedUserIds.includes(hero.userId)) {\n          inviteJoinCount--;\n          return;\n        }\n        // If the hero has a display name, use that.\n        // Otherwise, look their user ID up in the membership and use\n        // the name from there, or the user ID as a last resort.\n        if (hero.displayName) {\n          otherNames.push(hero.displayName);\n        } else {\n          var member = this.getMember(hero.userId);\n          otherNames.push(member ? member.name : hero.userId);\n        }\n      });\n    } else {\n      var otherMembers = this.currentState.getMembers().filter(m => {\n        return m.userId !== userId && (m.membership === KnownMembership.Invite || m.membership === KnownMembership.Join);\n      });\n      otherMembers = otherMembers.filter(_ref6 => {\n        var {\n          userId\n        } = _ref6;\n        // filter service members\n        if (excludedUserIds.includes(userId)) {\n          inviteJoinCount--;\n          return false;\n        }\n        return true;\n      });\n      // make sure members have stable order\n      var collator = new Intl.Collator();\n      otherMembers.sort((a, b) => collator.compare(a.userId, b.userId));\n      // only 5 first members, immitate summaryHeroes\n      otherMembers = otherMembers.slice(0, 5);\n      otherNames = otherMembers.map(m => m.name);\n    }\n    if (inviteJoinCount) {\n      return this.roomNameGenerator({\n        type: RoomNameType.Generated,\n        names: otherNames,\n        count: inviteJoinCount\n      });\n    }\n    var myMembership = this.getMyMembership();\n    // if I have created a room and invited people through\n    // 3rd party invites\n    if (myMembership == KnownMembership.Join) {\n      var thirdPartyInvites = this.currentState.getStateEvents(EventType.RoomThirdPartyInvite);\n      if (thirdPartyInvites !== null && thirdPartyInvites !== void 0 && thirdPartyInvites.length) {\n        var thirdPartyNames = thirdPartyInvites.map(i => {\n          return i.getContent().display_name;\n        });\n        return this.roomNameGenerator({\n          type: RoomNameType.Generated,\n          subtype: \"Inviting\",\n          names: thirdPartyNames,\n          count: thirdPartyNames.length + 1\n        });\n      }\n    }\n\n    // let's try to figure out who was here before\n    var leftNames = otherNames;\n    // if we didn't have heroes, try finding them in the room state\n    if (!leftNames.length) {\n      leftNames = this.currentState.getMembers().filter(m => {\n        return m.userId !== userId && m.membership !== KnownMembership.Invite && m.membership !== KnownMembership.Join;\n      }).map(m => m.name);\n    }\n    var oldName;\n    if (leftNames.length) {\n      oldName = this.roomNameGenerator({\n        type: RoomNameType.Generated,\n        names: leftNames,\n        count: leftNames.length + 1\n      });\n    }\n    return this.roomNameGenerator({\n      type: RoomNameType.EmptyRoom,\n      oldName\n    });\n  }\n\n  /**\n   * When we receive a new visibility change event:\n   *\n   * - store this visibility change alongside the timeline, in case we\n   *   later need to apply it to an event that we haven't received yet;\n   * - if we have already received the event whose visibility has changed,\n   *   patch it to reflect the visibility change and inform listeners.\n   */\n  applyNewVisibilityEvent(event) {\n    var visibilityChange = event.asVisibilityChange();\n    if (!visibilityChange) {\n      // The event is ill-formed.\n      return;\n    }\n\n    // Ignore visibility change events that are not emitted by moderators.\n    var userId = event.getSender();\n    if (!userId) {\n      return;\n    }\n    var isPowerSufficient = EVENT_VISIBILITY_CHANGE_TYPE.name && this.currentState.maySendStateEvent(EVENT_VISIBILITY_CHANGE_TYPE.name, userId) || EVENT_VISIBILITY_CHANGE_TYPE.altName && this.currentState.maySendStateEvent(EVENT_VISIBILITY_CHANGE_TYPE.altName, userId);\n    if (!isPowerSufficient) {\n      // Powerlevel is insufficient.\n      return;\n    }\n\n    // Record this change in visibility.\n    // If the event is not in our timeline and we only receive it later,\n    // we may need to apply the visibility change at a later date.\n\n    var visibilityEventsOnOriginalEvent = this.visibilityEvents.get(visibilityChange.eventId);\n    if (visibilityEventsOnOriginalEvent) {\n      // It would be tempting to simply erase the latest visibility change\n      // but we need to record all of the changes in case the latest change\n      // is ever redacted.\n      //\n      // In practice, linear scans through `visibilityEvents` should be fast.\n      // However, to protect against a potential DoS attack, we limit the\n      // number of iterations in this loop.\n      var index = visibilityEventsOnOriginalEvent.length - 1;\n      var min = Math.max(0, visibilityEventsOnOriginalEvent.length - MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH);\n      for (; index >= min; --index) {\n        var target = visibilityEventsOnOriginalEvent[index];\n        if (target.getTs() < event.getTs()) {\n          break;\n        }\n      }\n      if (index === -1) {\n        visibilityEventsOnOriginalEvent.unshift(event);\n      } else {\n        visibilityEventsOnOriginalEvent.splice(index + 1, 0, event);\n      }\n    } else {\n      this.visibilityEvents.set(visibilityChange.eventId, [event]);\n    }\n\n    // Finally, let's check if the event is already in our timeline.\n    // If so, we need to patch it and inform listeners.\n\n    var originalEvent = this.findEventById(visibilityChange.eventId);\n    if (!originalEvent) {\n      return;\n    }\n    originalEvent.applyVisibilityEvent(visibilityChange);\n  }\n  redactVisibilityChangeEvent(event) {\n    // Sanity checks.\n    if (!event.isVisibilityEvent) {\n      throw new Error(\"expected a visibility change event\");\n    }\n    var relation = event.getRelation();\n    var originalEventId = relation === null || relation === void 0 ? void 0 : relation.event_id;\n    var visibilityEventsOnOriginalEvent = this.visibilityEvents.get(originalEventId);\n    if (!visibilityEventsOnOriginalEvent) {\n      // No visibility changes on the original event.\n      // In particular, this change event was not recorded,\n      // most likely because it was ill-formed.\n      return;\n    }\n    var index = visibilityEventsOnOriginalEvent.findIndex(change => change.getId() === event.getId());\n    if (index === -1) {\n      // This change event was not recorded, most likely because\n      // it was ill-formed.\n      return;\n    }\n    // Remove visibility change.\n    visibilityEventsOnOriginalEvent.splice(index, 1);\n\n    // If we removed the latest visibility change event, propagate changes.\n    if (index === visibilityEventsOnOriginalEvent.length) {\n      var originalEvent = this.findEventById(originalEventId);\n      if (!originalEvent) {\n        return;\n      }\n      if (index === 0) {\n        // We have just removed the only visibility change event.\n        this.visibilityEvents.delete(originalEventId);\n        originalEvent.applyVisibilityEvent();\n      } else {\n        var newEvent = visibilityEventsOnOriginalEvent[visibilityEventsOnOriginalEvent.length - 1];\n        var newVisibility = newEvent.asVisibilityChange();\n        if (!newVisibility) {\n          // Event is ill-formed.\n          // This breaks our invariant.\n          throw new Error(\"at this stage, visibility changes should be well-formed\");\n        }\n        originalEvent.applyVisibilityEvent(newVisibility);\n      }\n    }\n  }\n\n  /**\n   * When we receive an event whose visibility has been altered by\n   * a (more recent) visibility change event, patch the event in\n   * place so that clients now not to display it.\n   *\n   * @param event - Any matrix event. If this event has at least one a\n   * pending visibility change event, apply the latest visibility\n   * change event.\n   */\n  applyPendingVisibilityEvents(event) {\n    var visibilityEvents = this.visibilityEvents.get(event.getId());\n    if (!visibilityEvents || visibilityEvents.length == 0) {\n      // No pending visibility change in store.\n      return;\n    }\n    var visibilityEvent = visibilityEvents[visibilityEvents.length - 1];\n    var visibilityChange = visibilityEvent.asVisibilityChange();\n    if (!visibilityChange) {\n      return;\n    }\n    if (visibilityChange.visible) {\n      // Events are visible by default, no need to apply a visibility change.\n      // Note that we need to keep the visibility changes in `visibilityEvents`,\n      // in case we later fetch an older visibility change event that is superseded\n      // by `visibilityChange`.\n    }\n    if (visibilityEvent.getTs() < event.getTs()) {\n      // Something is wrong, the visibility change cannot happen before the\n      // event. Presumably an ill-formed event.\n      return;\n    }\n    event.applyVisibilityEvent(visibilityChange);\n  }\n\n  /**\n   * Find when a client has gained thread capabilities by inspecting the oldest\n   * threaded receipt\n   * @returns the timestamp of the oldest threaded receipt\n   */\n  getOldestThreadedReceiptTs() {\n    return this.oldestThreadedReceiptTs;\n  }\n\n  /**\n   * Determines if the given user has read a particular event ID with the known\n   * history of the room. This is not a definitive check as it relies only on\n   * what is available to the room at the time of execution.\n   *\n   * @param userId - The user ID to check the read state of.\n   * @param eventId - The event ID to check if the user read.\n   * @returns true if the user has read the event, false otherwise.\n   */\n  hasUserReadEvent(userId, eventId) {\n    return this.roomReceipts.hasUserReadEvent(userId, eventId);\n  }\n\n  /**\n   * Returns the most recent unthreaded receipt for a given user\n   * @param userId - the MxID of the User\n   * @returns an unthreaded Receipt. Can be undefined if receipts have been disabled\n   * or a user chooses to use private read receipts (or we have simply not received\n   * a receipt from this user yet).\n   */\n  getLastUnthreadedReceiptFor(userId) {\n    return this.unthreadedReceipts.get(userId);\n  }\n\n  /**\n   * This issue should also be addressed on synapse's side and is tracked as part\n   * of https://github.com/matrix-org/synapse/issues/14837\n   *\n   *\n   * We consider a room  fully read if the current user has sent\n   * the last event in the live timeline of that context and if the read receipt\n   * we have on record matches.\n   * This also detects all unread threads and applies the same logic to those\n   * contexts\n   */\n  fixupNotifications(userId) {\n    super.fixupNotifications(userId);\n    var unreadThreads = this.getThreads().filter(thread => this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total) > 0);\n    for (var thread of unreadThreads) {\n      thread.fixupNotifications(userId);\n    }\n  }\n\n  /**\n   * Determine the order of two events in this room.\n   *\n   * In principle this should use the same order as the server, but in practice\n   * this is difficult for events that were not received over the Sync API. See\n   * MSC4033 for details.\n   *\n   * This implementation leans on the order of events within their timelines, and\n   * falls back to comparing event timestamps when they are in different\n   * timelines.\n   *\n   * See https://github.com/matrix-org/matrix-js-sdk/issues/3325 for where we are\n   * tracking the work to fix this.\n   *\n   * @param leftEventId - the id of the first event\n   * @param rightEventId - the id of the second event\n    * @returns -1 if left \\< right, 1 if left \\> right, 0 if left == right, null if\n   *          we can't tell (because we can't find the events).\n   */\n  compareEventOrdering(leftEventId, rightEventId) {\n    return compareEventOrdering(this, leftEventId, rightEventId);\n  }\n\n  /**\n   * Return true if this room has an `m.room.encryption` state event.\n   *\n   * If this returns `true`, events sent to this room should be encrypted (and `MatrixClient.sendEvent` and friends\n   * will encrypt outgoing events).\n   */\n  hasEncryptionStateEvent() {\n    var _this$getLiveTimeline;\n    return Boolean((_this$getLiveTimeline = this.getLiveTimeline().getState(EventTimeline.FORWARDS)) === null || _this$getLiveTimeline === void 0 ? void 0 : _this$getLiveTimeline.getStateEvents(EventType.RoomEncryption, \"\"));\n  }\n}\n\n// a map from current event status to a list of allowed next statuses\nvar ALLOWED_TRANSITIONS = {\n  [EventStatus.ENCRYPTING]: [EventStatus.SENDING, EventStatus.NOT_SENT, EventStatus.CANCELLED],\n  [EventStatus.SENDING]: [EventStatus.ENCRYPTING, EventStatus.QUEUED, EventStatus.NOT_SENT, EventStatus.SENT],\n  [EventStatus.QUEUED]: [EventStatus.SENDING, EventStatus.NOT_SENT, EventStatus.CANCELLED],\n  [EventStatus.SENT]: [],\n  [EventStatus.NOT_SENT]: [EventStatus.SENDING, EventStatus.QUEUED, EventStatus.CANCELLED],\n  [EventStatus.CANCELLED]: []\n};\nexport var RoomNameType = /*#__PURE__*/function (RoomNameType) {\n  RoomNameType[RoomNameType[\"EmptyRoom\"] = 0] = \"EmptyRoom\";\n  RoomNameType[RoomNameType[\"Generated\"] = 1] = \"Generated\";\n  RoomNameType[RoomNameType[\"Actual\"] = 2] = \"Actual\";\n  return RoomNameType;\n}({});\n// Can be overriden by IMatrixClientCreateOpts::memberNamesToRoomNameFn\nfunction memberNamesToRoomName(names, count) {\n  var countWithoutMe = count - 1;\n  if (!names.length) {\n    return \"Empty room\";\n  } else if (names.length === 1 && countWithoutMe <= 1) {\n    return names[0];\n  } else if (names.length === 2 && countWithoutMe <= 2) {\n    return \"\".concat(names[0], \" and \").concat(names[1]);\n  } else {\n    var plural = countWithoutMe > 1;\n    if (plural) {\n      return \"\".concat(names[0], \" and \").concat(countWithoutMe, \" others\");\n    } else {\n      return \"\".concat(names[0], \" and 1 other\");\n    }\n  }\n}\n//# sourceMappingURL=room.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport var ServerSupport = /*#__PURE__*/function (ServerSupport) {\n  ServerSupport[ServerSupport[\"Stable\"] = 0] = \"Stable\";\n  ServerSupport[ServerSupport[\"Unstable\"] = 1] = \"Unstable\";\n  ServerSupport[ServerSupport[\"Unsupported\"] = 2] = \"Unsupported\";\n  return ServerSupport;\n}({});\nexport var Feature = /*#__PURE__*/function (Feature) {\n  Feature[\"Thread\"] = \"Thread\";\n  Feature[\"ThreadUnreadNotifications\"] = \"ThreadUnreadNotifications\";\n  /**\n   * @deprecated this is now exposed as a capability not a feature\n   */\n  Feature[\"LoginTokenRequest\"] = \"LoginTokenRequest\";\n  Feature[\"RelationBasedRedactions\"] = \"RelationBasedRedactions\";\n  Feature[\"AccountDataDeletion\"] = \"AccountDataDeletion\";\n  Feature[\"RelationsRecursion\"] = \"RelationsRecursion\";\n  Feature[\"IntentionalMentions\"] = \"IntentionalMentions\";\n  return Feature;\n}({});\nvar featureSupportResolver = {\n  [Feature.Thread]: {\n    unstablePrefixes: [\"org.matrix.msc3440\"],\n    matrixVersion: \"v1.3\"\n  },\n  [Feature.ThreadUnreadNotifications]: {\n    unstablePrefixes: [\"org.matrix.msc3771\", \"org.matrix.msc3773\"],\n    matrixVersion: \"v1.4\"\n  },\n  [Feature.LoginTokenRequest]: {\n    unstablePrefixes: [\"org.matrix.msc3882\"]\n  },\n  [Feature.RelationBasedRedactions]: {\n    unstablePrefixes: [\"org.matrix.msc3912\"]\n  },\n  [Feature.AccountDataDeletion]: {\n    unstablePrefixes: [\"org.matrix.msc3391\"]\n  },\n  [Feature.RelationsRecursion]: {\n    unstablePrefixes: [\"org.matrix.msc3981\"],\n    matrixVersion: \"v1.10\"\n  },\n  [Feature.IntentionalMentions]: {\n    unstablePrefixes: [\"org.matrix.msc3952_intentional_mentions\"],\n    matrixVersion: \"v1.7\"\n  }\n};\nexport function buildFeatureSupportMap(_x) {\n  return _buildFeatureSupportMap.apply(this, arguments);\n}\nfunction _buildFeatureSupportMap() {\n  _buildFeatureSupportMap = _asyncToGenerator(function* (versions) {\n    var supportMap = new Map();\n    for (var [feature, supportCondition] of Object.entries(featureSupportResolver)) {\n      var _versions$versions$in, _versions$versions, _supportCondition$uns, _supportCondition$uns2;\n      var supportMatrixVersion = (_versions$versions$in = (_versions$versions = versions.versions) === null || _versions$versions === void 0 ? void 0 : _versions$versions.includes(supportCondition.matrixVersion || \"\")) !== null && _versions$versions$in !== void 0 ? _versions$versions$in : false;\n      var supportUnstablePrefixes = (_supportCondition$uns = (_supportCondition$uns2 = supportCondition.unstablePrefixes) === null || _supportCondition$uns2 === void 0 ? void 0 : _supportCondition$uns2.every(unstablePrefix => {\n        var _versions$unstable_fe;\n        return ((_versions$unstable_fe = versions.unstable_features) === null || _versions$unstable_fe === void 0 ? void 0 : _versions$unstable_fe[unstablePrefix]) === true;\n      })) !== null && _supportCondition$uns !== void 0 ? _supportCondition$uns : false;\n      if (supportMatrixVersion) {\n        supportMap.set(feature, ServerSupport.Stable);\n      } else if (supportUnstablePrefixes) {\n        supportMap.set(feature, ServerSupport.Unstable);\n      } else {\n        supportMap.set(feature, ServerSupport.Unsupported);\n      }\n    }\n    return supportMap;\n  });\n  return _buildFeatureSupportMap.apply(this, arguments);\n}\n//# sourceMappingURL=feature.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2015 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\n * TODO:\n * This class mainly serves to take all the syncing logic out of client.js and\n * into a separate file. It's all very fluid, and this class gut wrenches a lot\n * of MatrixClient props (e.g. http). Given we want to support WebSockets as\n * an alternative syncing API, we may want to have a proper syncing interface\n * for HTTP and WS at some point.\n */\n\nimport { User } from \"./models/user.js\";\nimport { NotificationCountType, Room, RoomEvent } from \"./models/room.js\";\nimport { deepCopy, noUnsafeEventProps, unsafeProp } from \"./utils.js\";\nimport { Filter } from \"./filter.js\";\nimport { EventTimeline } from \"./models/event-timeline.js\";\nimport { ClientEvent, PendingEventOrdering } from \"./client.js\";\nimport { MatrixEvent } from \"./models/event.js\";\nimport { Method } from \"./http-api/index.js\";\nimport { EventType } from \"./@types/event.js\";\nimport { RoomStateEvent } from \"./models/room-state.js\";\nimport { RoomMemberEvent } from \"./models/room-member.js\";\nimport { BeaconEvent } from \"./models/beacon.js\";\nimport { UNREAD_THREAD_NOTIFICATIONS } from \"./@types/sync.js\";\nimport { Feature, ServerSupport } from \"./feature.js\";\nimport { KnownMembership } from \"./@types/membership.js\";\n\n// /sync requests allow you to set a timeout= but the request may continue\n// beyond that and wedge forever, so we need to track how long we are willing\n// to keep open the connection. This constant is *ADDED* to the timeout= value\n// to determine the max time we're willing to wait.\nvar BUFFER_PERIOD_MS = 80 * 1000;\n\n// Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed\n// to RECONNECTING. This is needed to inform the client of server issues when the\n// keepAlive is successful but the server /sync fails.\nvar FAILED_SYNC_ERROR_THRESHOLD = 3;\nexport var SyncState = /*#__PURE__*/function (SyncState) {\n  /** Emitted after we try to sync more than `FAILED_SYNC_ERROR_THRESHOLD`\n   * times and are still failing. Or when we enounter a hard error like the\n   * token being invalid. */\n  SyncState[\"Error\"] = \"ERROR\";\n  /** Emitted after the first sync events are ready (this could even be sync\n   * events from the cache) */\n  SyncState[\"Prepared\"] = \"PREPARED\";\n  /** Emitted when the sync loop is no longer running */\n  SyncState[\"Stopped\"] = \"STOPPED\";\n  /** Emitted after each sync request happens */\n  SyncState[\"Syncing\"] = \"SYNCING\";\n  /** Emitted after a connectivity error and we're ready to start syncing again */\n  SyncState[\"Catchup\"] = \"CATCHUP\";\n  /** Emitted for each time we try reconnecting. Will switch to `Error` after\n   * we reach the `FAILED_SYNC_ERROR_THRESHOLD`\n   */\n  SyncState[\"Reconnecting\"] = \"RECONNECTING\";\n  return SyncState;\n}({});\n\n// Room versions where \"insertion\", \"batch\", and \"marker\" events are controlled\n// by power-levels. MSC2716 is supported in existing room versions but they\n// should only have special meaning when the room creator sends them.\nvar MSC2716_ROOM_VERSIONS = [\"org.matrix.msc2716v3\"];\nfunction getFilterName(userId, suffix) {\n  // scope this on the user ID because people may login on many accounts\n  // and they all need to be stored!\n  return \"FILTER_SYNC_\".concat(userId) + (suffix ? \"_\" + suffix : \"\");\n}\n\n/**\n * Options passed into the constructor of SyncApi by MatrixClient\n */\n\nexport var SetPresence = /*#__PURE__*/function (SetPresence) {\n  SetPresence[\"Offline\"] = \"offline\";\n  SetPresence[\"Online\"] = \"online\";\n  SetPresence[\"Unavailable\"] = \"unavailable\";\n  return SetPresence;\n}({});\n/** add default settings to an IStoredClientOpts */\nexport function defaultClientOpts(opts) {\n  return _objectSpread({\n    initialSyncLimit: 8,\n    resolveInvitesToProfiles: false,\n    pollTimeout: 30 * 1000,\n    pendingEventOrdering: PendingEventOrdering.Chronological,\n    threadSupport: false\n  }, opts);\n}\nexport function defaultSyncApiOpts(syncOpts) {\n  return _objectSpread({\n    canResetEntireTimeline: _roomId => false\n  }, syncOpts);\n}\nexport class SyncApi {\n  /**\n   * Construct an entity which is able to sync with a homeserver.\n   * @param client - The matrix client instance to use.\n   * @param opts - client config options\n   * @param syncOpts - sync-specific options passed by the client\n   * @internal\n   */\n  constructor(client, opts, syncOpts) {\n    var _this = this;\n    this.client = client;\n    _defineProperty(this, \"opts\", void 0);\n    _defineProperty(this, \"syncOpts\", void 0);\n    _defineProperty(this, \"_peekRoom\", null);\n    _defineProperty(this, \"currentSyncRequest\", void 0);\n    _defineProperty(this, \"abortController\", void 0);\n    _defineProperty(this, \"syncState\", null);\n    _defineProperty(this, \"syncStateData\", void 0);\n    // additional data (eg. error object for failed sync)\n    _defineProperty(this, \"catchingUp\", false);\n    _defineProperty(this, \"running\", false);\n    _defineProperty(this, \"keepAliveTimer\", void 0);\n    _defineProperty(this, \"connectionReturnedResolvers\", void 0);\n    _defineProperty(this, \"notifEvents\", []);\n    // accumulator of sync events in the current sync response\n    _defineProperty(this, \"failedSyncCount\", 0);\n    // Number of consecutive failed /sync requests\n    _defineProperty(this, \"storeIsInvalid\", false);\n    // flag set if the store needs to be cleared before we can start\n    _defineProperty(this, \"presence\", void 0);\n    _defineProperty(this, \"getPushRules\", /*#__PURE__*/_asyncToGenerator(function* () {\n      try {\n        _this.syncOpts.logger.debug(\"Getting push rules...\");\n        var result = yield _this.client.getPushRules();\n        _this.syncOpts.logger.debug(\"Got push rules\");\n        _this.client.pushRules = result;\n      } catch (err) {\n        _this.syncOpts.logger.error(\"Getting push rules failed\", err);\n        if (_this.shouldAbortSync(err)) return;\n        // wait for saved sync to complete before doing anything else,\n        // otherwise the sync state will end up being incorrect\n        _this.syncOpts.logger.debug(\"Waiting for saved sync before retrying push rules...\");\n        yield _this.recoverFromSyncStartupError(_this.savedSyncPromise, err);\n        return _this.getPushRules(); // try again\n      }\n    }));\n    _defineProperty(this, \"buildDefaultFilter\", () => {\n      var filter = new Filter(this.client.credentials.userId);\n      if (this.client.canSupport.get(Feature.ThreadUnreadNotifications) !== ServerSupport.Unsupported) {\n        filter.setUnreadThreadNotifications(true);\n      }\n      return filter;\n    });\n    _defineProperty(this, \"prepareLazyLoadingForSync\", /*#__PURE__*/_asyncToGenerator(function* () {\n      _this.syncOpts.logger.debug(\"Prepare lazy loading for sync...\");\n      if (_this.client.isGuest()) {\n        _this.opts.lazyLoadMembers = false;\n      }\n      if (_this.opts.lazyLoadMembers) {\n        _this.syncOpts.logger.debug(\"Enabling lazy load on sync filter...\");\n        if (!_this.opts.filter) {\n          _this.opts.filter = _this.buildDefaultFilter();\n        }\n        _this.opts.filter.setLazyLoadMembers(true);\n      }\n    }));\n    _defineProperty(this, \"storeClientOptions\", /*#__PURE__*/_asyncToGenerator(function* () {\n      try {\n        _this.syncOpts.logger.debug(\"Storing client options...\");\n        yield _this.client.storeClientOptions();\n        _this.syncOpts.logger.debug(\"Stored client options\");\n      } catch (err) {\n        _this.syncOpts.logger.error(\"Storing client options failed\", err);\n        throw err;\n      }\n    }));\n    _defineProperty(this, \"getFilter\", /*#__PURE__*/_asyncToGenerator(function* () {\n      _this.syncOpts.logger.debug(\"Getting filter...\");\n      var filter;\n      if (_this.opts.filter) {\n        filter = _this.opts.filter;\n      } else {\n        filter = _this.buildDefaultFilter();\n      }\n      var filterId;\n      try {\n        filterId = yield _this.client.getOrCreateFilter(getFilterName(_this.client.credentials.userId), filter);\n      } catch (err) {\n        _this.syncOpts.logger.error(\"Getting filter failed\", err);\n        if (_this.shouldAbortSync(err)) return {};\n        // wait for saved sync to complete before doing anything else,\n        // otherwise the sync state will end up being incorrect\n        _this.syncOpts.logger.debug(\"Waiting for saved sync before retrying filter...\");\n        yield _this.recoverFromSyncStartupError(_this.savedSyncPromise, err);\n        return _this.getFilter(); // try again\n      }\n      return {\n        filter,\n        filterId\n      };\n    }));\n    _defineProperty(this, \"savedSyncPromise\", void 0);\n    /**\n     * Event handler for the 'online' event\n     * This event is generally unreliable and precise behaviour\n     * varies between browsers, so we poll for connectivity too,\n     * but this might help us reconnect a little faster.\n     */\n    _defineProperty(this, \"onOnline\", () => {\n      this.syncOpts.logger.debug(\"Browser thinks we are back online\");\n      this.startKeepAlives(0);\n    });\n    this.opts = defaultClientOpts(opts);\n    this.syncOpts = defaultSyncApiOpts(syncOpts);\n    if (client.getNotifTimelineSet()) {\n      client.reEmitter.reEmit(client.getNotifTimelineSet(), [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n    }\n  }\n  createRoom(roomId) {\n    var room = _createAndReEmitRoom(this.client, roomId, this.opts);\n    room.on(RoomStateEvent.Marker, (markerEvent, markerFoundOptions) => {\n      this.onMarkerStateEvent(room, markerEvent, markerFoundOptions);\n    });\n    return room;\n  }\n\n  /** When we see the marker state change in the room, we know there is some\n   * new historical messages imported by MSC2716 `/batch_send` somewhere in\n   * the room and we need to throw away the timeline to make sure the\n   * historical messages are shown when we paginate `/messages` again.\n   * @param room - The room where the marker event was sent\n   * @param markerEvent - The new marker event\n   * @param setStateOptions - When `timelineWasEmpty` is set\n   * as `true`, the given marker event will be ignored\n   */\n  onMarkerStateEvent(room, markerEvent) {\n    var {\n      timelineWasEmpty\n    } = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n    // We don't need to refresh the timeline if it was empty before the\n    // marker arrived. This could be happen in a variety of cases:\n    //  1. From the initial sync\n    //  2. If it's from the first state we're seeing after joining the room\n    //  3. Or whether it's coming from `syncFromCache`\n    if (timelineWasEmpty) {\n      this.syncOpts.logger.debug(\"MarkerState: Ignoring markerEventId=\".concat(markerEvent.getId(), \" in roomId=\").concat(room.roomId, \" \") + \"because the timeline was empty before the marker arrived which means there is nothing to refresh.\");\n      return;\n    }\n    var isValidMsc2716Event =\n    // Check whether the room version directly supports MSC2716, in\n    // which case, \"marker\" events are already auth'ed by\n    // power_levels\n    MSC2716_ROOM_VERSIONS.includes(room.getVersion()) ||\n    // MSC2716 is also supported in all existing room versions but\n    // special meaning should only be given to \"insertion\", \"batch\",\n    // and \"marker\" events when they come from the room creator\n    markerEvent.getSender() === room.getCreator();\n\n    // It would be nice if we could also specifically tell whether the\n    // historical messages actually affected the locally cached client\n    // timeline or not. The problem is we can't see the prev_events of\n    // the base insertion event that the marker was pointing to because\n    // prev_events aren't available in the client API's. In most cases,\n    // the history won't be in people's locally cached timelines in the\n    // client, so we don't need to bother everyone about refreshing\n    // their timeline. This works for a v1 though and there are use\n    // cases like initially bootstrapping your bridged room where people\n    // are likely to encounter the historical messages affecting their\n    // current timeline (think someone signing up for Beeper and\n    // importing their Whatsapp history).\n    if (isValidMsc2716Event) {\n      // Saw new marker event, let's let the clients know they should\n      // refresh the timeline.\n      this.syncOpts.logger.debug(\"MarkerState: Timeline needs to be refreshed because \" + \"a new markerEventId=\".concat(markerEvent.getId(), \" was sent in roomId=\").concat(room.roomId));\n      room.setTimelineNeedsRefresh(true);\n      room.emit(RoomEvent.HistoryImportedWithinTimeline, markerEvent, room);\n    } else {\n      this.syncOpts.logger.debug(\"MarkerState: Ignoring markerEventId=\".concat(markerEvent.getId(), \" in roomId=\").concat(room.roomId, \" because \") + \"MSC2716 is not supported in the room version or for any room version, the marker wasn't sent \" + \"by the room creator.\");\n    }\n  }\n\n  /**\n   * Sync rooms the user has left.\n   * @returns Resolved when they've been added to the store.\n   */\n  syncLeftRooms() {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      var _data$rooms;\n      var client = _this2.client;\n\n      // grab a filter with limit=1 and include_leave=true\n      var filter = new Filter(_this2.client.credentials.userId);\n      filter.setTimelineLimit(1);\n      filter.setIncludeLeaveRooms(true);\n      var localTimeoutMs = _this2.opts.pollTimeout + BUFFER_PERIOD_MS;\n      var filterId = yield client.getOrCreateFilter(getFilterName(client.credentials.userId, \"LEFT_ROOMS\"), filter);\n      var qps = {\n        \"timeout\": 0,\n        // don't want to block since this is a single isolated req\n        \"filter\": filterId,\n        \"org.matrix.msc4222.use_state_after\": true\n      };\n      var data = yield client.http.authedRequest(Method.Get, \"/sync\", qps, undefined, {\n        localTimeoutMs\n      });\n      var leaveRooms = [];\n      if ((_data$rooms = data.rooms) !== null && _data$rooms !== void 0 && _data$rooms.leave) {\n        leaveRooms = _this2.mapSyncResponseToRoomArray(data.rooms.leave);\n      }\n      var rooms = yield Promise.all(leaveRooms.map(/*#__PURE__*/function () {\n        var _ref5 = _asyncToGenerator(function* (leaveObj) {\n          var room = leaveObj.room;\n          if (!leaveObj.isBrandNewRoom) {\n            // the intention behind syncLeftRooms is to add in rooms which were\n            // *omitted* from the initial /sync. Rooms the user were joined to\n            // but then left whilst the app is running will appear in this list\n            // and we do not want to bother with them since they will have the\n            // current state already (and may get dupe messages if we add\n            // yet more timeline events!), so skip them.\n            // NB: When we persist rooms to localStorage this will be more\n            //     complicated...\n            return;\n          }\n          leaveObj.timeline = leaveObj.timeline || {\n            prev_batch: null,\n            events: []\n          };\n\n          // set the back-pagination token. Do this *before* adding any\n          // events so that clients can start back-paginating.\n          room.getLiveTimeline().setPaginationToken(leaveObj.timeline.prev_batch, EventTimeline.BACKWARDS);\n          var {\n            timelineEvents\n          } = yield _this2.mapAndInjectRoomEvents(leaveObj);\n          room.recalculate();\n          client.store.storeRoom(room);\n          client.emit(ClientEvent.Room, room);\n          _this2.processEventsForNotifs(room, timelineEvents);\n          return room;\n        });\n        return function (_x) {\n          return _ref5.apply(this, arguments);\n        };\n      }()));\n      return rooms.filter(Boolean);\n    })();\n  }\n\n  /**\n   * Peek into a room. This will result in the room in question being synced so it\n   * is accessible via getRooms(). Live updates for the room will be provided.\n   * @param roomId - The room ID to peek into.\n   * @param limit - The number of timeline events to initially retrieve.\n   * @returns A promise which resolves once the room has been added to the\n   * store.\n   */\n  peek(roomId) {\n    var _this$_peekRoom;\n    var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 20;\n    if (((_this$_peekRoom = this._peekRoom) === null || _this$_peekRoom === void 0 ? void 0 : _this$_peekRoom.roomId) === roomId) {\n      return Promise.resolve(this._peekRoom);\n    }\n    var client = this.client;\n    this._peekRoom = this.createRoom(roomId);\n    return this.client.roomInitialSync(roomId, limit).then(response => {\n      var _this$_peekRoom2;\n      if (((_this$_peekRoom2 = this._peekRoom) === null || _this$_peekRoom2 === void 0 ? void 0 : _this$_peekRoom2.roomId) !== roomId) {\n        throw new Error(\"Peeking aborted\");\n      }\n\n      // make sure things are init'd\n      response.messages = response.messages || {\n        chunk: []\n      };\n      response.messages.chunk = response.messages.chunk || [];\n      response.state = response.state || [];\n\n      // FIXME: Mostly duplicated from injectRoomEvents but not entirely\n      // because \"state\" in this API is at the BEGINNING of the chunk\n      var oldStateEvents = deepCopy(response.state).map(client.getEventMapper());\n      var stateEvents = response.state.map(client.getEventMapper());\n      var messages = response.messages.chunk.map(client.getEventMapper());\n\n      // XXX: copypasted from /sync until we kill off this minging v1 API stuff)\n      // handle presence events (User objects)\n      if (Array.isArray(response.presence)) {\n        response.presence.map(client.getEventMapper()).forEach(function (presenceEvent) {\n          var user = client.store.getUser(presenceEvent.getContent().user_id);\n          if (user) {\n            user.setPresenceEvent(presenceEvent);\n          } else {\n            user = User.createUser(presenceEvent.getContent().user_id, client);\n            user.setPresenceEvent(presenceEvent);\n            client.store.storeUser(user);\n          }\n          client.emit(ClientEvent.Event, presenceEvent);\n        });\n      }\n\n      // set the pagination token before adding the events in case people\n      // fire off pagination requests in response to the Room.timeline\n      // events.\n      if (response.messages.start) {\n        this._peekRoom.oldState.paginationToken = response.messages.start;\n      }\n\n      // set the state of the room to as it was after the timeline executes\n      this._peekRoom.oldState.setStateEvents(oldStateEvents);\n      this._peekRoom.currentState.setStateEvents(stateEvents);\n      this.resolveInvites(this._peekRoom);\n      this._peekRoom.recalculate();\n\n      // roll backwards to diverge old state. addEventsToTimeline\n      // will overwrite the pagination token, so make sure it overwrites\n      // it with the right thing.\n      this._peekRoom.addEventsToTimeline(messages.reverse(), true, true, this._peekRoom.getLiveTimeline(), response.messages.start);\n      client.store.storeRoom(this._peekRoom);\n      client.emit(ClientEvent.Room, this._peekRoom);\n      this.peekPoll(this._peekRoom);\n      return this._peekRoom;\n    });\n  }\n\n  /**\n   * Stop polling for updates in the peeked room. NOPs if there is no room being\n   * peeked.\n   */\n  stopPeeking() {\n    this._peekRoom = null;\n  }\n\n  /**\n   * Do a peek room poll.\n   * @param token - from= token\n   */\n  peekPoll(peekRoom, token) {\n    var _this$abortController,\n      _this3 = this;\n    if (this._peekRoom !== peekRoom) {\n      this.syncOpts.logger.debug(\"Stopped peeking in room %s\", peekRoom.roomId);\n      return;\n    }\n\n    // FIXME: gut wrenching; hard-coded timeout values\n    this.client.http.authedRequest(Method.Get, \"/events\", {\n      room_id: peekRoom.roomId,\n      timeout: String(30 * 1000),\n      from: token\n    }, undefined, {\n      localTimeoutMs: 50 * 1000,\n      abortSignal: (_this$abortController = this.abortController) === null || _this$abortController === void 0 ? void 0 : _this$abortController.signal\n    }).then(/*#__PURE__*/function () {\n      var _ref6 = _asyncToGenerator(function* (res) {\n        if (_this3._peekRoom !== peekRoom) {\n          _this3.syncOpts.logger.debug(\"Stopped peeking in room %s\", peekRoom.roomId);\n          return;\n        }\n        // We have a problem that we get presence both from /events and /sync\n        // however, /sync only returns presence for users in rooms\n        // you're actually joined to.\n        // in order to be sure to get presence for all of the users in the\n        // peeked room, we handle presence explicitly here. This may result\n        // in duplicate presence events firing for some users, which is a\n        // performance drain, but such is life.\n        // XXX: copypasted from /sync until we can kill this minging v1 stuff.\n\n        res.chunk.filter(function (e) {\n          return e.type === \"m.presence\";\n        }).map(_this3.client.getEventMapper()).forEach(presenceEvent => {\n          var user = _this3.client.store.getUser(presenceEvent.getContent().user_id);\n          if (user) {\n            user.setPresenceEvent(presenceEvent);\n          } else {\n            user = User.createUser(presenceEvent.getContent().user_id, _this3.client);\n            user.setPresenceEvent(presenceEvent);\n            _this3.client.store.storeUser(user);\n          }\n          _this3.client.emit(ClientEvent.Event, presenceEvent);\n        });\n\n        // strip out events which aren't for the given room_id (e.g presence)\n        // and also ephemeral events (which we're assuming is anything without\n        // and event ID because the /events API doesn't separate them).\n        var events = res.chunk.filter(function (e) {\n          return e.room_id === peekRoom.roomId && e.event_id;\n        }).map(_this3.client.getEventMapper());\n        yield peekRoom.addLiveEvents(events, {\n          addToState: true\n        });\n        _this3.peekPoll(peekRoom, res.end);\n      });\n      return function (_x2) {\n        return _ref6.apply(this, arguments);\n      };\n    }(), err => {\n      this.syncOpts.logger.error(\"[%s] Peek poll failed: %s\", peekRoom.roomId, err);\n      setTimeout(() => {\n        this.peekPoll(peekRoom, token);\n      }, 30 * 1000);\n    });\n  }\n\n  /**\n   * Returns the current state of this sync object\n   * @see MatrixClient#event:\"sync\"\n   */\n  getSyncState() {\n    return this.syncState;\n  }\n\n  /**\n   * Returns the additional data object associated with\n   * the current sync state, or null if there is no\n   * such data.\n   * Sync errors, if available, are put in the 'error' key of\n   * this object.\n   */\n  getSyncStateData() {\n    var _this$syncStateData;\n    return (_this$syncStateData = this.syncStateData) !== null && _this$syncStateData !== void 0 ? _this$syncStateData : null;\n  }\n  recoverFromSyncStartupError(savedSyncPromise, error) {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      // Wait for the saved sync to complete - we send the pushrules and filter requests\n      // before the saved sync has finished so they can run in parallel, but only process\n      // the results after the saved sync is done. Equivalently, we wait for it to finish\n      // before reporting failures from these functions.\n      yield savedSyncPromise;\n      var keepaliveProm = _this4.startKeepAlives();\n      _this4.updateSyncState(SyncState.Error, {\n        error\n      });\n      yield keepaliveProm;\n    })();\n  }\n  shouldAbortSync(error) {\n    if (error.errcode === \"M_UNKNOWN_TOKEN\") {\n      // The logout already happened, we just need to stop.\n      this.syncOpts.logger.warn(\"Token no longer valid - assuming logout\");\n      this.stop();\n      this.updateSyncState(SyncState.Error, {\n        error\n      });\n      return true;\n    }\n    return false;\n  }\n  /**\n   * Main entry point\n   */\n  sync() {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      var _globalThis$window, _globalThis$window$ad;\n      _this5.running = true;\n      _this5.abortController = new AbortController();\n      (_globalThis$window = globalThis.window) === null || _globalThis$window === void 0 || (_globalThis$window$ad = _globalThis$window.addEventListener) === null || _globalThis$window$ad === void 0 || _globalThis$window$ad.call(_globalThis$window, \"online\", _this5.onOnline, false);\n      if (_this5.client.isGuest()) {\n        // no push rules for guests, no access to POST filter for guests.\n        return _this5.doSync({});\n      }\n\n      // Pull the saved sync token out first, before the worker starts sending\n      // all the sync data which could take a while. This will let us send our\n      // first incremental sync request before we've processed our saved data.\n      _this5.syncOpts.logger.debug(\"Getting saved sync token...\");\n      var savedSyncTokenPromise = _this5.client.store.getSavedSyncToken().then(tok => {\n        _this5.syncOpts.logger.debug(\"Got saved sync token\");\n        return tok;\n      });\n      _this5.savedSyncPromise = _this5.client.store.getSavedSync().then(savedSync => {\n        _this5.syncOpts.logger.debug(\"Got reply from saved sync, exists? \".concat(!!savedSync));\n        if (savedSync) {\n          return _this5.syncFromCache(savedSync);\n        }\n      }).catch(err => {\n        _this5.syncOpts.logger.error(\"Getting saved sync failed\", err);\n      });\n\n      // We need to do one-off checks before we can begin the /sync loop.\n      // These are:\n      //   1) We need to get push rules so we can check if events should bing as we get\n      //      them from /sync.\n      //   2) We need to get/create a filter which we can use for /sync.\n      //   3) We need to prepare lazy loading for sync\n      //   4) We need to store the client options\n\n      // Now start the first incremental sync request: this can also\n      // take a while so if we set it going now, we can wait for it\n      // to finish while we process our saved sync data.\n      yield _this5.getPushRules();\n      yield _this5.prepareLazyLoadingForSync();\n      yield _this5.storeClientOptions();\n      var {\n        filterId,\n        filter\n      } = yield _this5.getFilter();\n      if (!filter) return; // bail, getFilter failed\n\n      // reset the notifications timeline to prepare it to paginate from\n      // the current point in time.\n      // The right solution would be to tie /sync pagination tokens into\n      // /notifications API somehow.\n      _this5.client.resetNotifTimelineSet();\n      if (!_this5.currentSyncRequest) {\n        var firstSyncFilter = filterId;\n        var savedSyncToken = yield savedSyncTokenPromise;\n        if (savedSyncToken) {\n          _this5.syncOpts.logger.debug(\"Sending first sync request...\");\n        } else {\n          _this5.syncOpts.logger.debug(\"Sending initial sync request...\");\n          var initialFilter = _this5.buildDefaultFilter();\n          initialFilter.setDefinition(filter.getDefinition());\n          initialFilter.setTimelineLimit(_this5.opts.initialSyncLimit);\n          // Use an inline filter, no point uploading it for a single usage\n          firstSyncFilter = JSON.stringify(initialFilter.getDefinition());\n        }\n\n        // Send this first sync request here so we can then wait for the saved\n        // sync data to finish processing before we process the results of this one.\n        _this5.currentSyncRequest = _this5.doSyncRequest({\n          filter: firstSyncFilter\n        }, savedSyncToken);\n      }\n\n      // Now wait for the saved sync to finish...\n      _this5.syncOpts.logger.debug(\"Waiting for saved sync before starting sync processing...\");\n      yield _this5.savedSyncPromise;\n      // process the first sync request and continue syncing with the normal filterId\n      return _this5.doSync({\n        filter: filterId\n      });\n    })();\n  }\n\n  /**\n   * Stops the sync object from syncing.\n   */\n  stop() {\n    var _globalThis$window2, _globalThis$window2$r, _this$abortController2;\n    this.syncOpts.logger.debug(\"SyncApi.stop\");\n    // It is necessary to check for the existance of\n    // globalThis.window AND globalThis.window.removeEventListener.\n    // Some platforms (e.g. React Native) register globalThis.window,\n    // but do not have globalThis.window.removeEventListener.\n    (_globalThis$window2 = globalThis.window) === null || _globalThis$window2 === void 0 || (_globalThis$window2$r = _globalThis$window2.removeEventListener) === null || _globalThis$window2$r === void 0 || _globalThis$window2$r.call(_globalThis$window2, \"online\", this.onOnline, false);\n    this.running = false;\n    (_this$abortController2 = this.abortController) === null || _this$abortController2 === void 0 || _this$abortController2.abort();\n    if (this.keepAliveTimer) {\n      clearTimeout(this.keepAliveTimer);\n      this.keepAliveTimer = undefined;\n    }\n  }\n\n  /**\n   * Retry a backed off syncing request immediately. This should only be used when\n   * the user <b>explicitly</b> attempts to retry their lost connection.\n   * @returns True if this resulted in a request being retried.\n   */\n  retryImmediately() {\n    if (!this.connectionReturnedResolvers) {\n      return false;\n    }\n    this.startKeepAlives(0);\n    return true;\n  }\n  /**\n   * Process a single set of cached sync data.\n   * @param savedSync - a saved sync that was persisted by a store. This\n   * should have been acquired via client.store.getSavedSync().\n   */\n  syncFromCache(savedSync) {\n    var _this6 = this;\n    return _asyncToGenerator(function* () {\n      _this6.syncOpts.logger.debug(\"sync(): not doing HTTP hit, instead returning stored /sync data\");\n      var nextSyncToken = savedSync.nextBatch;\n\n      // Set sync token for future incremental syncing\n      _this6.client.store.setSyncToken(nextSyncToken);\n\n      // No previous sync, set old token to null\n      var syncEventData = {\n        nextSyncToken,\n        catchingUp: false,\n        fromCache: true\n      };\n      var data = {\n        next_batch: nextSyncToken,\n        rooms: savedSync.roomsData,\n        account_data: {\n          events: savedSync.accountData\n        }\n      };\n      try {\n        yield _this6.processSyncResponse(syncEventData, data);\n      } catch (e) {\n        _this6.syncOpts.logger.error(\"Error processing cached sync\", e);\n      }\n\n      // Don't emit a prepared if we've bailed because the store is invalid:\n      // in this case the client will not be usable until stopped & restarted\n      // so this would be useless and misleading.\n      if (!_this6.storeIsInvalid) {\n        _this6.updateSyncState(SyncState.Prepared, syncEventData);\n      }\n    })();\n  }\n\n  /**\n   * Invoke me to do /sync calls\n   */\n  doSync(syncOptions) {\n    var _this7 = this;\n    return _asyncToGenerator(function* () {\n      while (_this7.running) {\n        var syncToken = _this7.client.store.getSyncToken();\n        var data = void 0;\n        try {\n          if (!_this7.currentSyncRequest) {\n            _this7.currentSyncRequest = _this7.doSyncRequest(syncOptions, syncToken);\n          }\n          data = yield _this7.currentSyncRequest;\n        } catch (e) {\n          var abort = yield _this7.onSyncError(e);\n          if (abort) return;\n          continue;\n        } finally {\n          _this7.currentSyncRequest = undefined;\n        }\n\n        // set the sync token NOW *before* processing the events. We do this so\n        // if something barfs on an event we can skip it rather than constantly\n        // polling with the same token.\n        _this7.client.store.setSyncToken(data.next_batch);\n\n        // Reset after a successful sync\n        _this7.failedSyncCount = 0;\n        var syncEventData = {\n          oldSyncToken: syncToken !== null && syncToken !== void 0 ? syncToken : undefined,\n          nextSyncToken: data.next_batch,\n          catchingUp: _this7.catchingUp\n        };\n        try {\n          yield _this7.processSyncResponse(syncEventData, data);\n        } catch (e) {\n          // log the exception with stack if we have it, else fall back\n          // to the plain description\n          _this7.syncOpts.logger.error(\"Caught /sync error\", e);\n\n          // Emit the exception for client handling\n          _this7.client.emit(ClientEvent.SyncUnexpectedError, e);\n        }\n\n        // Persist after processing as `unsigned` may get mutated\n        // with an `org.matrix.msc4023.thread_id`\n        yield _this7.client.store.setSyncData(data);\n\n        // update this as it may have changed\n        syncEventData.catchingUp = _this7.catchingUp;\n\n        // emit synced events\n        if (!syncOptions.hasSyncedBefore) {\n          _this7.updateSyncState(SyncState.Prepared, syncEventData);\n          syncOptions.hasSyncedBefore = true;\n        }\n\n        // tell the crypto module to do its processing. It may block (to do a\n        // /keys/changes request).\n        if (_this7.syncOpts.cryptoCallbacks) {\n          yield _this7.syncOpts.cryptoCallbacks.onSyncCompleted(syncEventData);\n        }\n\n        // keep emitting SYNCING -> SYNCING for clients who want to do bulk updates\n        _this7.updateSyncState(SyncState.Syncing, syncEventData);\n        if (_this7.client.store.wantsSave()) {\n          // tell databases that everything is now in a consistent state and can be saved.\n          yield _this7.client.store.save();\n        }\n      }\n      if (!_this7.running) {\n        _this7.syncOpts.logger.debug(\"Sync no longer running: exiting.\");\n        if (_this7.connectionReturnedResolvers) {\n          _this7.connectionReturnedResolvers.reject();\n          _this7.connectionReturnedResolvers = undefined;\n        }\n        _this7.updateSyncState(SyncState.Stopped);\n      }\n    })();\n  }\n  doSyncRequest(syncOptions, syncToken) {\n    var _this$abortController3;\n    var qps = this.getSyncParams(syncOptions, syncToken);\n    return this.client.http.authedRequest(Method.Get, \"/sync\", qps, undefined, {\n      localTimeoutMs: qps.timeout + BUFFER_PERIOD_MS,\n      abortSignal: (_this$abortController3 = this.abortController) === null || _this$abortController3 === void 0 ? void 0 : _this$abortController3.signal\n    });\n  }\n  getSyncParams(syncOptions, syncToken) {\n    var timeout = this.opts.pollTimeout;\n    if (this.getSyncState() !== SyncState.Syncing || this.catchingUp) {\n      // unless we are happily syncing already, we want the server to return\n      // as quickly as possible, even if there are no events queued. This\n      // serves two purposes:\n      //\n      // * When the connection dies, we want to know asap when it comes back,\n      //   so that we can hide the error from the user. (We don't want to\n      //   have to wait for an event or a timeout).\n      //\n      // * We want to know if the server has any to_device messages queued up\n      //   for us. We do that by calling it with a zero timeout until it\n      //   doesn't give us any more to_device messages.\n      this.catchingUp = true;\n      timeout = 0;\n    }\n    var filter = syncOptions.filter;\n    if (this.client.isGuest() && !filter) {\n      filter = this.getGuestFilter();\n    }\n    var qps = {\n      filter,\n      timeout,\n      \"org.matrix.msc4222.use_state_after\": true\n    };\n    if (this.opts.disablePresence) {\n      qps.set_presence = SetPresence.Offline;\n    } else if (this.presence !== undefined) {\n      qps.set_presence = this.presence;\n    }\n    if (syncToken) {\n      qps.since = syncToken;\n    } else {\n      // use a cachebuster for initialsyncs, to make sure that\n      // we don't get a stale sync\n      // (https://github.com/vector-im/vector-web/issues/1354)\n      qps._cacheBuster = Date.now();\n    }\n    if ([SyncState.Reconnecting, SyncState.Error].includes(this.getSyncState())) {\n      // we think the connection is dead. If it comes back up, we won't know\n      // about it till /sync returns. If the timeout= is high, this could\n      // be a long time. Set it to 0 when doing retries so we don't have to wait\n      // for an event or a timeout before emiting the SYNCING event.\n      qps.timeout = 0;\n    }\n    return qps;\n  }\n\n  /**\n   * Specify the set_presence value to be used for subsequent calls to the Sync API.\n   * @param presence - the presence to specify to set_presence of sync calls\n   */\n  setPresence(presence) {\n    this.presence = presence;\n  }\n  onSyncError(err) {\n    var _this8 = this;\n    return _asyncToGenerator(function* () {\n      if (!_this8.running) {\n        _this8.syncOpts.logger.debug(\"Sync no longer running: exiting\");\n        if (_this8.connectionReturnedResolvers) {\n          _this8.connectionReturnedResolvers.reject();\n          _this8.connectionReturnedResolvers = undefined;\n        }\n        _this8.updateSyncState(SyncState.Stopped);\n        return true; // abort\n      }\n      _this8.syncOpts.logger.error(\"/sync error %s\", err);\n      if (_this8.shouldAbortSync(err)) {\n        return true; // abort\n      }\n      _this8.failedSyncCount++;\n      _this8.syncOpts.logger.debug(\"Number of consecutive failed sync requests:\", _this8.failedSyncCount);\n      _this8.syncOpts.logger.debug(\"Starting keep-alive\");\n      // Note that we do *not* mark the sync connection as\n      // lost yet: we only do this if a keepalive poke\n      // fails, since long lived HTTP connections will\n      // go away sometimes and we shouldn't treat this as\n      // erroneous. We set the state to 'reconnecting'\n      // instead, so that clients can observe this state\n      // if they wish.\n      var keepAlivePromise = _this8.startKeepAlives();\n      _this8.currentSyncRequest = undefined;\n      // Transition from RECONNECTING to ERROR after a given number of failed syncs\n      _this8.updateSyncState(_this8.failedSyncCount >= FAILED_SYNC_ERROR_THRESHOLD ? SyncState.Error : SyncState.Reconnecting, {\n        error: err\n      });\n      var connDidFail = yield keepAlivePromise;\n\n      // Only emit CATCHUP if we detected a connectivity error: if we didn't,\n      // it's quite likely the sync will fail again for the same reason and we\n      // want to stay in ERROR rather than keep flip-flopping between ERROR\n      // and CATCHUP.\n      if (connDidFail && _this8.getSyncState() === SyncState.Error) {\n        _this8.updateSyncState(SyncState.Catchup, {\n          catchingUp: true\n        });\n      }\n      return false;\n    })();\n  }\n\n  /**\n   * Process data returned from a sync response and propagate it\n   * into the model objects\n   *\n   * @param syncEventData - Object containing sync tokens associated with this sync\n   * @param data - The response from /sync\n   */\n  processSyncResponse(syncEventData, data) {\n    var _this9 = this;\n    return _asyncToGenerator(function* () {\n      var _data$presence, _data$account_data, _this9$syncOpts$crypt, _data$device_unused_f;\n      var client = _this9.client;\n\n      // data looks like:\n      // {\n      //    next_batch: $token,\n      //    presence: { events: [] },\n      //    account_data: { events: [] },\n      //    device_lists: { changed: [\"@user:server\", ... ]},\n      //    to_device: { events: [] },\n      //    device_one_time_keys_count: { signed_curve25519: 42 },\n      //    rooms: {\n      //      invite: {\n      //        $roomid: {\n      //          invite_state: { events: [] }\n      //        }\n      //      },\n      //      join: {\n      //        $roomid: {\n      //          state: { events: [] },\n      //          timeline: { events: [], prev_batch: $token, limited: true },\n      //          ephemeral: { events: [] },\n      //          summary: {\n      //             m.heroes: [ $user_id ],\n      //             m.joined_member_count: $count,\n      //             m.invited_member_count: $count\n      //          },\n      //          account_data: { events: [] },\n      //          unread_notifications: {\n      //              highlight_count: 0,\n      //              notification_count: 0,\n      //          }\n      //          \"org.matrix.msc4222.state_after\": { events: [] },  // only if \"org.matrix.msc4222.use_state_after\" is true\n      //          msc4354_sticky: { events: [] }, // only if \"org.matrix.msc4354.sticky\" is true\n      //        }\n      //      },\n      //      leave: {\n      //        $roomid: {\n      //          state: { events: [] },\n      //          timeline: { events: [], prev_batch: $token }\n      //        }\n      //      }\n      //    }\n      // }\n\n      // TODO-arch:\n      // - Each event we pass through needs to be emitted via 'event', can we\n      //   do this in one place?\n      // - The isBrandNewRoom boilerplate is boilerplatey.\n\n      // handle presence events (User objects)\n      if (Array.isArray((_data$presence = data.presence) === null || _data$presence === void 0 ? void 0 : _data$presence.events)) {\n        data.presence.events.filter(noUnsafeEventProps).map(client.getEventMapper()).forEach(function (presenceEvent) {\n          var user = client.store.getUser(presenceEvent.getSender());\n          if (user) {\n            user.setPresenceEvent(presenceEvent);\n          } else {\n            user = User.createUser(presenceEvent.getSender(), client);\n            user.setPresenceEvent(presenceEvent);\n            client.store.storeUser(user);\n          }\n          client.emit(ClientEvent.Event, presenceEvent);\n        });\n      }\n\n      // handle non-room account_data\n      if (Array.isArray((_data$account_data = data.account_data) === null || _data$account_data === void 0 ? void 0 : _data$account_data.events)) {\n        var events = data.account_data.events.filter(noUnsafeEventProps).map(client.getEventMapper());\n        var prevEventsMap = events.reduce((m, c) => {\n          m[c.getType()] = client.store.getAccountData(c.getType());\n          return m;\n        }, {});\n        client.store.storeAccountDataEvents(events);\n        events.forEach(function (accountDataEvent) {\n          // Honour push rules that come down the sync stream but also\n          // honour push rules that were previously cached. Base rules\n          // will be updated when we receive push rules via getPushRules\n          // (see sync) before syncing over the network.\n          if (accountDataEvent.getType() === EventType.PushRules) {\n            var rules = accountDataEvent.getContent();\n            client.setPushRules(rules);\n          }\n          var prevEvent = prevEventsMap[accountDataEvent.getType()];\n          client.emit(ClientEvent.AccountData, accountDataEvent, prevEvent);\n          return accountDataEvent;\n        });\n      }\n\n      // handle to-device events\n      if (data.to_device && Array.isArray(data.to_device.events) && data.to_device.events.length > 0) {\n        var toDeviceMessages = data.to_device.events.filter(noUnsafeEventProps);\n        var receivedToDeviceMessages;\n        if (_this9.syncOpts.cryptoCallbacks) {\n          receivedToDeviceMessages = yield _this9.syncOpts.cryptoCallbacks.preprocessToDeviceMessages(toDeviceMessages);\n        } else {\n          receivedToDeviceMessages = toDeviceMessages.map(rawEvent => (\n          // Crypto is not enabled, so we just return the events.\n          {\n            message: rawEvent,\n            encryptionInfo: null\n          }));\n        }\n        processToDeviceMessages(receivedToDeviceMessages, client);\n      } else {\n        // no more to-device events: we can stop polling with a short timeout.\n        _this9.catchingUp = false;\n      }\n\n      // the returned json structure is a bit crap, so make it into a\n      // nicer form (array) after applying sanity to make sure we don't fail\n      // on missing keys (on the off chance)\n      var inviteRooms = [];\n      var joinRooms = [];\n      var leaveRooms = [];\n      var knockRooms = [];\n      if (data.rooms) {\n        if (data.rooms.invite) {\n          inviteRooms = _this9.mapSyncResponseToRoomArray(data.rooms.invite);\n        }\n        if (data.rooms.join) {\n          joinRooms = _this9.mapSyncResponseToRoomArray(data.rooms.join);\n        }\n        if (data.rooms.leave) {\n          leaveRooms = _this9.mapSyncResponseToRoomArray(data.rooms.leave);\n        }\n        if (data.rooms.knock) {\n          knockRooms = _this9.mapSyncResponseToRoomArray(data.rooms.knock);\n        }\n      }\n      _this9.notifEvents = [];\n\n      // Handle invites\n      yield Promise.all(inviteRooms.map(/*#__PURE__*/function () {\n        var _ref7 = _asyncToGenerator(function* (inviteObj) {\n          var room = inviteObj.room;\n          var stateEvents = _this9.mapSyncEventsFormat(inviteObj.invite_state, room);\n          yield _this9.injectRoomEvents(room, stateEvents, undefined);\n          if (inviteObj.isBrandNewRoom) {\n            room.recalculate();\n            client.store.storeRoom(room);\n            client.emit(ClientEvent.Room, room);\n          } else {\n            // Update room state for invite->reject->invite cycles\n            room.recalculate();\n          }\n          stateEvents.forEach(function (e) {\n            client.emit(ClientEvent.Event, e);\n          });\n        });\n        return function (_x3) {\n          return _ref7.apply(this, arguments);\n        };\n      }()));\n\n      // Handle joins\n      yield Promise.all(joinRooms.map(/*#__PURE__*/function () {\n        var _ref8 = _asyncToGenerator(function* (joinObj) {\n          var _joinObj$UNREAD_THREA;\n          var room = joinObj.room;\n          var stateEvents = _this9.mapSyncEventsFormat(joinObj.state, room);\n          var stateAfterEvents = _this9.mapSyncEventsFormat(joinObj[\"org.matrix.msc4222.state_after\"], room);\n          // Prevent events from being decrypted ahead of time\n          // this helps large account to speed up faster\n          // room::decryptCriticalEvent is in charge of decrypting all the events\n          // required for a client to function properly\n          var timelineEvents = _this9.mapSyncEventsFormat(joinObj.timeline, room, false);\n          var ephemeralEvents = _this9.mapSyncEventsFormat(joinObj.ephemeral);\n          var accountDataEvents = _this9.mapSyncEventsFormat(joinObj.account_data);\n          var stickyEvents = _this9.mapSyncEventsFormat(joinObj.msc4354_sticky);\n\n          // If state_after is present, this is the events that form the state at the end of the timeline block and\n          // regular timeline events do *not* count towards state. If it's not present, then the state is formed by\n          // the state events plus the timeline events. Note mapSyncEventsFormat returns an empty array if the field\n          // is absent so we explicitly check the field on the original object.\n          var eventsFormingFinalState = joinObj[\"org.matrix.msc4222.state_after\"] ? stateAfterEvents : stateEvents.concat(timelineEvents);\n          var encrypted = _this9.isRoomEncrypted(room, eventsFormingFinalState);\n          // We store the server-provided value first so it's correct when any of the events fire.\n          if (joinObj.unread_notifications) {\n            /**\n             * We track unread notifications ourselves in encrypted rooms, so don't\n             * bother setting it here. We trust our calculations better than the\n             * server's for this case, and therefore will assume that our non-zero\n             * count is accurate.\n             * XXX: this is known faulty as the push rule for `.m.room.encrypted` may be disabled so server\n             * may issue notification counts of 0 which we wrongly trust.\n             * https://github.com/matrix-org/matrix-spec-proposals/pull/2654 would fix this\n             *\n             * @see import(\"./client\").fixNotificationCountOnDecryption\n             */\n            if (!encrypted || joinObj.unread_notifications.notification_count === 0) {\n              var _joinObj$unread_notif;\n              // In an encrypted room, if the room has notifications enabled then it's typical for\n              // the server to flag all new messages as notifying. However, some push rules calculate\n              // events as ignored based on their event contents (e.g. ignoring msgtype=m.notice messages)\n              // so we want to calculate this figure on the client in all cases.\n              room.setUnreadNotificationCount(NotificationCountType.Total, (_joinObj$unread_notif = joinObj.unread_notifications.notification_count) !== null && _joinObj$unread_notif !== void 0 ? _joinObj$unread_notif : 0);\n            }\n            if (!encrypted || room.getUnreadNotificationCount(NotificationCountType.Highlight) <= 0) {\n              var _joinObj$unread_notif2;\n              // If the locally stored highlight count is zero, use the server provided value.\n              room.setUnreadNotificationCount(NotificationCountType.Highlight, (_joinObj$unread_notif2 = joinObj.unread_notifications.highlight_count) !== null && _joinObj$unread_notif2 !== void 0 ? _joinObj$unread_notif2 : 0);\n            }\n          }\n          var unreadThreadNotifications = (_joinObj$UNREAD_THREA = joinObj[UNREAD_THREAD_NOTIFICATIONS.name]) !== null && _joinObj$UNREAD_THREA !== void 0 ? _joinObj$UNREAD_THREA : joinObj[UNREAD_THREAD_NOTIFICATIONS.altName];\n          if (unreadThreadNotifications) {\n            // This mirrors the logic above for rooms: take the *total* notification count from\n            // the server for unencrypted rooms or is it's zero. Any threads not present in this\n            // object implicitly have zero notifications, so start by clearing the total counts\n            // for all such threads.\n            room.resetThreadUnreadNotificationCountFromSync(Object.keys(unreadThreadNotifications));\n            for (var [threadId, unreadNotification] of Object.entries(unreadThreadNotifications)) {\n              if (!encrypted || unreadNotification.notification_count === 0) {\n                var _unreadNotification$n;\n                room.setThreadUnreadNotificationCount(threadId, NotificationCountType.Total, (_unreadNotification$n = unreadNotification.notification_count) !== null && _unreadNotification$n !== void 0 ? _unreadNotification$n : 0);\n              }\n              var hasNoNotifications = room.getThreadUnreadNotificationCount(threadId, NotificationCountType.Highlight) <= 0;\n              if (!encrypted || encrypted && hasNoNotifications) {\n                var _unreadNotification$h;\n                room.setThreadUnreadNotificationCount(threadId, NotificationCountType.Highlight, (_unreadNotification$h = unreadNotification.highlight_count) !== null && _unreadNotification$h !== void 0 ? _unreadNotification$h : 0);\n              }\n            }\n          } else {\n            room.resetThreadUnreadNotificationCountFromSync();\n          }\n          joinObj.timeline = joinObj.timeline || {};\n          if (joinObj.isBrandNewRoom) {\n            // set the back-pagination token. Do this *before* adding any\n            // events so that clients can start back-paginating.\n            if (joinObj.timeline.prev_batch !== null) {\n              room.getLiveTimeline().setPaginationToken(joinObj.timeline.prev_batch, EventTimeline.BACKWARDS);\n            }\n          } else if (joinObj.timeline.limited) {\n            var limited = true;\n\n            // we've got a limited sync, so we *probably* have a gap in the\n            // timeline, so should reset. But we might have been peeking or\n            // paginating and already have some of the events, in which\n            // case we just want to append any subsequent events to the end\n            // of the existing timeline.\n            //\n            // This is particularly important in the case that we already have\n            // *all* of the events in the timeline - in that case, if we reset\n            // the timeline, we'll end up with an entirely empty timeline,\n            // which we'll try to paginate but not get any new events (which\n            // will stop us linking the empty timeline into the chain).\n            //\n            for (var i = timelineEvents.length - 1; i >= 0; i--) {\n              var eventId = timelineEvents[i].getId();\n              if (room.getTimelineForEvent(eventId)) {\n                _this9.syncOpts.logger.debug(\"Already have event \".concat(eventId, \" in limited sync - not resetting\"));\n                limited = false;\n\n                // we might still be missing some of the events before i;\n                // we don't want to be adding them to the end of the\n                // timeline because that would put them out of order.\n                timelineEvents.splice(0, i);\n\n                // XXX: there's a problem here if the skipped part of the\n                // timeline modifies the state set in stateEvents, because\n                // we'll end up using the state from stateEvents rather\n                // than the later state from timelineEvents. We probably\n                // need to wind stateEvents forward over the events we're\n                // skipping.\n\n                break;\n              }\n            }\n            if (limited) {\n              var _syncEventData$oldSyn;\n              room.resetLiveTimeline(joinObj.timeline.prev_batch, _this9.syncOpts.canResetEntireTimeline(room.roomId) ? null : (_syncEventData$oldSyn = syncEventData.oldSyncToken) !== null && _syncEventData$oldSyn !== void 0 ? _syncEventData$oldSyn : null);\n\n              // We have to assume any gap in any timeline is\n              // reason to stop incrementally tracking notifications and\n              // reset the timeline.\n              client.resetNotifTimelineSet();\n            }\n          }\n\n          // process any crypto events *before* emitting the RoomStateEvent events. This\n          // avoids a race condition if the application tries to send a message after the\n          // state event is processed, but before crypto is enabled, which then causes the\n          // crypto layer to complain.\n\n          if (_this9.syncOpts.cryptoCallbacks) {\n            for (var e of eventsFormingFinalState) {\n              if (e.isState() && e.getType() === EventType.RoomEncryption && e.getStateKey() === \"\") {\n                yield _this9.syncOpts.cryptoCallbacks.onCryptoEvent(room, e);\n              }\n            }\n          }\n\n          // Proactively decrypt state events: normally we decrypt on demand, but for state\n          // events we need them immediately, so we handle them here. Specifically, consumers\n          // (e.g. Element Web) expect state events to be unencrypted upon receipt.\n          for (var ev of timelineEvents.filter(ev => ev.isState())) {\n            yield _this9.client.decryptEventIfNeeded(ev);\n          }\n          try {\n            if (\"org.matrix.msc4222.state_after\" in joinObj) {\n              yield _this9.injectRoomEvents(room, undefined, stateAfterEvents, timelineEvents, syncEventData.fromCache);\n            } else {\n              yield _this9.injectRoomEvents(room, stateEvents, undefined, timelineEvents, syncEventData.fromCache);\n            }\n          } catch (e) {\n            _this9.syncOpts.logger.error(\"Failed to process events on room \".concat(room.roomId, \":\"), e);\n          }\n\n          // set summary after processing events,\n          // because it will trigger a name calculation\n          // which needs the room state to be up to date\n          if (joinObj.summary) {\n            room.setSummary(joinObj.summary);\n          }\n\n          // we deliberately don't add ephemeral events to the timeline\n          room.addEphemeralEvents(ephemeralEvents);\n\n          // we deliberately don't add accountData to the timeline\n          room.addAccountData(accountDataEvents);\n\n          // Sticky events primarily come via the `timeline` field, with the\n          // sticky info field marking them as sticky.\n          // If the sync is \"gappy\" (meaning it is skipping events to catch up) then\n          // sticky events will instead come down the sticky section.\n          // This ensures we collect sticky events from both places.\n          var stickyEventsAndStickyEventsFromTheTimeline = stickyEvents.concat(timelineEvents.filter(e => e.unstableStickyInfo !== undefined));\n          // Note: We calculate sticky events before emitting `.Room` as it's nice to have\n          // sticky events calculated and ready to go.\n          room._unstable_addStickyEvents(stickyEventsAndStickyEventsFromTheTimeline);\n          room.recalculate();\n          if (joinObj.isBrandNewRoom) {\n            client.store.storeRoom(room);\n            client.emit(ClientEvent.Room, room);\n          }\n          _this9.processEventsForNotifs(room, timelineEvents);\n          var emitEvent = e => client.emit(ClientEvent.Event, e);\n          // this fires a couple of times for some events. (eg state events are in the timeline and the state)\n          // should this get a sync section as an additional event emission param (e, syncSection))?\n          stateEvents.forEach(emitEvent);\n          timelineEvents.forEach(emitEvent);\n          ephemeralEvents.forEach(emitEvent);\n          accountDataEvents.forEach(emitEvent);\n          stickyEvents.filter(stickyEvent =>\n          // This is highly unlikey, but in the case where a sticky event\n          // has appeared in the timeline AND the sticky section, we only\n          // want to emit the event once.\n          !timelineEvents.some(timelineEvent => timelineEvent.getId() === stickyEvent.getId())).forEach(emitEvent);\n          // Decrypt only the last message in all rooms to make sure we can generate a preview\n          // And decrypt all events after the recorded read receipt to ensure an accurate\n          // notification count\n          room.decryptCriticalEvents();\n        });\n        return function (_x4) {\n          return _ref8.apply(this, arguments);\n        };\n      }()));\n\n      // Handle leaves (e.g. kicked rooms)\n      yield Promise.all(leaveRooms.map(/*#__PURE__*/function () {\n        var _ref9 = _asyncToGenerator(function* (leaveObj) {\n          var room = leaveObj.room;\n          var {\n            timelineEvents,\n            stateEvents,\n            stateAfterEvents\n          } = yield _this9.mapAndInjectRoomEvents(leaveObj);\n          var accountDataEvents = _this9.mapSyncEventsFormat(leaveObj.account_data);\n          room.addAccountData(accountDataEvents);\n          room.recalculate();\n          if (leaveObj.isBrandNewRoom) {\n            client.store.storeRoom(room);\n            client.emit(ClientEvent.Room, room);\n          }\n          _this9.processEventsForNotifs(room, timelineEvents);\n          stateEvents === null || stateEvents === void 0 || stateEvents.forEach(function (e) {\n            client.emit(ClientEvent.Event, e);\n          });\n          stateAfterEvents === null || stateAfterEvents === void 0 || stateAfterEvents.forEach(function (e) {\n            client.emit(ClientEvent.Event, e);\n          });\n          timelineEvents.forEach(function (e) {\n            client.emit(ClientEvent.Event, e);\n          });\n          accountDataEvents.forEach(function (e) {\n            client.emit(ClientEvent.Event, e);\n          });\n        });\n        return function (_x5) {\n          return _ref9.apply(this, arguments);\n        };\n      }()));\n\n      // Handle knocks\n      yield Promise.all(knockRooms.map(/*#__PURE__*/function () {\n        var _ref0 = _asyncToGenerator(function* (knockObj) {\n          var room = knockObj.room;\n          var stateEvents = _this9.mapSyncEventsFormat(knockObj.knock_state, room);\n          yield _this9.injectRoomEvents(room, stateEvents, undefined);\n          if (knockObj.isBrandNewRoom) {\n            room.recalculate();\n            client.store.storeRoom(room);\n            client.emit(ClientEvent.Room, room);\n          } else {\n            // Update room state for knock->leave->knock cycles\n            room.recalculate();\n          }\n          stateEvents.forEach(function (e) {\n            client.emit(ClientEvent.Event, e);\n          });\n        });\n        return function (_x6) {\n          return _ref0.apply(this, arguments);\n        };\n      }()));\n\n      // update the notification timeline, if appropriate.\n      // we only do this for live events, as otherwise we can't order them sanely\n      // in the timeline relative to ones paginated in by /notifications.\n      // XXX: we could fix this by making EventTimeline support chronological\n      // ordering... but it doesn't, right now.\n      if (syncEventData.oldSyncToken && _this9.notifEvents.length) {\n        _this9.notifEvents.sort(function (a, b) {\n          return a.getTs() - b.getTs();\n        });\n        _this9.notifEvents.forEach(function (event) {\n          var _client$getNotifTimel;\n          (_client$getNotifTimel = client.getNotifTimelineSet()) === null || _client$getNotifTimel === void 0 || _client$getNotifTimel.addLiveEvent(event, {\n            addToState: true\n          });\n        });\n      }\n\n      // Handle device list updates\n      if (data.device_lists) {\n        if (_this9.syncOpts.cryptoCallbacks) {\n          yield _this9.syncOpts.cryptoCallbacks.processDeviceLists(data.device_lists);\n        } else {\n          // FIXME if we *don't* have a crypto module, we still need to\n          // invalidate the device lists. But that would require a\n          // substantial bit of rework :/.\n        }\n      }\n\n      // Handle one_time_keys_count and unused fallback keys\n      yield (_this9$syncOpts$crypt = _this9.syncOpts.cryptoCallbacks) === null || _this9$syncOpts$crypt === void 0 ? void 0 : _this9$syncOpts$crypt.processKeyCounts(data.device_one_time_keys_count, (_data$device_unused_f = data.device_unused_fallback_key_types) !== null && _data$device_unused_f !== void 0 ? _data$device_unused_f : data[\"org.matrix.msc2732.device_unused_fallback_key_types\"]);\n    })();\n  }\n\n  /**\n   * Starts polling the connectivity check endpoint\n   * @param delay - How long to delay until the first poll.\n   *        defaults to a short, randomised interval (to prevent\n   *        tight-looping if /versions succeeds but /sync etc. fail).\n   * @returns which resolves once the connection returns\n   */\n  startKeepAlives(delay) {\n    if (delay === undefined) {\n      delay = 2000 + Math.floor(Math.random() * 5000);\n    }\n    if (this.keepAliveTimer !== null) {\n      clearTimeout(this.keepAliveTimer);\n    }\n    if (delay > 0) {\n      this.keepAliveTimer = setTimeout(this.pokeKeepAlive.bind(this), delay);\n    } else {\n      this.pokeKeepAlive();\n    }\n    if (!this.connectionReturnedResolvers) {\n      this.connectionReturnedResolvers = Promise.withResolvers();\n    }\n    return this.connectionReturnedResolvers.promise;\n  }\n\n  /**\n   * Make a dummy call to /_matrix/client/versions, to see if the HS is\n   * reachable.\n   *\n   * On failure, schedules a call back to itself. On success, resolves\n   * this.connectionReturnedResolvers.\n   *\n   * @param connDidFail - True if a connectivity failure has been detected. Optional.\n   */\n  pokeKeepAlive() {\n    var _this$abortController4;\n    var connDidFail = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n    if (!this.running) {\n      // we are in a keepAlive, retrying to connect, but the syncronization\n      // was stopped, so we are stopping the retry.\n      clearTimeout(this.keepAliveTimer);\n      if (this.connectionReturnedResolvers) {\n        this.connectionReturnedResolvers.reject(\"SyncApi.stop() was called\");\n        this.connectionReturnedResolvers = undefined;\n      }\n      return;\n    }\n    var success = () => {\n      clearTimeout(this.keepAliveTimer);\n      if (this.connectionReturnedResolvers) {\n        this.connectionReturnedResolvers.resolve(connDidFail);\n        this.connectionReturnedResolvers = undefined;\n      }\n    };\n    this.client.http.request(Method.Get, \"/_matrix/client/versions\", undefined,\n    // queryParams\n    undefined,\n    // data\n    {\n      prefix: \"\",\n      localTimeoutMs: 15 * 1000,\n      abortSignal: (_this$abortController4 = this.abortController) === null || _this$abortController4 === void 0 ? void 0 : _this$abortController4.signal\n    }).then(() => {\n      success();\n    }, err => {\n      if (err.httpStatus == 400 || err.httpStatus == 404) {\n        // treat this as a success because the server probably just doesn't\n        // support /versions: point is, we're getting a response.\n        // We wait a short time though, just in case somehow the server\n        // is in a mode where it 400s /versions responses and sync etc.\n        // responses fail, this will mean we don't hammer in a loop.\n        this.keepAliveTimer = setTimeout(success, 2000);\n      } else {\n        connDidFail = true;\n        this.keepAliveTimer = setTimeout(this.pokeKeepAlive.bind(this, connDidFail), 5000 + Math.floor(Math.random() * 5000));\n        // A keepalive has failed, so we emit the\n        // error state (whether or not this is the\n        // first failure).\n        // Note we do this after setting the timer:\n        // this lets the unit tests advance the mock\n        // clock when they get the error.\n        this.updateSyncState(SyncState.Error, {\n          error: err\n        });\n      }\n    });\n  }\n  mapSyncResponseToRoomArray(obj) {\n    // Maps { roomid: {stuff}, roomid: {stuff} }\n    // to\n    // [{stuff+Room+isBrandNewRoom}, {stuff+Room+isBrandNewRoom}]\n    var client = this.client;\n    return Object.keys(obj).filter(k => !unsafeProp(k)).map(roomId => {\n      var room = client.store.getRoom(roomId);\n      var isBrandNewRoom = false;\n      if (!room) {\n        room = this.createRoom(roomId);\n        isBrandNewRoom = true;\n      }\n      return _objectSpread(_objectSpread({}, obj[roomId]), {}, {\n        room,\n        isBrandNewRoom\n      });\n    });\n  }\n  mapSyncEventsFormat(obj, room) {\n    var decrypt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n    if (!obj || !Array.isArray(obj.events)) {\n      return [];\n    }\n    var mapper = this.client.getEventMapper({\n      decrypt\n    });\n    return obj.events.filter(noUnsafeEventProps).map(function (e) {\n      if (room) {\n        e.room_id = room.roomId;\n      }\n      return mapper(e);\n    });\n  }\n\n  /**\n   */\n  resolveInvites(room) {\n    if (!room || !this.opts.resolveInvitesToProfiles) {\n      return;\n    }\n    var client = this.client;\n    // For each invited room member we want to give them a displayname/avatar url\n    // if they have one (the m.room.member invites don't contain this).\n    room.getMembersWithMembership(KnownMembership.Invite).forEach(function (member) {\n      if (member.requestedProfileInfo) return;\n      member.requestedProfileInfo = true;\n      // try to get a cached copy first.\n      var user = client.getUser(member.userId);\n      var promise;\n      if (user) {\n        promise = Promise.resolve({\n          avatar_url: user.avatarUrl,\n          displayname: user.displayName\n        });\n      } else {\n        promise = client.getProfileInfo(member.userId);\n      }\n      promise.then(function (info) {\n        // slightly naughty by doctoring the invite event but this means all\n        // the code paths remain the same between invite/join display name stuff\n        // which is a worthy trade-off for some minor pollution.\n        var inviteEvent = member.events.member;\n        if ((inviteEvent === null || inviteEvent === void 0 ? void 0 : inviteEvent.getContent().membership) !== KnownMembership.Invite) {\n          // between resolving and now they have since joined, so don't clobber\n          return;\n        }\n        inviteEvent.getContent().avatar_url = info.avatar_url;\n        inviteEvent.getContent().displayname = info.displayname;\n        // fire listeners\n        member.setMembershipEvent(inviteEvent, room.currentState);\n      }, function (err) {\n        // OH WELL.\n      });\n    });\n  }\n  findEncryptionEvent(events) {\n    return events === null || events === void 0 ? void 0 : events.find(e => e.getType() === EventType.RoomEncryption && e.getStateKey() === \"\");\n  }\n\n  // When processing the sync response we cannot rely on Room.hasEncryptionStateEvent we actually\n  // inject the events into the room object, so we have to inspect the events themselves.\n  isRoomEncrypted(room, eventsFormingFinalState) {\n    return room.hasEncryptionStateEvent() || !!this.findEncryptionEvent(eventsFormingFinalState);\n  }\n  mapAndInjectRoomEvents(wrappedRoom) {\n    var _this0 = this;\n    return _asyncToGenerator(function* () {\n      var stateEvents = _this0.mapSyncEventsFormat(wrappedRoom.state, wrappedRoom.room);\n      var stateAfterEvents = _this0.mapSyncEventsFormat(wrappedRoom[\"org.matrix.msc4222.state_after\"], wrappedRoom.room);\n      var timelineEvents = _this0.mapSyncEventsFormat(wrappedRoom.timeline, wrappedRoom.room);\n      if (\"org.matrix.msc4222.state_after\" in wrappedRoom) {\n        yield _this0.injectRoomEvents(wrappedRoom.room, undefined, stateAfterEvents, timelineEvents);\n      } else {\n        yield _this0.injectRoomEvents(wrappedRoom.room, stateEvents, undefined, timelineEvents);\n      }\n      return {\n        timelineEvents,\n        stateEvents,\n        stateAfterEvents\n      };\n    })();\n  }\n\n  /**\n   * Injects events into a room's model.\n   * @param stateEventList - A list of state events. This is the state\n   * at the *START* of the timeline list if it is supplied.\n   * @param stateAfterEventList - A list of state events. This is the state\n   * at the *END* of the timeline list if it is supplied.\n   * @param timelineEventList - A list of timeline events, including threaded. Lower index\n   * is earlier in time. Higher index is later.\n   * @param fromCache - whether the sync response came from cache\n   *\n   * No more than one of stateEventList and stateAfterEventList must be supplied. If\n   * stateEventList is supplied, the events in timelineEventList are added to the state\n   * after stateEventList. If stateAfterEventList is supplied, the events in timelineEventList\n   * are not added to the state.\n   */\n\n  injectRoomEvents(room, stateEventList, stateAfterEventList, timelineEventList) {\n    var _arguments = arguments,\n      _this1 = this;\n    return _asyncToGenerator(function* () {\n      var fromCache = _arguments.length > 4 && _arguments[4] !== undefined ? _arguments[4] : false;\n      var eitherStateEventList = stateAfterEventList !== null && stateAfterEventList !== void 0 ? stateAfterEventList : stateEventList;\n\n      // If there are no events in the timeline yet, initialise it with\n      // the given state events\n      var liveTimeline = room.getLiveTimeline();\n      var timelineWasEmpty = liveTimeline.getEvents().length == 0;\n      if (timelineWasEmpty) {\n        // Passing these events into initialiseState will freeze them, so we need\n        // to compute and cache the push actions for them now, otherwise sync dies\n        // with an attempt to assign to read only property.\n        // XXX: This is pretty horrible and is assuming all sorts of behaviour from\n        // these functions that it shouldn't be. We should probably either store the\n        // push actions cache elsewhere so we can freeze MatrixEvents, or otherwise\n        // find some solution where MatrixEvents are immutable but allow for a cache\n        // field.\n\n        for (var ev of eitherStateEventList) {\n          _this1.client.getPushActionsForEvent(ev);\n        }\n        liveTimeline.initialiseState(eitherStateEventList, {\n          timelineWasEmpty\n        });\n      }\n      _this1.resolveInvites(room);\n\n      // recalculate the room name at this point as adding events to the timeline\n      // may make notifications appear which should have the right name.\n      // XXX: This looks suspect: we'll end up recalculating the room once here\n      // and then again after adding events (processSyncResponse calls it after\n      // calling us) even if no state events were added. It also means that if\n      // one of the room events in timelineEventList is something that needs\n      // a recalculation (like m.room.name) we won't recalculate until we've\n      // finished adding all the events, which will cause the notification to have\n      // the old room name rather than the new one.\n      room.recalculate();\n\n      // If the timeline wasn't empty, we process the state events here: they're\n      // defined as updates to the state before the start of the timeline, so this\n      // starts to roll the state forward.\n      // XXX: That's what we *should* do, but this can happen if we were previously\n      // peeking in a room, in which case we obviously do *not* want to add the\n      // state events here onto the end of the timeline. Historically, the js-sdk\n      // has just set these new state events on the old and new state. This seems\n      // very wrong because there could be events in the timeline that diverge the\n      // state, in which case this is going to leave things out of sync. However,\n      // for now I think it;s best to behave the same as the code has done previously.\n      if (!timelineWasEmpty) {\n        // XXX: As above, don't do this...\n        //room.addLiveEvents(stateEventList || []);\n        // Do this instead...\n        room.oldState.setStateEvents(eitherStateEventList);\n        room.currentState.setStateEvents(eitherStateEventList);\n      }\n\n      // Execute the timeline events. If addToState is true the timeline has any state\n      // events in it, this will continue to diverge the current state.\n      // This also needs to be done before running push rules on the events as they need\n      // to be decorated with sender etc.\n      yield room.addLiveEvents(timelineEventList || [], {\n        fromCache,\n        timelineWasEmpty,\n        addToState: stateAfterEventList === undefined\n      });\n      _this1.client.processBeaconEvents(room, timelineEventList);\n    })();\n  }\n\n  /**\n   * Takes a list of timelineEvents and adds and adds to notifEvents\n   * as appropriate.\n   * This must be called after the room the events belong to has been stored.\n   *\n   * @param timelineEventList - A list of timeline events. Lower index\n   * is earlier in time. Higher index is later.\n   */\n  processEventsForNotifs(room, timelineEventList) {\n    // gather our notifications into this.notifEvents\n    if (this.client.getNotifTimelineSet()) {\n      for (var event of timelineEventList) {\n        var _pushActions$tweaks;\n        var pushActions = this.client.getPushActionsForEvent(event);\n        if (pushActions !== null && pushActions !== void 0 && pushActions.notify && (_pushActions$tweaks = pushActions.tweaks) !== null && _pushActions$tweaks !== void 0 && _pushActions$tweaks.highlight) {\n          this.notifEvents.push(event);\n        }\n      }\n    }\n  }\n  getGuestFilter() {\n    // Dev note: This used to be conditional to return a filter of 20 events maximum, but\n    // the condition never went to the other branch. This is now hardcoded.\n    return \"{}\";\n  }\n\n  /**\n   * Sets the sync state and emits an event to say so\n   * @param newState - The new state string\n   * @param data - Object of additional data to emit in the event\n   */\n  updateSyncState(newState, data) {\n    var old = this.syncState;\n    this.syncState = newState;\n    this.syncStateData = data;\n    this.client.emit(ClientEvent.Sync, this.syncState, old, data);\n  }\n}\n\n// /!\\ This function is not intended for public use! It's only exported from\n// here in order to share some common logic with sliding-sync-sdk.ts.\nexport function _createAndReEmitRoom(client, roomId, opts) {\n  var {\n    timelineSupport\n  } = client;\n  var room = new Room(roomId, client, client.getUserId(), {\n    lazyLoadMembers: opts.lazyLoadMembers,\n    pendingEventOrdering: opts.pendingEventOrdering,\n    timelineSupport\n  });\n  client.reEmitter.reEmit(room, [RoomEvent.Name, RoomEvent.Redaction, RoomEvent.RedactionCancelled, RoomEvent.Receipt, RoomEvent.Tags, RoomEvent.LocalEchoUpdated, RoomEvent.AccountData, RoomEvent.MyMembership, RoomEvent.Timeline, RoomEvent.TimelineReset, RoomStateEvent.Events, RoomStateEvent.Members, RoomStateEvent.NewMember, RoomStateEvent.Update, BeaconEvent.New, BeaconEvent.Update, BeaconEvent.Destroy, BeaconEvent.LivenessChange]);\n\n  // We need to add a listener for RoomState.members in order to hook them\n  // correctly.\n  room.on(RoomStateEvent.NewMember, (event, state, member) => {\n    var _client$getUser;\n    member.user = (_client$getUser = client.getUser(member.userId)) !== null && _client$getUser !== void 0 ? _client$getUser : undefined;\n    client.reEmitter.reEmit(member, [RoomMemberEvent.Name, RoomMemberEvent.Typing, RoomMemberEvent.PowerLevel, RoomMemberEvent.Membership]);\n  });\n  return room;\n}\n\n/**\n * Process a list of (decrypted, where possible) received to-device events.\n *\n * Emits the appropriate {@link ClientEvent.ReceivedToDeviceMessage} event.\n * Also converts the events into `MatrixEvent`s, and emits the now deprecated {@link ClientEvent.ToDeviceEvent} events for compatibility.\n * */\nexport function processToDeviceMessages(toDeviceMessages, client) {\n  var cancelledKeyVerificationTxns = [];\n  toDeviceMessages.map(processedMessage => {\n    // map is a cheap inline forEach\n    // We want to flag m.key.verification.start events as cancelled\n    // if there's an accompanying m.key.verification.cancel event, so\n    // we pull out the transaction IDs from the cancellation events\n    // so we can flag the verification events as cancelled in the loop\n    // below.\n    if (processedMessage.message.type === \"m.key.verification.cancel\") {\n      var txnId = processedMessage.message.content[\"transaction_id\"];\n      if (txnId) {\n        cancelledKeyVerificationTxns.push(txnId);\n      }\n    }\n\n    // as mentioned above, .map is a cheap inline forEach, so return\n    // the unmodified event.\n    return processedMessage;\n  }).forEach(function (processedEvent) {\n    // For backwards compatibility, we also emit the event as a `MatrixEvent` using `ClientEvent.ToDeviceEvent`.\n    {\n      var toDeviceEvent = processedEvent.message;\n      var content = toDeviceEvent.content;\n      // The message is cloned before being passed to the MatrixEvent constructor, because\n      // the `makeEncrypted` method will mutate the type and content properties of the original message and will interfere\n      // with the emitted event for `ReceivedToDeviceMessage`.\n      var deprecatedCompatibilityEvent = new MatrixEvent(Object.assign({}, toDeviceEvent));\n      if (toDeviceEvent.type === \"m.key.verification.start\" || toDeviceEvent.type === \"m.key.verification.request\") {\n        var txnId = content[\"transaction_id\"];\n        if (cancelledKeyVerificationTxns.includes(txnId)) {\n          deprecatedCompatibilityEvent.flagCancelled();\n        }\n      }\n      if (processedEvent.encryptionInfo) {\n        // Restore partially the legacy behavior to detect encrypted messages.\n        // Now `event.isEncrypted()` will return true.\n        deprecatedCompatibilityEvent.makeEncrypted(EventType.RoomMessageEncrypted, {\n          ciphertext: \"\"\n        }, processedEvent.encryptionInfo.senderCurve25519KeyBase64, \"\");\n      }\n      client.emit(ClientEvent.ToDeviceEvent, deprecatedCompatibilityEvent);\n    }\n    client.emit(ClientEvent.ReceivedToDeviceMessage, processedEvent);\n  });\n}\n//# sourceMappingURL=sync.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module.\n */\n\n/**\n * Construct a stub store. This does no-ops on most store methods.\n */\nexport class StubStore {\n  constructor() {\n    _defineProperty(this, \"accountData\", new Map());\n    // stub\n    _defineProperty(this, \"fromToken\", null);\n  }\n  /** @returns whether or not the database was newly created in this session. */\n  isNewlyCreated() {\n    return Promise.resolve(true);\n  }\n\n  /**\n   * Get the sync token.\n   */\n  getSyncToken() {\n    return this.fromToken;\n  }\n\n  /**\n   * Set the sync token.\n   */\n  setSyncToken(token) {\n    this.fromToken = token;\n  }\n\n  /**\n   * No-op.\n   */\n  storeRoom(room) {}\n\n  /**\n   * No-op.\n   */\n  getRoom(roomId) {\n    return null;\n  }\n\n  /**\n   * No-op.\n   * @returns An empty array.\n   */\n  getRooms() {\n    return [];\n  }\n\n  /**\n   * Permanently delete a room.\n   */\n  removeRoom(roomId) {\n    return;\n  }\n\n  /**\n   * No-op.\n   * @returns An empty array.\n   */\n  getRoomSummaries() {\n    return [];\n  }\n\n  /**\n   * No-op.\n   */\n  storeUser(user) {}\n\n  /**\n   * No-op.\n   */\n  getUser(userId) {\n    return null;\n  }\n\n  /**\n   * No-op.\n   */\n  getUsers() {\n    return [];\n  }\n\n  /**\n   * No-op.\n   */\n  scrollback(room, limit) {\n    return [];\n  }\n\n  /**\n   * No-op.\n   */\n  setUserCreator(creator) {\n    return;\n  }\n\n  /**\n   * Store events for a room.\n   * @param room - The room to store events for.\n   * @param events - The events to store.\n   * @param token - The token associated with these events.\n   * @param toStart - True if these are paginated results.\n   */\n  storeEvents(room, events, token, toStart) {}\n\n  /**\n   * Store a filter.\n   */\n  storeFilter(filter) {}\n\n  /**\n   * Retrieve a filter.\n   * @returns A filter or null.\n   */\n  getFilter(userId, filterId) {\n    return null;\n  }\n\n  /**\n   * Retrieve a filter ID with the given name.\n   * @param filterName - The filter name.\n   * @returns The filter ID or null.\n   */\n  getFilterIdByName(filterName) {\n    return null;\n  }\n\n  /**\n   * Set a filter name to ID mapping.\n   */\n  setFilterIdByName(filterName, filterId) {}\n\n  /**\n   * Store user-scoped account data events\n   * @param events - The events to store.\n   */\n  storeAccountDataEvents(events) {}\n\n  /**\n   * Get account data event by event type\n   * @param eventType - The event type being queried\n   */\n  getAccountData(eventType) {\n    return undefined;\n  }\n\n  /**\n   * setSyncData does nothing as there is no backing data store.\n   *\n   * @param syncData - The sync data\n   * @returns An immediately resolved promise.\n   */\n  setSyncData(syncData) {\n    return Promise.resolve();\n  }\n\n  /**\n   * We never want to save because we have nothing to save to.\n   *\n   * @returns If the store wants to save\n   */\n  wantsSave() {\n    return false;\n  }\n\n  /**\n   * Save does nothing as there is no backing data store.\n   */\n  save() {\n    return Promise.resolve();\n  }\n\n  /**\n   * Startup does nothing.\n   * @returns An immediately resolved promise.\n   */\n  startup() {\n    return Promise.resolve();\n  }\n\n  /**\n   * @returns Promise which resolves with a sync response to restore the\n   * client state to where it was at the last save, or null if there\n   * is no saved sync data.\n   */\n  getSavedSync() {\n    return Promise.resolve(null);\n  }\n\n  /**\n   * @returns If there is a saved sync, the nextBatch token\n   * for this sync, otherwise null.\n   */\n  getSavedSyncToken() {\n    return Promise.resolve(null);\n  }\n\n  /**\n   * Delete all data from this store. Does nothing since this store\n   * doesn't store anything.\n   * @returns An immediately resolved promise.\n   */\n  deleteAllData() {\n    return Promise.resolve();\n  }\n  getOutOfBandMembers() {\n    return Promise.resolve(null);\n  }\n  setOutOfBandMembers(roomId, membershipEvents) {\n    return Promise.resolve();\n  }\n  clearOutOfBandMembers() {\n    return Promise.resolve();\n  }\n  getClientOptions() {\n    return Promise.resolve(undefined);\n  }\n  storeClientOptions(options) {\n    return Promise.resolve();\n  }\n  getPendingEvents(roomId) {\n    return _asyncToGenerator(function* () {\n      return [];\n    })();\n  }\n  setPendingEvents(roomId, events) {\n    return Promise.resolve();\n  }\n  saveToDeviceBatches(batch) {\n    return _asyncToGenerator(function* () {\n      return Promise.resolve();\n    })();\n  }\n  getOldestToDeviceBatch() {\n    return Promise.resolve(null);\n  }\n  removeToDeviceBatch(id) {\n    return _asyncToGenerator(function* () {\n      return Promise.resolve();\n    })();\n  }\n  destroy() {\n    return _asyncToGenerator(function* () {})();\n  } // Nothing to do\n}\n//# sourceMappingURL=stub.js.map","import validate from './validate.js';\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n    byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n    return (byteToHex[arr[offset + 0]] +\n        byteToHex[arr[offset + 1]] +\n        byteToHex[arr[offset + 2]] +\n        byteToHex[arr[offset + 3]] +\n        '-' +\n        byteToHex[arr[offset + 4]] +\n        byteToHex[arr[offset + 5]] +\n        '-' +\n        byteToHex[arr[offset + 6]] +\n        byteToHex[arr[offset + 7]] +\n        '-' +\n        byteToHex[arr[offset + 8]] +\n        byteToHex[arr[offset + 9]] +\n        '-' +\n        byteToHex[arr[offset + 10]] +\n        byteToHex[arr[offset + 11]] +\n        byteToHex[arr[offset + 12]] +\n        byteToHex[arr[offset + 13]] +\n        byteToHex[arr[offset + 14]] +\n        byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n    const uuid = unsafeStringify(arr, offset);\n    if (!validate(uuid)) {\n        throw TypeError('Stringified UUID is invalid');\n    }\n    return uuid;\n}\nexport default stringify;\n","let getRandomValues;\nconst rnds8 = new Uint8Array(16);\nexport default function rng() {\n    if (!getRandomValues) {\n        if (typeof crypto === 'undefined' || !crypto.getRandomValues) {\n            throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n        }\n        getRandomValues = crypto.getRandomValues.bind(crypto);\n    }\n    return getRandomValues(rnds8);\n}\n","const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nexport default { randomUUID };\n","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction _v4(options, buf, offset) {\n    options = options || {};\n    const rnds = options.random ?? options.rng?.() ?? rng();\n    if (rnds.length < 16) {\n        throw new Error('Random bytes length must be >= 16');\n    }\n    rnds[6] = (rnds[6] & 0x0f) | 0x40;\n    rnds[8] = (rnds[8] & 0x3f) | 0x80;\n    if (buf) {\n        offset = offset || 0;\n        if (offset < 0 || offset + 16 > buf.length) {\n            throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);\n        }\n        for (let i = 0; i < 16; ++i) {\n            buf[offset + i] = rnds[i];\n        }\n        return buf;\n    }\n    return unsafeStringify(rnds);\n}\nfunction v4(options, buf, offset) {\n    if (native.randomUUID && !buf && !options) {\n        return native.randomUUID();\n    }\n    return _v4(options, buf, offset);\n}\nexport default v4;\n","var grammar = module.exports = {\n  v: [{\n    name: 'version',\n    reg: /^(\\d*)$/\n  }],\n  o: [{\n    // o=- 20518 0 IN IP4 203.0.113.1\n    // NB: sessionId will be a String in most cases because it is huge\n    name: 'origin',\n    reg: /^(\\S*) (\\d*) (\\d*) (\\S*) IP(\\d) (\\S*)/,\n    names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],\n    format: '%s %s %d %s IP%d %s'\n  }],\n  // default parsing of these only (though some of these feel outdated)\n  s: [{ name: 'name' }],\n  i: [{ name: 'description' }],\n  u: [{ name: 'uri' }],\n  e: [{ name: 'email' }],\n  p: [{ name: 'phone' }],\n  z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly...\n  r: [{ name: 'repeats' }],   // TODO: this one can also be parsed properly\n  // k: [{}], // outdated thing ignored\n  t: [{\n    // t=0 0\n    name: 'timing',\n    reg: /^(\\d*) (\\d*)/,\n    names: ['start', 'stop'],\n    format: '%d %d'\n  }],\n  c: [{\n    // c=IN IP4 10.47.197.26\n    name: 'connection',\n    reg: /^IN IP(\\d) (\\S*)/,\n    names: ['version', 'ip'],\n    format: 'IN IP%d %s'\n  }],\n  b: [{\n    // b=AS:4000\n    push: 'bandwidth',\n    reg: /^(TIAS|AS|CT|RR|RS):(\\d*)/,\n    names: ['type', 'limit'],\n    format: '%s:%s'\n  }],\n  m: [{\n    // m=video 51744 RTP/AVP 126 97 98 34 31\n    // NB: special - pushes to session\n    // TODO: rtp/fmtp should be filtered by the payloads found here?\n    reg: /^(\\w*) (\\d*) ([\\w/]*)(?: (.*))?/,\n    names: ['type', 'port', 'protocol', 'payloads'],\n    format: '%s %d %s %s'\n  }],\n  a: [\n    {\n      // a=rtpmap:110 opus/48000/2\n      push: 'rtp',\n      reg: /^rtpmap:(\\d*) ([\\w\\-.]*)(?:\\s*\\/(\\d*)(?:\\s*\\/(\\S*))?)?/,\n      names: ['payload', 'codec', 'rate', 'encoding'],\n      format: function (o) {\n        return (o.encoding)\n          ? 'rtpmap:%d %s/%s/%s'\n          : o.rate\n            ? 'rtpmap:%d %s/%s'\n            : 'rtpmap:%d %s';\n      }\n    },\n    {\n      // a=fmtp:108 profile-level-id=24;object=23;bitrate=64000\n      // a=fmtp:111 minptime=10; useinbandfec=1\n      push: 'fmtp',\n      reg: /^fmtp:(\\d*) ([\\S| ]*)/,\n      names: ['payload', 'config'],\n      format: 'fmtp:%d %s'\n    },\n    {\n      // a=control:streamid=0\n      name: 'control',\n      reg: /^control:(.*)/,\n      format: 'control:%s'\n    },\n    {\n      // a=rtcp:65179 IN IP4 193.84.77.194\n      name: 'rtcp',\n      reg: /^rtcp:(\\d*)(?: (\\S*) IP(\\d) (\\S*))?/,\n      names: ['port', 'netType', 'ipVer', 'address'],\n      format: function (o) {\n        return (o.address != null)\n          ? 'rtcp:%d %s IP%d %s'\n          : 'rtcp:%d';\n      }\n    },\n    {\n      // a=rtcp-fb:98 trr-int 100\n      push: 'rtcpFbTrrInt',\n      reg: /^rtcp-fb:(\\*|\\d*) trr-int (\\d*)/,\n      names: ['payload', 'value'],\n      format: 'rtcp-fb:%s trr-int %d'\n    },\n    {\n      // a=rtcp-fb:98 nack rpsi\n      push: 'rtcpFb',\n      reg: /^rtcp-fb:(\\*|\\d*) ([\\w-_]*)(?: ([\\w-_]*))?/,\n      names: ['payload', 'type', 'subtype'],\n      format: function (o) {\n        return (o.subtype != null)\n          ? 'rtcp-fb:%s %s %s'\n          : 'rtcp-fb:%s %s';\n      }\n    },\n    {\n      // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset\n      // a=extmap:1/recvonly URI-gps-string\n      // a=extmap:3 urn:ietf:params:rtp-hdrext:encrypt urn:ietf:params:rtp-hdrext:smpte-tc 25@600/24\n      push: 'ext',\n      reg: /^extmap:(\\d+)(?:\\/(\\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\\S*)(?: (\\S*))?/,\n      names: ['value', 'direction', 'encrypt-uri', 'uri', 'config'],\n      format: function (o) {\n        return (\n          'extmap:%d' +\n          (o.direction ? '/%s' : '%v') +\n          (o['encrypt-uri'] ? ' %s' : '%v') +\n          ' %s' +\n          (o.config ? ' %s' : '')\n        );\n      }\n    },\n    {\n      // a=extmap-allow-mixed\n      name: 'extmapAllowMixed',\n      reg: /^(extmap-allow-mixed)/\n    },\n    {\n      // a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32\n      push: 'crypto',\n      reg: /^crypto:(\\d*) ([\\w_]*) (\\S*)(?: (\\S*))?/,\n      names: ['id', 'suite', 'config', 'sessionConfig'],\n      format: function (o) {\n        return (o.sessionConfig != null)\n          ? 'crypto:%d %s %s %s'\n          : 'crypto:%d %s %s';\n      }\n    },\n    {\n      // a=setup:actpass\n      name: 'setup',\n      reg: /^setup:(\\w*)/,\n      format: 'setup:%s'\n    },\n    {\n      // a=connection:new\n      name: 'connectionType',\n      reg: /^connection:(new|existing)/,\n      format: 'connection:%s'\n    },\n    {\n      // a=mid:1\n      name: 'mid',\n      reg: /^mid:([^\\s]*)/,\n      format: 'mid:%s'\n    },\n    {\n      // a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a\n      push: 'msid',\n      reg: /^msid:([\\w-]+)(?: ([\\w-]+))?/,\n      names: ['id', 'appdata'],\n      format: 'msid:%s %s'\n    },\n    {\n      // a=ptime:20\n      name: 'ptime',\n      reg: /^ptime:(\\d*(?:\\.\\d*)*)/,\n      format: 'ptime:%d'\n    },\n    {\n      // a=maxptime:60\n      name: 'maxptime',\n      reg: /^maxptime:(\\d*(?:\\.\\d*)*)/,\n      format: 'maxptime:%d'\n    },\n    {\n      // a=sendrecv\n      name: 'direction',\n      reg: /^(sendrecv|recvonly|sendonly|inactive)/\n    },\n    {\n      // a=ice-lite\n      name: 'icelite',\n      reg: /^(ice-lite)/\n    },\n    {\n      // a=ice-ufrag:F7gI\n      name: 'iceUfrag',\n      reg: /^ice-ufrag:(\\S*)/,\n      format: 'ice-ufrag:%s'\n    },\n    {\n      // a=ice-pwd:x9cml/YzichV2+XlhiMu8g\n      name: 'icePwd',\n      reg: /^ice-pwd:(\\S*)/,\n      format: 'ice-pwd:%s'\n    },\n    {\n      // a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33\n      name: 'fingerprint',\n      reg: /^fingerprint:(\\S*) (\\S*)/,\n      names: ['type', 'hash'],\n      format: 'fingerprint:%s %s'\n    },\n    {\n      // a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host\n      // a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0 network-id 3 network-cost 10\n      // a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0 network-id 3 network-cost 10\n      // a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0 network-id 3 network-cost 10\n      // a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0 network-id 3 network-cost 10\n      push:'candidates',\n      reg: /^candidate:(\\S*) (\\d*) (\\S*) (\\d*) (\\S*) (\\d*) typ (\\S*)(?: raddr (\\S*) rport (\\d*))?(?: tcptype (\\S*))?(?: generation (\\d*))?(?: network-id (\\d*))?(?: network-cost (\\d*))?/,\n      names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation', 'network-id', 'network-cost'],\n      format: function (o) {\n        var str = 'candidate:%s %d %s %d %s %d typ %s';\n\n        str += (o.raddr != null) ? ' raddr %s rport %d' : '%v%v';\n\n        // NB: candidate has three optional chunks, so %void middles one if it's missing\n        str += (o.tcptype != null) ? ' tcptype %s' : '%v';\n\n        if (o.generation != null) {\n          str += ' generation %d';\n        }\n\n        str += (o['network-id'] != null) ? ' network-id %d' : '%v';\n        str += (o['network-cost'] != null) ? ' network-cost %d' : '%v';\n        return str;\n      }\n    },\n    {\n      // a=end-of-candidates (keep after the candidates line for readability)\n      name: 'endOfCandidates',\n      reg: /^(end-of-candidates)/\n    },\n    {\n      // a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...\n      name: 'remoteCandidates',\n      reg: /^remote-candidates:(.*)/,\n      format: 'remote-candidates:%s'\n    },\n    {\n      // a=ice-options:google-ice\n      name: 'iceOptions',\n      reg: /^ice-options:(\\S*)/,\n      format: 'ice-options:%s'\n    },\n    {\n      // a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1\n      push: 'ssrcs',\n      reg: /^ssrc:(\\d*) ([\\w_-]*)(?::(.*))?/,\n      names: ['id', 'attribute', 'value'],\n      format: function (o) {\n        var str = 'ssrc:%d';\n        if (o.attribute != null) {\n          str += ' %s';\n          if (o.value != null) {\n            str += ':%s';\n          }\n        }\n        return str;\n      }\n    },\n    {\n      // a=ssrc-group:FEC 1 2\n      // a=ssrc-group:FEC-FR 3004364195 1080772241\n      push: 'ssrcGroups',\n      // token-char = %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39 / %x41-5A / %x5E-7E\n      reg: /^ssrc-group:([\\x21\\x23\\x24\\x25\\x26\\x27\\x2A\\x2B\\x2D\\x2E\\w]*) (.*)/,\n      names: ['semantics', 'ssrcs'],\n      format: 'ssrc-group:%s %s'\n    },\n    {\n      // a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV\n      name: 'msidSemantic',\n      reg: /^msid-semantic:\\s?(\\w*) (\\S*)/,\n      names: ['semantic', 'token'],\n      format: 'msid-semantic: %s %s' // space after ':' is not accidental\n    },\n    {\n      // a=group:BUNDLE audio video\n      push: 'groups',\n      reg: /^group:(\\w*) (.*)/,\n      names: ['type', 'mids'],\n      format: 'group:%s %s'\n    },\n    {\n      // a=rtcp-mux\n      name: 'rtcpMux',\n      reg: /^(rtcp-mux)/\n    },\n    {\n      // a=rtcp-rsize\n      name: 'rtcpRsize',\n      reg: /^(rtcp-rsize)/\n    },\n    {\n      // a=sctpmap:5000 webrtc-datachannel 1024\n      name: 'sctpmap',\n      reg: /^sctpmap:([\\w_/]*) (\\S*)(?: (\\S*))?/,\n      names: ['sctpmapNumber', 'app', 'maxMessageSize'],\n      format: function (o) {\n        return (o.maxMessageSize != null)\n          ? 'sctpmap:%s %s %s'\n          : 'sctpmap:%s %s';\n      }\n    },\n    {\n      // a=x-google-flag:conference\n      name: 'xGoogleFlag',\n      reg: /^x-google-flag:([^\\s]*)/,\n      format: 'x-google-flag:%s'\n    },\n    {\n      // a=rid:1 send max-width=1280;max-height=720;max-fps=30;depend=0\n      push: 'rids',\n      reg: /^rid:([\\d\\w]+) (\\w+)(?: ([\\S| ]*))?/,\n      names: ['id', 'direction', 'params'],\n      format: function (o) {\n        return (o.params) ? 'rid:%s %s %s' : 'rid:%s %s';\n      }\n    },\n    {\n      // a=imageattr:97 send [x=800,y=640,sar=1.1,q=0.6] [x=480,y=320] recv [x=330,y=250]\n      // a=imageattr:* send [x=800,y=640] recv *\n      // a=imageattr:100 recv [x=320,y=240]\n      push: 'imageattrs',\n      reg: new RegExp(\n        // a=imageattr:97\n        '^imageattr:(\\\\d+|\\\\*)' +\n        // send [x=800,y=640,sar=1.1,q=0.6] [x=480,y=320]\n        '[\\\\s\\\\t]+(send|recv)[\\\\s\\\\t]+(\\\\*|\\\\[\\\\S+\\\\](?:[\\\\s\\\\t]+\\\\[\\\\S+\\\\])*)' +\n        // recv [x=330,y=250]\n        '(?:[\\\\s\\\\t]+(recv|send)[\\\\s\\\\t]+(\\\\*|\\\\[\\\\S+\\\\](?:[\\\\s\\\\t]+\\\\[\\\\S+\\\\])*))?'\n      ),\n      names: ['pt', 'dir1', 'attrs1', 'dir2', 'attrs2'],\n      format: function (o) {\n        return 'imageattr:%s %s %s' + (o.dir2 ? ' %s %s' : '');\n      }\n    },\n    {\n      // a=simulcast:send 1,2,3;~4,~5 recv 6;~7,~8\n      // a=simulcast:recv 1;4,5 send 6;7\n      name: 'simulcast',\n      reg: new RegExp(\n        // a=simulcast:\n        '^simulcast:' +\n        // send 1,2,3;~4,~5\n        '(send|recv) ([a-zA-Z0-9\\\\-_~;,]+)' +\n        // space + recv 6;~7,~8\n        '(?:\\\\s?(send|recv) ([a-zA-Z0-9\\\\-_~;,]+))?' +\n        // end\n        '$'\n      ),\n      names: ['dir1', 'list1', 'dir2', 'list2'],\n      format: function (o) {\n        return 'simulcast:%s %s' + (o.dir2 ? ' %s %s' : '');\n      }\n    },\n    {\n      // old simulcast draft 03 (implemented by Firefox)\n      //   https://tools.ietf.org/html/draft-ietf-mmusic-sdp-simulcast-03\n      // a=simulcast: recv pt=97;98 send pt=97\n      // a=simulcast: send rid=5;6;7 paused=6,7\n      name: 'simulcast_03',\n      reg: /^simulcast:[\\s\\t]+([\\S+\\s\\t]+)$/,\n      names: ['value'],\n      format: 'simulcast: %s'\n    },\n    {\n      // a=framerate:25\n      // a=framerate:29.97\n      name: 'framerate',\n      reg: /^framerate:(\\d+(?:$|\\.\\d+))/,\n      format: 'framerate:%s'\n    },\n    {\n      // RFC4570\n      // a=source-filter: incl IN IP4 239.5.2.31 10.1.15.5\n      name: 'sourceFilter',\n      reg: /^source-filter: *(excl|incl) (\\S*) (IP4|IP6|\\*) (\\S*) (.*)/,\n      names: ['filterMode', 'netType', 'addressTypes', 'destAddress', 'srcList'],\n      format: 'source-filter: %s %s %s %s %s'\n    },\n    {\n      // a=bundle-only\n      name: 'bundleOnly',\n      reg: /^(bundle-only)/\n    },\n    {\n      // a=label:1\n      name: 'label',\n      reg: /^label:(.+)/,\n      format: 'label:%s'\n    },\n    {\n      // RFC version 26 for SCTP over DTLS\n      // https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-26#section-5\n      name: 'sctpPort',\n      reg: /^sctp-port:(\\d+)$/,\n      format: 'sctp-port:%s'\n    },\n    {\n      // RFC version 26 for SCTP over DTLS\n      // https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-26#section-6\n      name: 'maxMessageSize',\n      reg: /^max-message-size:(\\d+)$/,\n      format: 'max-message-size:%s'\n    },\n    {\n      // RFC7273\n      // a=ts-refclk:ptp=IEEE1588-2008:39-A7-94-FF-FE-07-CB-D0:37\n      push:'tsRefClocks',\n      reg: /^ts-refclk:([^\\s=]*)(?:=(\\S*))?/,\n      names: ['clksrc', 'clksrcExt'],\n      format: function (o) {\n        return 'ts-refclk:%s' + (o.clksrcExt != null ? '=%s' : '');\n      }\n    },\n    {\n      // RFC7273\n      // a=mediaclk:direct=963214424\n      name:'mediaClk',\n      reg: /^mediaclk:(?:id=(\\S*))? *([^\\s=]*)(?:=(\\S*))?(?: *rate=(\\d+)\\/(\\d+))?/,\n      names: ['id', 'mediaClockName', 'mediaClockValue', 'rateNumerator', 'rateDenominator'],\n      format: function (o) {\n        var str = 'mediaclk:';\n        str += (o.id != null ? 'id=%s %s' : '%v%s');\n        str += (o.mediaClockValue != null ? '=%s' : '');\n        str += (o.rateNumerator != null ? ' rate=%s' : '');\n        str += (o.rateDenominator != null ? '/%s' : '');\n        return str;\n      }\n    },\n    {\n      // a=keywds:keywords\n      name: 'keywords',\n      reg: /^keywds:(.+)$/,\n      format: 'keywds:%s'\n    },\n    {\n      // a=content:main\n      name: 'content',\n      reg: /^content:(.+)/,\n      format: 'content:%s'\n    },\n    // BFCP https://tools.ietf.org/html/rfc4583\n    {\n      // a=floorctrl:c-s\n      name: 'bfcpFloorCtrl',\n      reg: /^floorctrl:(c-only|s-only|c-s)/,\n      format: 'floorctrl:%s'\n    },\n    {\n      // a=confid:1\n      name: 'bfcpConfId',\n      reg: /^confid:(\\d+)/,\n      format: 'confid:%s'\n    },\n    {\n      // a=userid:1\n      name: 'bfcpUserId',\n      reg: /^userid:(\\d+)/,\n      format: 'userid:%s'\n    },\n    {\n      // a=floorid:1\n      name: 'bfcpFloorId',\n      reg: /^floorid:(.+) (?:m-stream|mstrm):(.+)/,\n      names: ['id', 'mStream'],\n      format: 'floorid:%s mstrm:%s'\n    },\n    {\n      // any a= that we don't understand is kept verbatim on media.invalid\n      push: 'invalid',\n      names: ['value']\n    }\n  ]\n};\n\n// set sensible defaults to avoid polluting the grammar with boring details\nObject.keys(grammar).forEach(function (key) {\n  var objs = grammar[key];\n  objs.forEach(function (obj) {\n    if (!obj.reg) {\n      obj.reg = /(.*)/;\n    }\n    if (!obj.format) {\n      obj.format = '%s';\n    }\n  });\n});\n","var toIntIfInt = function (v) {\n  return String(Number(v)) === v ? Number(v) : v;\n};\n\nvar attachProperties = function (match, location, names, rawName) {\n  if (rawName && !names) {\n    location[rawName] = toIntIfInt(match[1]);\n  }\n  else {\n    for (var i = 0; i < names.length; i += 1) {\n      if (match[i+1] != null) {\n        location[names[i]] = toIntIfInt(match[i+1]);\n      }\n    }\n  }\n};\n\nvar parseReg = function (obj, location, content) {\n  var needsBlank = obj.name && obj.names;\n  if (obj.push && !location[obj.push]) {\n    location[obj.push] = [];\n  }\n  else if (needsBlank && !location[obj.name]) {\n    location[obj.name] = {};\n  }\n  var keyLocation = obj.push ?\n    {} :  // blank object that will be pushed\n    needsBlank ? location[obj.name] : location; // otherwise, named location or root\n\n  attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);\n\n  if (obj.push) {\n    location[obj.push].push(keyLocation);\n  }\n};\n\nvar grammar = require('./grammar');\nvar validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);\n\nexports.parse = function (sdp) {\n  var session = {}\n    , media = []\n    , location = session; // points at where properties go under (one of the above)\n\n  // parse lines we understand\n  sdp.split(/(\\r\\n|\\r|\\n)/).filter(validLine).forEach(function (l) {\n    var type = l[0];\n    var content = l.slice(2);\n    if (type === 'm') {\n      media.push({rtp: [], fmtp: []});\n      location = media[media.length-1]; // point at latest media line\n    }\n\n    for (var j = 0; j < (grammar[type] || []).length; j += 1) {\n      var obj = grammar[type][j];\n      if (obj.reg.test(content)) {\n        return parseReg(obj, location, content);\n      }\n    }\n  });\n\n  session.media = media; // link it up\n  return session;\n};\n\nvar paramReducer = function (acc, expr) {\n  var s = expr.split(/=(.+)/, 2);\n  if (s.length === 2) {\n    acc[s[0]] = toIntIfInt(s[1]);\n  } else if (s.length === 1 && expr.length > 1) {\n    acc[s[0]] = undefined;\n  }\n  return acc;\n};\n\nexports.parseParams = function (str) {\n  return str.split(/;\\s?/).reduce(paramReducer, {});\n};\n\n// For backward compatibility - alias will be removed in 3.0.0\nexports.parseFmtpConfig = exports.parseParams;\n\nexports.parsePayloads = function (str) {\n  return str.toString().split(' ').map(Number);\n};\n\nexports.parseRemoteCandidates = function (str) {\n  var candidates = [];\n  var parts = str.split(' ').map(toIntIfInt);\n  for (var i = 0; i < parts.length; i += 3) {\n    candidates.push({\n      component: parts[i],\n      ip: parts[i + 1],\n      port: parts[i + 2]\n    });\n  }\n  return candidates;\n};\n\nexports.parseImageAttributes = function (str) {\n  return str.split(' ').map(function (item) {\n    return item.substring(1, item.length-1).split(',').reduce(paramReducer, {});\n  });\n};\n\nexports.parseSimulcastStreamList = function (str) {\n  return str.split(';').map(function (stream) {\n    return stream.split(',').map(function (format) {\n      var scid, paused = false;\n\n      if (format[0] !== '~') {\n        scid = toIntIfInt(format);\n      } else {\n        scid = toIntIfInt(format.substring(1, format.length));\n        paused = true;\n      }\n\n      return {\n        scid: scid,\n        paused: paused\n      };\n    });\n  });\n};\n","var grammar = require('./grammar');\n\n// customized util.format - discards excess arguments and can void middle ones\nvar formatRegExp = /%[sdv%]/g;\nvar format = function (formatStr) {\n  var i = 1;\n  var args = arguments;\n  var len = args.length;\n  return formatStr.replace(formatRegExp, function (x) {\n    if (i >= len) {\n      return x; // missing argument\n    }\n    var arg = args[i];\n    i += 1;\n    switch (x) {\n    case '%%':\n      return '%';\n    case '%s':\n      return String(arg);\n    case '%d':\n      return Number(arg);\n    case '%v':\n      return '';\n    }\n  });\n  // NB: we discard excess arguments - they are typically undefined from makeLine\n};\n\nvar makeLine = function (type, obj, location) {\n  var str = obj.format instanceof Function ?\n    (obj.format(obj.push ? location : location[obj.name])) :\n    obj.format;\n\n  var args = [type + '=' + str];\n  if (obj.names) {\n    for (var i = 0; i < obj.names.length; i += 1) {\n      var n = obj.names[i];\n      if (obj.name) {\n        args.push(location[obj.name][n]);\n      }\n      else { // for mLine and push attributes\n        args.push(location[obj.names[i]]);\n      }\n    }\n  }\n  else {\n    args.push(location[obj.name]);\n  }\n  return format.apply(null, args);\n};\n\n// RFC specified order\n// TODO: extend this with all the rest\nvar defaultOuterOrder = [\n  'v', 'o', 's', 'i',\n  'u', 'e', 'p', 'c',\n  'b', 't', 'r', 'z', 'a'\n];\nvar defaultInnerOrder = ['i', 'c', 'b', 'a'];\n\n\nmodule.exports = function (session, opts) {\n  opts = opts || {};\n  // ensure certain properties exist\n  if (session.version == null) {\n    session.version = 0; // 'v=0' must be there (only defined version atm)\n  }\n  if (session.name == null) {\n    session.name = ' '; // 's= ' must be there if no meaningful name set\n  }\n  session.media.forEach(function (mLine) {\n    if (mLine.payloads == null) {\n      mLine.payloads = '';\n    }\n  });\n\n  var outerOrder = opts.outerOrder || defaultOuterOrder;\n  var innerOrder = opts.innerOrder || defaultInnerOrder;\n  var sdp = [];\n\n  // loop through outerOrder for matching properties on session\n  outerOrder.forEach(function (type) {\n    grammar[type].forEach(function (obj) {\n      if (obj.name in session && session[obj.name] != null) {\n        sdp.push(makeLine(type, obj, session));\n      }\n      else if (obj.push in session && session[obj.push] != null) {\n        session[obj.push].forEach(function (el) {\n          sdp.push(makeLine(type, obj, el));\n        });\n      }\n    });\n  });\n\n  // then for each media line, follow the innerOrder\n  session.media.forEach(function (mLine) {\n    sdp.push(makeLine('m', grammar.m[0], mLine));\n\n    innerOrder.forEach(function (type) {\n      grammar[type].forEach(function (obj) {\n        if (obj.name in mLine && mLine[obj.name] != null) {\n          sdp.push(makeLine(type, obj, mLine));\n        }\n        else if (obj.push in mLine && mLine[obj.push] != null) {\n          mLine[obj.push].forEach(function (el) {\n            sdp.push(makeLine(type, obj, el));\n          });\n        }\n      });\n    });\n  });\n\n  return sdp.join('\\r\\n') + '\\r\\n';\n};\n","var parser = require('./parser');\nvar writer = require('./writer');\nvar grammar = require('./grammar');\n\nexports.grammar = grammar;\nexports.write = writer;\nexports.parse = parser.parse;\nexports.parseParams = parser.parseParams;\nexports.parseFmtpConfig = parser.parseFmtpConfig; // Alias of parseParams().\nexports.parsePayloads = parser.parsePayloads;\nexports.parseRemoteCandidates = parser.parseRemoteCandidates;\nexports.parseImageAttributes = parser.parseImageAttributes;\nexports.parseSimulcastStreamList = parser.parseSimulcastStreamList;\n","/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Base64 encoding and decoding utilities\n */\n\nfunction toBase64(uint8Array, options) {\n  if (typeof uint8Array.toBase64 === \"function\") {\n    // Currently this is only supported in Firefox,\n    // but we match the options in the hope in the future we can rely on it for all environments.\n    // https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.prototype.tobase64\n    return uint8Array.toBase64(options);\n  }\n  var base64 = btoa(uint8Array.reduce((acc, current) => acc + String.fromCharCode(current), \"\"));\n  if (options.omitPadding) {\n    base64 = base64.replace(/={1,2}$/, \"\");\n  }\n  if (options.alphabet === \"base64url\") {\n    base64 = base64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n  }\n  return base64;\n}\n\n/**\n * Encode a typed array of uint8 as base64.\n * @param uint8Array - The data to encode.\n * @returns The base64.\n */\nexport function encodeBase64(uint8Array) {\n  return toBase64(uint8Array, {\n    alphabet: \"base64\",\n    omitPadding: false\n  });\n}\n\n/**\n * Encode a typed array of uint8 as unpadded base64.\n * @param uint8Array - The data to encode.\n * @returns The unpadded base64.\n */\nexport function encodeUnpaddedBase64(uint8Array) {\n  return toBase64(uint8Array, {\n    alphabet: \"base64\",\n    omitPadding: true\n  });\n}\n\n/**\n * Encode a typed array of uint8 as unpadded base64 using the URL-safe encoding.\n * @param uint8Array - The data to encode.\n * @returns The unpadded base64.\n */\nexport function encodeUnpaddedBase64Url(uint8Array) {\n  return toBase64(uint8Array, {\n    alphabet: \"base64url\",\n    omitPadding: true\n  });\n}\nfunction fromBase64(base64, options) {\n  if (typeof Uint8Array.fromBase64 === \"function\") {\n    // Currently this is only supported in Firefox,\n    // but we match the options in the hope in the future we can rely on it for all environments.\n    // https://tc39.es/proposal-arraybuffer-base64/spec/#sec-uint8array.frombase64\n    return Uint8Array.fromBase64(base64, options);\n  }\n  return Uint8Array.from(atob(base64), c => c.charCodeAt(0));\n}\n\n/**\n * Decode a base64 (or base64url) string to a typed array of uint8.\n * @param base64 - The base64 to decode.\n * @returns The decoded data.\n */\nexport function decodeBase64(base64) {\n  // The function requires us to select an alphabet, but we don't know if base64url was used so we convert.\n  return fromBase64(base64.replace(/-/g, \"+\").replace(/_/g, \"/\"), {\n    alphabet: \"base64\",\n    lastChunkHandling: \"loose\"\n  });\n}\n//# sourceMappingURL=base64.js.map","/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { encodeUnpaddedBase64Url } from \"./base64.js\";\n\n/**\n * String representing the lowercase latin alphabet for use in {@link secureRandomStringFrom}\n * (can be combined with other such exports or other characters by appending strings)\n */\nexport var LOWERCASE = \"abcdefghijklmnopqrstuvwxyz\";\n\n/**\n * String representing the uppercase latin alphabet for use in secureRandomStringFrom\n * (can be combined with other such exports or other characters by appending strings)\n */\nexport var UPPERCASE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n/**\n * String representing the arabic numerals for use in secureRandomStringFrom\n * (can be combined with other such exports or other characters by appending strings)\n */\nexport var DIGITS = \"0123456789\";\nexport function secureRandomBase64Url(len) {\n  var key = new Uint8Array(len);\n  globalThis.crypto.getRandomValues(key);\n  return encodeUnpaddedBase64Url(key);\n}\n\n/**\n * Generates a random string of uppercase and lowercase letters plus digits using a\n * cryptographically secure random number generator.\n * @param len The length of the string to generate\n * @returns Random string of uppercase and lowercase letters plus digits of length `len`\n */\nexport function secureRandomString(len) {\n  return secureRandomStringFrom(len, UPPERCASE + LOWERCASE + DIGITS);\n}\n\n/**\n * Generate a cryptographically secure random string using characters given.\n *\n * @param len - The length of the string to generate (must be positive and less than 32768).\n * @param chars - The characters to use in the random string (between 2 and 256 characters long).\n * @returns Random string of characters of length `len`.\n */\nexport function secureRandomStringFrom(len, chars) {\n  // This is intended for latin strings so 256 possibilities should be more than enough and\n  // means we can use random bytes, minimising the amount of entropy we need to ask for.\n  if (chars.length < 2 || chars.length > 256) {\n    throw new Error(\"Character set must be between 2 and 256 characters long\");\n  }\n  if (len < 1 || len > 32768) {\n    throw new Error(\"Requested random string length must be between 1 and 32768\");\n  }\n\n  // We'll generate random unsigned bytes, so get the largest number less than 256 that is a multiple\n  // of the length of the character set: We'll need to discard any random values that are larger than\n  // this as we can't possibly map them onto the character set while keeping each character equally\n  // likely to be chosen (minus 1 to convert to indices in a string). (Essentially, we're using a d8\n  // to choose between 7 possibilities and re-rolling on an 8, keeping all 7 outcomes equally likely.)\n  // Our random values must be strictly less than this\n  var randomValueCutoff = 256 - 256 % chars.length;\n\n  // Grab 30% more entropy than we need. This should be enough that we can discard the values that are\n  // too high without having to go back and grab more unless we're super unlucky.\n  var entropyBuffer = new Uint8Array(Math.floor(len * 1.3));\n  // Mark all of this buffer as used to start with (we haven't populated it with entropy yet) so it will\n  // be filled on the first iteration.\n  var entropyBufferPos = entropyBuffer.length;\n  var result = [];\n  while (result.length < len) {\n    if (entropyBufferPos === entropyBuffer.length) {\n      globalThis.crypto.getRandomValues(entropyBuffer);\n      entropyBufferPos = 0;\n    }\n    var randomByte = entropyBuffer[entropyBufferPos++];\n    if (randomByte < randomValueCutoff) {\n      result.push(chars[randomByte % chars.length]);\n    }\n  }\n  return result.join(\"\");\n}\n//# sourceMappingURL=randomstring.js.map","// allow non-camelcase as these are events type that go onto the wire\n/* eslint-disable camelcase */\n\n// TODO: Change to \"sdp_stream_metadata\" when MSC3077 is merged\nexport var SDPStreamMetadataKey = \"org.matrix.msc3077.sdp_stream_metadata\";\nexport var SDPStreamMetadataPurpose = /*#__PURE__*/function (SDPStreamMetadataPurpose) {\n  SDPStreamMetadataPurpose[\"Usermedia\"] = \"m.usermedia\";\n  SDPStreamMetadataPurpose[\"Screenshare\"] = \"m.screenshare\";\n  return SDPStreamMetadataPurpose;\n}({});\n\n/* eslint-enable camelcase */\n//# sourceMappingURL=callEventTypes.js.map","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar audioContext = null;\nvar refCount = 0;\n\n/**\n * Acquires a reference to the shared AudioContext.\n * It's highly recommended to reuse this AudioContext rather than creating your\n * own, because multiple AudioContexts can be problematic in some browsers.\n * Make sure to call releaseContext when you're done using it.\n * @returns The shared AudioContext\n */\nexport var acquireContext = () => {\n  if (audioContext === null) audioContext = new AudioContext();\n  refCount++;\n  return audioContext;\n};\n\n/**\n * Signals that one of the references to the shared AudioContext has been\n * released, allowing the context and associated hardware resources to be\n * cleaned up if nothing else is using it.\n */\nexport var releaseContext = () => {\n  refCount--;\n  if (refCount === 0) {\n    var _audioContext;\n    (_audioContext = audioContext) === null || _audioContext === void 0 || _audioContext.close();\n    audioContext = null;\n  }\n};\n//# sourceMappingURL=audioContext.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2021 Šimon Brandner <simon.bra.ag@gmail.com>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { SDPStreamMetadataPurpose } from \"./callEventTypes.js\";\nimport { acquireContext, releaseContext } from \"./audioContext.js\";\nimport { logger } from \"../logger.js\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.js\";\nimport { CallEvent, CallState } from \"./call.js\";\nvar POLLING_INTERVAL = 200; // ms\nexport var SPEAKING_THRESHOLD = -60; // dB\nvar SPEAKING_SAMPLE_COUNT = 8; // samples\n\nexport var CallFeedEvent = /*#__PURE__*/function (CallFeedEvent) {\n  CallFeedEvent[\"NewStream\"] = \"new_stream\";\n  CallFeedEvent[\"MuteStateChanged\"] = \"mute_state_changed\";\n  CallFeedEvent[\"LocalVolumeChanged\"] = \"local_volume_changed\";\n  CallFeedEvent[\"VolumeChanged\"] = \"volume_changed\";\n  CallFeedEvent[\"ConnectedChanged\"] = \"connected_changed\";\n  CallFeedEvent[\"Speaking\"] = \"speaking\";\n  CallFeedEvent[\"Disposed\"] = \"disposed\";\n  return CallFeedEvent;\n}({});\nexport class CallFeed extends TypedEventEmitter {\n  constructor(opts) {\n    super();\n    _defineProperty(this, \"stream\", void 0);\n    _defineProperty(this, \"sdpMetadataStreamId\", void 0);\n    _defineProperty(this, \"userId\", void 0);\n    _defineProperty(this, \"deviceId\", void 0);\n    _defineProperty(this, \"purpose\", void 0);\n    _defineProperty(this, \"speakingVolumeSamples\", void 0);\n    _defineProperty(this, \"client\", void 0);\n    _defineProperty(this, \"call\", void 0);\n    _defineProperty(this, \"roomId\", void 0);\n    _defineProperty(this, \"audioMuted\", void 0);\n    _defineProperty(this, \"videoMuted\", void 0);\n    _defineProperty(this, \"localVolume\", 1);\n    _defineProperty(this, \"measuringVolumeActivity\", false);\n    _defineProperty(this, \"audioContext\", void 0);\n    _defineProperty(this, \"analyser\", void 0);\n    _defineProperty(this, \"frequencyBinCount\", void 0);\n    _defineProperty(this, \"speakingThreshold\", SPEAKING_THRESHOLD);\n    _defineProperty(this, \"speaking\", false);\n    _defineProperty(this, \"volumeLooperTimeout\", void 0);\n    _defineProperty(this, \"_disposed\", false);\n    _defineProperty(this, \"_connected\", false);\n    _defineProperty(this, \"onAddTrack\", () => {\n      this.emit(CallFeedEvent.NewStream, this.stream);\n    });\n    _defineProperty(this, \"onCallState\", state => {\n      if (state === CallState.Connected) {\n        this.connected = true;\n      } else if (state === CallState.Connecting) {\n        this.connected = false;\n      }\n    });\n    _defineProperty(this, \"volumeLooper\", () => {\n      if (!this.analyser) return;\n      if (!this.measuringVolumeActivity) return;\n      this.analyser.getFloatFrequencyData(this.frequencyBinCount);\n      var maxVolume = -Infinity;\n      for (var volume of this.frequencyBinCount) {\n        if (volume > maxVolume) {\n          maxVolume = volume;\n        }\n      }\n      this.speakingVolumeSamples.shift();\n      this.speakingVolumeSamples.push(maxVolume);\n      this.emit(CallFeedEvent.VolumeChanged, maxVolume);\n      var newSpeaking = false;\n      for (var _volume of this.speakingVolumeSamples) {\n        if (_volume > this.speakingThreshold) {\n          newSpeaking = true;\n          break;\n        }\n      }\n      if (this.speaking !== newSpeaking) {\n        this.speaking = newSpeaking;\n        this.emit(CallFeedEvent.Speaking, this.speaking);\n      }\n      this.volumeLooperTimeout = setTimeout(this.volumeLooper, POLLING_INTERVAL);\n    });\n    this.client = opts.client;\n    this.call = opts.call;\n    this.roomId = opts.roomId;\n    this.userId = opts.userId;\n    this.deviceId = opts.deviceId;\n    this.purpose = opts.purpose;\n    this.audioMuted = opts.audioMuted;\n    this.videoMuted = opts.videoMuted;\n    this.speakingVolumeSamples = new Array(SPEAKING_SAMPLE_COUNT).fill(-Infinity);\n    this.sdpMetadataStreamId = opts.stream.id;\n    this.updateStream(null, opts.stream);\n    this.stream = opts.stream; // updateStream does this, but this makes TS happier\n\n    if (this.hasAudioTrack) {\n      this.initVolumeMeasuring();\n    }\n    if (opts.call) {\n      opts.call.addListener(CallEvent.State, this.onCallState);\n      this.onCallState(opts.call.state);\n    }\n  }\n  get connected() {\n    // Local feeds are always considered connected\n    return this.isLocal() || this._connected;\n  }\n  set connected(connected) {\n    this._connected = connected;\n    this.emit(CallFeedEvent.ConnectedChanged, this.connected);\n  }\n  get hasAudioTrack() {\n    return this.stream.getAudioTracks().length > 0;\n  }\n  updateStream(oldStream, newStream) {\n    if (newStream === oldStream) return;\n    var wasMeasuringVolumeActivity = this.measuringVolumeActivity;\n    if (oldStream) {\n      oldStream.removeEventListener(\"addtrack\", this.onAddTrack);\n      this.measureVolumeActivity(false);\n    }\n    this.stream = newStream;\n    newStream.addEventListener(\"addtrack\", this.onAddTrack);\n    if (this.hasAudioTrack) {\n      this.initVolumeMeasuring();\n      if (wasMeasuringVolumeActivity) this.measureVolumeActivity(true);\n    } else {\n      this.measureVolumeActivity(false);\n    }\n    this.emit(CallFeedEvent.NewStream, this.stream);\n  }\n  initVolumeMeasuring() {\n    if (!this.hasAudioTrack) return;\n    if (!this.audioContext) this.audioContext = acquireContext();\n    this.analyser = this.audioContext.createAnalyser();\n    this.analyser.fftSize = 512;\n    this.analyser.smoothingTimeConstant = 0.1;\n    var mediaStreamAudioSourceNode = this.audioContext.createMediaStreamSource(this.stream);\n    mediaStreamAudioSourceNode.connect(this.analyser);\n    this.frequencyBinCount = new Float32Array(this.analyser.frequencyBinCount);\n  }\n  /**\n   * Returns callRoom member\n   * @returns member of the callRoom\n   */\n  getMember() {\n    var _callRoom$getMember;\n    var callRoom = this.client.getRoom(this.roomId);\n    return (_callRoom$getMember = callRoom === null || callRoom === void 0 ? void 0 : callRoom.getMember(this.userId)) !== null && _callRoom$getMember !== void 0 ? _callRoom$getMember : null;\n  }\n\n  /**\n   * Returns true if CallFeed is local, otherwise returns false\n   * @returns is local?\n   */\n  isLocal() {\n    return this.userId === this.client.getUserId() && (this.deviceId === undefined || this.deviceId === this.client.getDeviceId());\n  }\n\n  /**\n   * Returns true if audio is muted or if there are no audio\n   * tracks, otherwise returns false\n   * @returns is audio muted?\n   */\n  isAudioMuted() {\n    return this.stream.getAudioTracks().length === 0 || this.audioMuted;\n  }\n\n  /**\n   * Returns true video is muted or if there are no video\n   * tracks, otherwise returns false\n   * @returns is video muted?\n   */\n  isVideoMuted() {\n    // We assume only one video track\n    return this.stream.getVideoTracks().length === 0 || this.videoMuted;\n  }\n  isSpeaking() {\n    return this.speaking;\n  }\n\n  /**\n   * Replaces the current MediaStream with a new one.\n   * The stream will be different and new stream as remote parties are\n   * concerned, but this can be used for convenience locally to set up\n   * volume listeners automatically on the new stream etc.\n   * @param newStream - new stream with which to replace the current one\n   */\n  setNewStream(newStream) {\n    this.updateStream(this.stream, newStream);\n  }\n\n  /**\n   * Set one or both of feed's internal audio and video video mute state\n   * Either value may be null to leave it as-is\n   * @param audioMuted - is the feed's audio muted?\n   * @param videoMuted - is the feed's video muted?\n   */\n  setAudioVideoMuted(audioMuted, videoMuted) {\n    if (audioMuted !== null) {\n      if (this.audioMuted !== audioMuted) {\n        this.speakingVolumeSamples.fill(-Infinity);\n      }\n      this.audioMuted = audioMuted;\n    }\n    if (videoMuted !== null) this.videoMuted = videoMuted;\n    this.emit(CallFeedEvent.MuteStateChanged, this.audioMuted, this.videoMuted);\n  }\n\n  /**\n   * Starts emitting volume_changed events where the emitter value is in decibels\n   * @param enabled - emit volume changes\n   */\n  measureVolumeActivity(enabled) {\n    if (enabled) {\n      if (!this.analyser || !this.frequencyBinCount || !this.hasAudioTrack) return;\n      this.measuringVolumeActivity = true;\n      this.volumeLooper();\n    } else {\n      this.measuringVolumeActivity = false;\n      this.speakingVolumeSamples.fill(-Infinity);\n      this.emit(CallFeedEvent.VolumeChanged, -Infinity);\n    }\n  }\n  setSpeakingThreshold(threshold) {\n    this.speakingThreshold = threshold;\n  }\n  clone() {\n    var mediaHandler = this.client.getMediaHandler();\n    var stream = this.stream.clone();\n    logger.log(\"CallFeed clone() cloning stream (originalStreamId=\".concat(this.stream.id, \", newStreamId\").concat(stream.id, \")\"));\n    if (this.purpose === SDPStreamMetadataPurpose.Usermedia) {\n      mediaHandler.userMediaStreams.push(stream);\n    } else {\n      mediaHandler.screensharingStreams.push(stream);\n    }\n    return new CallFeed({\n      client: this.client,\n      roomId: this.roomId,\n      userId: this.userId,\n      deviceId: this.deviceId,\n      stream,\n      purpose: this.purpose,\n      audioMuted: this.audioMuted,\n      videoMuted: this.videoMuted\n    });\n  }\n  dispose() {\n    var _this$stream, _this$call;\n    clearTimeout(this.volumeLooperTimeout);\n    (_this$stream = this.stream) === null || _this$stream === void 0 || _this$stream.removeEventListener(\"addtrack\", this.onAddTrack);\n    (_this$call = this.call) === null || _this$call === void 0 || _this$call.removeListener(CallEvent.State, this.onCallState);\n    if (this.audioContext) {\n      this.audioContext = undefined;\n      this.analyser = undefined;\n      releaseContext();\n    }\n    this._disposed = true;\n    this.emit(CallFeedEvent.Disposed);\n  }\n  get disposed() {\n    return this._disposed;\n  }\n  set disposed(value) {\n    this._disposed = value;\n  }\n  getLocalVolume() {\n    return this.localVolume;\n  }\n  setLocalVolume(localVolume) {\n    this.localVolume = localVolume;\n    this.emit(CallFeedEvent.LocalVolumeChanged, localVolume);\n  }\n}\n//# sourceMappingURL=callFeed.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"../logger.js\";\nimport { CallDirection, CallError, CallErrorCode, CallState, createNewMatrixCall } from \"./call.js\";\nimport { EventType } from \"../@types/event.js\";\nimport { ClientEvent } from \"../client.js\";\nimport { GroupCallErrorCode, GroupCallEvent, GroupCallUnknownDeviceError } from \"./groupCall.js\";\nimport { RoomEvent } from \"../models/room.js\";\n\n// Don't ring unless we'd be ringing for at least 3 seconds: the user needs some\n// time to press the 'accept' button\nvar RING_GRACE_PERIOD = 3000;\nexport var CallEventHandlerEvent = /*#__PURE__*/function (CallEventHandlerEvent) {\n  CallEventHandlerEvent[\"Incoming\"] = \"Call.incoming\";\n  return CallEventHandlerEvent;\n}({});\nexport class CallEventHandler {\n  constructor(client) {\n    // XXX: Most of these are only public because of the tests\n    _defineProperty(this, \"calls\", void 0);\n    _defineProperty(this, \"callEventBuffer\", void 0);\n    _defineProperty(this, \"nextSeqByCall\", new Map());\n    _defineProperty(this, \"toDeviceEventBuffers\", new Map());\n    _defineProperty(this, \"client\", void 0);\n    _defineProperty(this, \"candidateEventsByCall\", void 0);\n    _defineProperty(this, \"eventBufferPromiseChain\", void 0);\n    _defineProperty(this, \"onSync\", () => {\n      // Process the current event buffer and start queuing into a new one.\n      var currentEventBuffer = this.callEventBuffer;\n      this.callEventBuffer = [];\n\n      // Ensure correct ordering by only processing this queue after the previous one has finished processing\n      if (this.eventBufferPromiseChain) {\n        this.eventBufferPromiseChain = this.eventBufferPromiseChain.then(() => this.evaluateEventBuffer(currentEventBuffer));\n      } else {\n        this.eventBufferPromiseChain = this.evaluateEventBuffer(currentEventBuffer);\n      }\n    });\n    _defineProperty(this, \"onRoomTimeline\", event => {\n      this.callEventBuffer.push(event);\n    });\n    _defineProperty(this, \"onToDeviceEvent\", event => {\n      var content = event.getContent();\n      if (!content.call_id) {\n        this.callEventBuffer.push(event);\n        return;\n      }\n      if (!this.nextSeqByCall.has(content.call_id)) {\n        this.nextSeqByCall.set(content.call_id, 0);\n      }\n      if (content.seq === undefined) {\n        this.callEventBuffer.push(event);\n        return;\n      }\n      var nextSeq = this.nextSeqByCall.get(content.call_id) || 0;\n      if (content.seq !== nextSeq) {\n        if (!this.toDeviceEventBuffers.has(content.call_id)) {\n          this.toDeviceEventBuffers.set(content.call_id, []);\n        }\n        var buffer = this.toDeviceEventBuffers.get(content.call_id);\n        var index = buffer.findIndex(e => e.getContent().seq > content.seq);\n        if (index === -1) {\n          buffer.push(event);\n        } else {\n          buffer.splice(index, 0, event);\n        }\n      } else {\n        var callId = content.call_id;\n        this.callEventBuffer.push(event);\n        this.nextSeqByCall.set(callId, content.seq + 1);\n        var _buffer = this.toDeviceEventBuffers.get(callId);\n        var nextEvent = _buffer && _buffer.shift();\n        while (nextEvent && nextEvent.getContent().seq === this.nextSeqByCall.get(callId)) {\n          this.callEventBuffer.push(nextEvent);\n          this.nextSeqByCall.set(callId, nextEvent.getContent().seq + 1);\n          nextEvent = _buffer.shift();\n        }\n      }\n    });\n    this.client = client;\n    this.calls = new Map();\n    // The sync code always emits one event at a time, so it will patiently\n    // wait for us to finish processing a call invite before delivering the\n    // next event, even if that next event is a hangup. We therefore accumulate\n    // all our call events and then process them on the 'sync' event, ie.\n    // each time a sync has completed. This way, we can avoid emitting incoming\n    // call events if we get both the invite and answer/hangup in the same sync.\n    // This happens quite often, eg. replaying sync from storage, catchup sync\n    // after loading and after we've been offline for a bit.\n    this.callEventBuffer = [];\n    this.candidateEventsByCall = new Map();\n  }\n  start() {\n    this.client.on(ClientEvent.Sync, this.onSync);\n    this.client.on(RoomEvent.Timeline, this.onRoomTimeline);\n    this.client.on(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);\n  }\n  stop() {\n    this.client.removeListener(ClientEvent.Sync, this.onSync);\n    this.client.removeListener(RoomEvent.Timeline, this.onRoomTimeline);\n    this.client.removeListener(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);\n  }\n  evaluateEventBuffer(eventBuffer) {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      yield Promise.all(eventBuffer.map(event => _this.client.decryptEventIfNeeded(event)));\n      var callEvents = eventBuffer.filter(event => {\n        var eventType = event.getType();\n        return eventType.startsWith(\"m.call.\") || eventType.startsWith(\"org.matrix.call.\");\n      });\n      var ignoreCallIds = new Set();\n\n      // inspect the buffer and mark all calls which have been answered\n      // or hung up before passing them to the call event handler.\n      for (var event of callEvents) {\n        var eventType = event.getType();\n        if (eventType === EventType.CallAnswer || eventType === EventType.CallHangup) {\n          ignoreCallIds.add(event.getContent().call_id);\n        }\n      }\n\n      // Process call events in the order that they were received\n      for (var _event of callEvents) {\n        var _eventType = _event.getType();\n        var callId = _event.getContent().call_id;\n        if (_eventType === EventType.CallInvite && ignoreCallIds.has(callId)) {\n          // This call has previously been answered or hung up: ignore it\n          continue;\n        }\n        try {\n          yield _this.handleCallEvent(_event);\n        } catch (e) {\n          logger.error(\"CallEventHandler evaluateEventBuffer() caught exception handling call event\", e);\n        }\n      }\n    })();\n  }\n  handleCallEvent(event) {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      var _getGroupCallById;\n      _this2.client.emit(ClientEvent.ReceivedVoipEvent, event);\n      var content = event.getContent();\n      var callRoomId = event.getRoomId() || ((_getGroupCallById = _this2.client.groupCallEventHandler.getGroupCallById(content.conf_id)) === null || _getGroupCallById === void 0 || (_getGroupCallById = _getGroupCallById.room) === null || _getGroupCallById === void 0 ? void 0 : _getGroupCallById.roomId);\n      var groupCallId = content.conf_id;\n      var type = event.getType();\n      var senderId = event.getSender();\n      var call = content.call_id ? _this2.calls.get(content.call_id) : undefined;\n      var opponentDeviceId;\n      var groupCall;\n      if (groupCallId) {\n        groupCall = _this2.client.groupCallEventHandler.getGroupCallById(groupCallId);\n        if (!groupCall) {\n          logger.warn(\"CallEventHandler handleCallEvent() could not find a group call - ignoring event (groupCallId=\".concat(groupCallId, \", type=\").concat(type, \")\"));\n          return;\n        }\n        opponentDeviceId = content.device_id;\n        if (!opponentDeviceId) {\n          logger.warn(\"CallEventHandler handleCallEvent() could not find a device id - ignoring event (senderId=\".concat(senderId, \")\"));\n          groupCall.emit(GroupCallEvent.Error, new GroupCallUnknownDeviceError(senderId));\n          return;\n        }\n        if (content.dest_session_id !== _this2.client.getSessionId()) {\n          logger.warn(\"CallEventHandler handleCallEvent() call event does not match current session id - ignoring\");\n          return;\n        }\n      }\n      var weSentTheEvent = senderId === _this2.client.credentials.userId && (opponentDeviceId === undefined || opponentDeviceId === _this2.client.getDeviceId());\n      if (!callRoomId) return;\n      if (type === EventType.CallInvite) {\n        var _this2$client$getTurn, _createNewMatrixCall, _groupCall;\n        // ignore invites you send\n        if (weSentTheEvent) return;\n        // expired call\n        if (event.getLocalAge() > content.lifetime - RING_GRACE_PERIOD) return;\n        // stale/old invite event\n        if (call && call.state === CallState.Ended) return;\n        if (call) {\n          logger.warn(\"CallEventHandler handleCallEvent() already has a call but got an invite - clobbering (callId=\".concat(content.call_id, \")\"));\n        }\n        if (content.invitee && content.invitee !== _this2.client.getUserId()) {\n          return; // This invite was meant for another user in the room\n        }\n        var timeUntilTurnCresExpire = ((_this2$client$getTurn = _this2.client.getTurnServersExpiry()) !== null && _this2$client$getTurn !== void 0 ? _this2$client$getTurn : 0) - Date.now();\n        logger.info(\"CallEventHandler handleCallEvent() current turn creds expire in \" + timeUntilTurnCresExpire + \" ms\");\n        call = (_createNewMatrixCall = createNewMatrixCall(_this2.client, callRoomId, {\n          forceTURN: _this2.client.forceTURN,\n          opponentDeviceId,\n          groupCallId,\n          opponentSessionId: content.sender_session_id\n        })) !== null && _createNewMatrixCall !== void 0 ? _createNewMatrixCall : undefined;\n        if (!call) {\n          logger.log(\"CallEventHandler handleCallEvent() this client does not support WebRTC (callId=\".concat(content.call_id, \")\"));\n          // don't hang up the call: there could be other clients\n          // connected that do support WebRTC and declining the\n          // the call on their behalf would be really annoying.\n          return;\n        }\n        call.callId = content.call_id;\n        var stats = (_groupCall = groupCall) === null || _groupCall === void 0 ? void 0 : _groupCall.getGroupCallStats();\n        if (stats) {\n          call.initStats(stats);\n        }\n        try {\n          yield call.initWithInvite(event);\n        } catch (e) {\n          if (e instanceof CallError) {\n            if (e.code === GroupCallErrorCode.UnknownDevice) {\n              var _groupCall2;\n              (_groupCall2 = groupCall) === null || _groupCall2 === void 0 || _groupCall2.emit(GroupCallEvent.Error, e);\n            } else {\n              logger.error(e);\n            }\n          }\n        }\n        _this2.calls.set(call.callId, call);\n\n        // if we stashed candidate events for that call ID, play them back now\n        if (_this2.candidateEventsByCall.get(call.callId)) {\n          for (var ev of _this2.candidateEventsByCall.get(call.callId)) {\n            call.onRemoteIceCandidatesReceived(ev);\n          }\n        }\n\n        // Were we trying to call that user (room)?\n        var existingCall;\n        for (var thisCall of _this2.calls.values()) {\n          var _call$getOpponentMemb;\n          var isCalling = [CallState.WaitLocalMedia, CallState.CreateOffer, CallState.InviteSent].includes(thisCall.state);\n          if (call.roomId === thisCall.roomId && thisCall.direction === CallDirection.Outbound && ((_call$getOpponentMemb = call.getOpponentMember()) === null || _call$getOpponentMemb === void 0 ? void 0 : _call$getOpponentMemb.userId) === thisCall.invitee && isCalling) {\n            existingCall = thisCall;\n            break;\n          }\n        }\n        if (existingCall) {\n          if (existingCall.callId > call.callId) {\n            logger.log(\"CallEventHandler handleCallEvent() detected glare - answering incoming call and canceling outgoing call (incomingId=\".concat(call.callId, \", outgoingId=\").concat(existingCall.callId, \")\"));\n            existingCall.replacedBy(call);\n          } else {\n            logger.log(\"CallEventHandler handleCallEvent() detected glare - hanging up incoming call (incomingId=\".concat(call.callId, \", outgoingId=\").concat(existingCall.callId, \")\"));\n            call.hangup(CallErrorCode.Replaced, true);\n          }\n        } else {\n          _this2.client.emit(CallEventHandlerEvent.Incoming, call);\n        }\n        return;\n      } else if (type === EventType.CallCandidates) {\n        if (weSentTheEvent) return;\n        if (!call) {\n          // store the candidates; we may get a call eventually.\n          if (!_this2.candidateEventsByCall.has(content.call_id)) {\n            _this2.candidateEventsByCall.set(content.call_id, []);\n          }\n          _this2.candidateEventsByCall.get(content.call_id).push(event);\n        } else {\n          call.onRemoteIceCandidatesReceived(event);\n        }\n        return;\n      } else if ([EventType.CallHangup, EventType.CallReject].includes(type)) {\n        // Note that we also observe our own hangups here so we can see\n        // if we've already rejected a call that would otherwise be valid\n        if (!call) {\n          var _createNewMatrixCall2;\n          // if not live, store the fact that the call has ended because\n          // we're probably getting events backwards so\n          // the hangup will come before the invite\n          call = (_createNewMatrixCall2 = createNewMatrixCall(_this2.client, callRoomId, {\n            opponentDeviceId,\n            opponentSessionId: content.sender_session_id\n          })) !== null && _createNewMatrixCall2 !== void 0 ? _createNewMatrixCall2 : undefined;\n          if (call) {\n            call.callId = content.call_id;\n            call.initWithHangup(event);\n            _this2.calls.set(content.call_id, call);\n          }\n        } else {\n          if (call.state !== CallState.Ended) {\n            if (type === EventType.CallHangup) {\n              call.onHangupReceived(content);\n            } else {\n              call.onRejectReceived(content);\n            }\n\n            // @ts-expect-error typescript thinks the state can't be 'ended' because we're\n            // inside the if block where it wasn't, but it could have changed because\n            // on[Hangup|Reject]Received are side-effecty.\n            if (call.state === CallState.Ended) _this2.calls.delete(content.call_id);\n          }\n        }\n        return;\n      }\n\n      // The following events need a call and a peer connection\n      if (!call || !call.hasPeerConnection) {\n        logger.info(\"CallEventHandler handleCallEvent() discarding possible call event as we don't have a call (type=\".concat(type, \")\"));\n        return;\n      }\n      // Ignore remote echo\n      if (event.getContent().party_id === call.ourPartyId) return;\n      switch (type) {\n        case EventType.CallAnswer:\n          if (weSentTheEvent) {\n            if (call.state === CallState.Ringing) {\n              call.onAnsweredElsewhere(content);\n            }\n          } else {\n            call.onAnswerReceived(event);\n          }\n          break;\n        case EventType.CallSelectAnswer:\n          call.onSelectAnswerReceived(event);\n          break;\n        case EventType.CallNegotiate:\n          call.onNegotiateReceived(event);\n          break;\n        case EventType.CallAssertedIdentity:\n        case EventType.CallAssertedIdentityPrefix:\n          call.onAssertedIdentityReceived(event);\n          break;\n        case EventType.CallSDPStreamMetadataChanged:\n        case EventType.CallSDPStreamMetadataChangedPrefix:\n          call.onSDPStreamMetadataChangedReceived(event);\n          break;\n      }\n    })();\n  }\n}\n//# sourceMappingURL=callEventHandler.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2021 Šimon Brandner <simon.bra.ag@gmail.com>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { ClientEvent } from \"../client.js\";\nimport { GroupCall, GroupCallIntent, GroupCallType } from \"./groupCall.js\";\nimport { RoomStateEvent } from \"../models/room-state.js\";\nimport { logger } from \"../logger.js\";\nimport { EventType } from \"../@types/event.js\";\nimport { SyncState } from \"../sync.js\";\nexport var GroupCallEventHandlerEvent = /*#__PURE__*/function (GroupCallEventHandlerEvent) {\n  GroupCallEventHandlerEvent[\"Incoming\"] = \"GroupCall.incoming\";\n  GroupCallEventHandlerEvent[\"Outgoing\"] = \"GroupCall.outgoing\";\n  GroupCallEventHandlerEvent[\"Ended\"] = \"GroupCall.ended\";\n  GroupCallEventHandlerEvent[\"Participants\"] = \"GroupCall.participants\";\n  return GroupCallEventHandlerEvent;\n}({});\nexport class GroupCallEventHandler {\n  constructor(client) {\n    this.client = client;\n    _defineProperty(this, \"groupCalls\", new Map());\n    // roomId -> GroupCall\n    // All rooms we know about and whether we've seen a 'Room' event\n    // for them. The promise will be fulfilled once we've processed that\n    // event which means we're \"up to date\" on what calls are in a room\n    // and get\n    _defineProperty(this, \"roomDeferreds\", new Map());\n    _defineProperty(this, \"onRoomsChanged\", room => {\n      this.createGroupCallForRoom(room);\n    });\n    _defineProperty(this, \"onRoomStateChanged\", (event, state) => {\n      var eventType = event.getType();\n      if (eventType === EventType.GroupCallPrefix) {\n        var groupCallId = event.getStateKey();\n        var content = event.getContent();\n        var currentGroupCall = this.groupCalls.get(state.roomId);\n        if (!currentGroupCall && !content[\"m.terminated\"] && !event.isRedacted()) {\n          this.createGroupCallFromRoomStateEvent(event);\n        } else if (currentGroupCall && currentGroupCall.groupCallId === groupCallId) {\n          if (content[\"m.terminated\"] || event.isRedacted()) {\n            currentGroupCall.terminate(false);\n          } else if (content[\"m.type\"] !== currentGroupCall.type) {\n            // TODO: Handle the callType changing when the room state changes\n            logger.warn(\"GroupCallEventHandler onRoomStateChanged() currently does not support changing type (roomId=\".concat(state.roomId, \")\"));\n          }\n        } else if (currentGroupCall && currentGroupCall.groupCallId !== groupCallId) {\n          // TODO: Handle new group calls and multiple group calls\n          logger.warn(\"GroupCallEventHandler onRoomStateChanged() currently does not support multiple calls (roomId=\".concat(state.roomId, \")\"));\n        }\n      }\n    });\n  }\n  start() {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      // We wait until the client has started syncing for real.\n      // This is because we only support one call at a time, and want\n      // the latest. We therefore want the latest state of the room before\n      // we create a group call for the room so we can be fairly sure that\n      // the group call we create is really the latest one.\n      if (_this.client.getSyncState() !== SyncState.Syncing) {\n        logger.debug(\"GroupCallEventHandler start() waiting for client to start syncing\");\n        yield new Promise(resolve => {\n          var onSync = () => {\n            if (_this.client.getSyncState() === SyncState.Syncing) {\n              _this.client.off(ClientEvent.Sync, onSync);\n              return resolve();\n            }\n          };\n          _this.client.on(ClientEvent.Sync, onSync);\n        });\n      }\n      var rooms = _this.client.getRooms();\n      for (var room of rooms) {\n        _this.createGroupCallForRoom(room);\n      }\n      _this.client.on(ClientEvent.Room, _this.onRoomsChanged);\n      _this.client.on(RoomStateEvent.Events, _this.onRoomStateChanged);\n    })();\n  }\n  stop() {\n    this.client.removeListener(ClientEvent.Room, this.onRoomsChanged);\n    this.client.removeListener(RoomStateEvent.Events, this.onRoomStateChanged);\n  }\n  getRoomDeferred(roomId) {\n    var deferred = this.roomDeferreds.get(roomId);\n    if (deferred === undefined) {\n      var resolveFunc;\n      deferred = {\n        prom: new Promise(resolve => {\n          resolveFunc = resolve;\n        })\n      };\n      deferred.resolve = resolveFunc;\n      this.roomDeferreds.set(roomId, deferred);\n    }\n    return deferred;\n  }\n  waitUntilRoomReadyForGroupCalls(roomId) {\n    return this.getRoomDeferred(roomId).prom;\n  }\n  getGroupCallById(groupCallId) {\n    return [...this.groupCalls.values()].find(groupCall => groupCall.groupCallId === groupCallId);\n  }\n  createGroupCallForRoom(room) {\n    var callEvents = room.currentState.getStateEvents(EventType.GroupCallPrefix);\n    var sortedCallEvents = callEvents.sort((a, b) => b.getTs() - a.getTs());\n    for (var callEvent of sortedCallEvents) {\n      var content = callEvent.getContent();\n      if (content[\"m.terminated\"] || callEvent.isRedacted()) {\n        continue;\n      }\n      logger.debug(\"GroupCallEventHandler createGroupCallForRoom() choosing group call from possible calls (stateKey=\".concat(callEvent.getStateKey(), \", ts=\").concat(callEvent.getTs(), \", roomId=\").concat(room.roomId, \", numOfPossibleCalls=\").concat(callEvents.length, \")\"));\n      this.createGroupCallFromRoomStateEvent(callEvent);\n      break;\n    }\n    this.getRoomDeferred(room.roomId).resolve();\n  }\n  createGroupCallFromRoomStateEvent(event) {\n    var roomId = event.getRoomId();\n    var content = event.getContent();\n    var room = this.client.getRoom(roomId);\n    if (!room) {\n      logger.warn(\"GroupCallEventHandler createGroupCallFromRoomStateEvent() couldn't find room for call (roomId=\".concat(roomId, \")\"));\n      return;\n    }\n    var groupCallId = event.getStateKey();\n    var callType = content[\"m.type\"];\n    if (!Object.values(GroupCallType).includes(callType)) {\n      logger.warn(\"GroupCallEventHandler createGroupCallFromRoomStateEvent() received invalid call type (type=\".concat(callType, \", roomId=\").concat(roomId, \")\"));\n      return;\n    }\n    var callIntent = content[\"m.intent\"];\n    if (!Object.values(GroupCallIntent).includes(callIntent)) {\n      logger.warn(\"Received invalid group call intent (type=\".concat(callType, \", roomId=\").concat(roomId, \")\"));\n      return;\n    }\n    var isPtt = Boolean(content[\"io.element.ptt\"]);\n    var dataChannelOptions;\n    if (content !== null && content !== void 0 && content.dataChannelsEnabled && content !== null && content !== void 0 && content.dataChannelOptions) {\n      // Pull out just the dataChannelOptions we want to support.\n      var {\n        ordered,\n        maxPacketLifeTime,\n        maxRetransmits,\n        protocol\n      } = content.dataChannelOptions;\n      dataChannelOptions = {\n        ordered,\n        maxPacketLifeTime,\n        maxRetransmits,\n        protocol\n      };\n    }\n    var groupCall = new GroupCall(this.client, room, callType, isPtt, callIntent, groupCallId,\n    // Because without Media section a WebRTC connection is not possible, so need a RTCDataChannel to set up a\n    // no media WebRTC connection anyway.\n    (content === null || content === void 0 ? void 0 : content.dataChannelsEnabled) || this.client.isVoipWithNoMediaAllowed, dataChannelOptions, this.client.isVoipWithNoMediaAllowed, this.client.useLivekitForGroupCalls, content[\"io.element.livekit_service_url\"]);\n    this.groupCalls.set(room.roomId, groupCall);\n    this.client.emit(GroupCallEventHandlerEvent.Incoming, groupCall);\n    return groupCall;\n  }\n}\n//# sourceMappingURL=groupCallEventHandler.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class ConnectionStats {\n  constructor() {\n    _defineProperty(this, \"bandwidth\", {});\n    _defineProperty(this, \"bitrate\", {});\n    _defineProperty(this, \"packetLoss\", {});\n    _defineProperty(this, \"transport\", []);\n  }\n}\n//# sourceMappingURL=connectionStats.js.map","/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class ConnectionStatsBuilder {\n  static buildBandwidthReport(now) {\n    var availableIncomingBitrate = now.availableIncomingBitrate;\n    var availableOutgoingBitrate = now.availableOutgoingBitrate;\n    return {\n      download: availableIncomingBitrate ? Math.round(availableIncomingBitrate / 1000) : 0,\n      upload: availableOutgoingBitrate ? Math.round(availableOutgoingBitrate / 1000) : 0\n    };\n  }\n}\n//# sourceMappingURL=connectionStatsBuilder.js.map","export class TransportStatsBuilder {\n  static buildReport(report, now, conferenceStatsTransport, isFocus) {\n    var localUsedCandidate = report === null || report === void 0 ? void 0 : report.get(now.localCandidateId);\n    var remoteUsedCandidate = report === null || report === void 0 ? void 0 : report.get(now.remoteCandidateId);\n\n    // RTCIceCandidateStats\n    // https://w3c.github.io/webrtc-stats/#icecandidate-dict*\n    if (remoteUsedCandidate && localUsedCandidate) {\n      var remoteIpAddress = remoteUsedCandidate.ip !== undefined ? remoteUsedCandidate.ip : remoteUsedCandidate.address;\n      var remotePort = remoteUsedCandidate.port;\n      var ip = \"\".concat(remoteIpAddress, \":\").concat(remotePort);\n      var localIpAddress = localUsedCandidate.ip !== undefined ? localUsedCandidate.ip : localUsedCandidate.address;\n      var localPort = localUsedCandidate.port;\n      var localIp = \"\".concat(localIpAddress, \":\").concat(localPort);\n      var type = remoteUsedCandidate.protocol;\n\n      // Save the address unless it has been saved already.\n      if (!conferenceStatsTransport.some(t => t.ip === ip && t.type === type && t.localIp === localIp)) {\n        conferenceStatsTransport.push({\n          ip,\n          type,\n          localIp,\n          isFocus,\n          localCandidateType: localUsedCandidate.candidateType,\n          remoteCandidateType: remoteUsedCandidate.candidateType,\n          networkType: localUsedCandidate.networkType,\n          rtt: now.currentRoundTripTime ? now.currentRoundTripTime * 1000 : NaN\n        });\n      }\n    }\n    return conferenceStatsTransport;\n  }\n}\n//# sourceMappingURL=transportStatsBuilder.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { parse as parseSdp } from \"sdp-transform\";\nexport class MediaSsrcHandler {\n  constructor() {\n    _defineProperty(this, \"ssrcToMid\", {\n      local: new Map(),\n      remote: new Map()\n    });\n  }\n  findMidBySsrc(ssrc, type) {\n    var mid;\n    this.ssrcToMid[type].forEach((ssrcs, m) => {\n      if (ssrcs.find(s => s == ssrc)) {\n        mid = m;\n        return;\n      }\n    });\n    return mid;\n  }\n  parse(description, type) {\n    var sdp = parseSdp(description);\n    var ssrcToMid = new Map();\n    sdp.media.forEach(m => {\n      if (!!m.mid && m.type === \"video\" || m.type === \"audio\") {\n        var _m$ssrcs;\n        var ssrcs = [];\n        (_m$ssrcs = m.ssrcs) === null || _m$ssrcs === void 0 || _m$ssrcs.forEach(ssrc => {\n          if (ssrc.attribute === \"cname\") {\n            ssrcs.push(\"\".concat(ssrc.id));\n          }\n        });\n        ssrcToMid.set(\"\".concat(m.mid), ssrcs);\n      }\n    });\n    this.ssrcToMid[type] = ssrcToMid;\n  }\n  getSsrcToMidMap(type) {\n    return this.ssrcToMid[type];\n  }\n}\n//# sourceMappingURL=mediaSsrcHandler.js.map","/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class MediaTrackHandler {\n  constructor(pc) {\n    this.pc = pc;\n  }\n  getLocalTracks(kind) {\n    var isNotNullAndKind = track => {\n      return track !== null && track.kind === kind;\n    };\n    return this.pc.getTransceivers().filter(t => t.currentDirection === \"sendonly\" || t.currentDirection === \"sendrecv\").filter(t => t.sender !== null).map(t => t.sender).map(s => s.track).filter(isNotNullAndKind);\n  }\n  getTackById(trackId) {\n    return this.pc.getTransceivers().map(t => {\n      if ((t === null || t === void 0 ? void 0 : t.sender.track) !== null && t.sender.track.id === trackId) {\n        return t.sender.track;\n      }\n      if ((t === null || t === void 0 ? void 0 : t.receiver.track) !== null && t.receiver.track.id === trackId) {\n        return t.receiver.track;\n      }\n      return undefined;\n    }).find(t => t !== undefined);\n  }\n  getLocalTrackIdByMid(mid) {\n    var _transceiver$sender;\n    var transceiver = this.pc.getTransceivers().find(t => t.mid === mid);\n    return transceiver === null || transceiver === void 0 || (_transceiver$sender = transceiver.sender) === null || _transceiver$sender === void 0 || (_transceiver$sender = _transceiver$sender.track) === null || _transceiver$sender === void 0 ? void 0 : _transceiver$sender.id;\n  }\n  getRemoteTrackIdByMid(mid) {\n    var _transceiver$receiver;\n    var transceiver = this.pc.getTransceivers().find(t => t.mid === mid);\n    return transceiver === null || transceiver === void 0 || (_transceiver$receiver = transceiver.receiver) === null || _transceiver$receiver === void 0 || (_transceiver$receiver = _transceiver$receiver.track) === null || _transceiver$receiver === void 0 ? void 0 : _transceiver$receiver.id;\n  }\n  getActiveSimulcastStreams() {\n    //@TODO implement this right.. Check how many layer configured\n    return 3;\n  }\n  getTransceiverByTrackId(trackId) {\n    return this.pc.getTransceivers().find(t => {\n      return t.receiver.track.id === trackId || t.sender.track !== null && t.sender.track.id === trackId;\n    });\n  }\n}\n//# sourceMappingURL=mediaTrackHandler.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class MediaTrackStats {\n  constructor(trackId, type, kind) {\n    this.trackId = trackId;\n    this.type = type;\n    this.kind = kind;\n    _defineProperty(this, \"loss\", {\n      packetsTotal: 0,\n      packetsLost: 0,\n      isDownloadStream: false\n    });\n    _defineProperty(this, \"bitrate\", {\n      download: 0,\n      upload: 0\n    });\n    _defineProperty(this, \"resolution\", {\n      width: -1,\n      height: -1\n    });\n    _defineProperty(this, \"audioConcealment\", {\n      concealedAudio: 0,\n      totalAudioDuration: 0\n    });\n    _defineProperty(this, \"framerate\", 0);\n    _defineProperty(this, \"jitter\", 0);\n    _defineProperty(this, \"codec\", \"\");\n    _defineProperty(this, \"isAlive\", true);\n    _defineProperty(this, \"isMuted\", false);\n    _defineProperty(this, \"isEnabled\", true);\n  }\n  getType() {\n    return this.type;\n  }\n  setLoss(loss) {\n    this.loss = loss;\n  }\n  getLoss() {\n    return this.loss;\n  }\n  setResolution(resolution) {\n    this.resolution = resolution;\n  }\n  getResolution() {\n    return this.resolution;\n  }\n  setFramerate(framerate) {\n    this.framerate = framerate;\n  }\n  getFramerate() {\n    return this.framerate;\n  }\n  setBitrate(bitrate) {\n    this.bitrate = bitrate;\n  }\n  getBitrate() {\n    return this.bitrate;\n  }\n  setCodec(codecShortType) {\n    this.codec = codecShortType;\n    return true;\n  }\n  getCodec() {\n    return this.codec;\n  }\n  resetBitrate() {\n    this.bitrate = {\n      download: 0,\n      upload: 0\n    };\n  }\n  set alive(isAlive) {\n    this.isAlive = isAlive;\n  }\n\n  /**\n   * A MediaTrackState is alive if the corresponding MediaStreamTrack track bound to a transceiver and the\n   * MediaStreamTrack is in state MediaStreamTrack.readyState === live\n   */\n  get alive() {\n    return this.isAlive;\n  }\n  set muted(isMuted) {\n    this.isMuted = isMuted;\n  }\n\n  /**\n   * A MediaTrackState.isMuted corresponding to MediaStreamTrack.muted.\n   * But these values only match if MediaTrackState.isAlive.\n   */\n  get muted() {\n    return this.isMuted;\n  }\n  set enabled(isEnabled) {\n    this.isEnabled = isEnabled;\n  }\n\n  /**\n   * A MediaTrackState.isEnabled corresponding to MediaStreamTrack.enabled.\n   * But these values only match if MediaTrackState.isAlive.\n   */\n  get enabled() {\n    return this.isEnabled;\n  }\n  setJitter(jitter) {\n    this.jitter = jitter;\n  }\n\n  /**\n   * Jitter in milliseconds\n   */\n  getJitter() {\n    return this.jitter;\n  }\n\n  /**\n   * Audio concealment ration (conceled duration / total duration)\n   */\n  setAudioConcealment(concealedAudioDuration, totalAudioDuration) {\n    this.audioConcealment.concealedAudio = concealedAudioDuration;\n    this.audioConcealment.totalAudioDuration = totalAudioDuration;\n  }\n  getAudioConcealment() {\n    return this.audioConcealment;\n  }\n}\n//# sourceMappingURL=mediaTrackStats.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MediaTrackStats } from \"./mediaTrackStats.js\";\nexport class MediaTrackStatsHandler {\n  constructor(mediaSsrcHandler, mediaTrackHandler) {\n    this.mediaSsrcHandler = mediaSsrcHandler;\n    this.mediaTrackHandler = mediaTrackHandler;\n    _defineProperty(this, \"track2stats\", new Map());\n  }\n\n  /**\n   * Find tracks by rtc stats\n   * Argument report is any because the stats api is not consistent:\n   * For example `trackIdentifier`, `mid` not existing in every implementations\n   * https://www.w3.org/TR/webrtc-stats/#dom-rtcinboundrtpstreamstats\n   * https://developer.mozilla.org/en-US/docs/Web/API/RTCInboundRtpStreamStats\n   */\n  findTrack2Stats(report, type) {\n    var trackID;\n    if (report.trackIdentifier) {\n      trackID = report.trackIdentifier;\n    } else if (report.mid) {\n      trackID = type === \"remote\" ? this.mediaTrackHandler.getRemoteTrackIdByMid(report.mid) : this.mediaTrackHandler.getLocalTrackIdByMid(report.mid);\n    } else if (report.ssrc) {\n      var mid = this.mediaSsrcHandler.findMidBySsrc(report.ssrc, type);\n      if (!mid) {\n        return undefined;\n      }\n      trackID = type === \"remote\" ? this.mediaTrackHandler.getRemoteTrackIdByMid(report.mid) : this.mediaTrackHandler.getLocalTrackIdByMid(report.mid);\n    }\n    if (!trackID) {\n      return undefined;\n    }\n    var trackStats = this.track2stats.get(trackID);\n    if (!trackStats) {\n      var track = this.mediaTrackHandler.getTackById(trackID);\n      if (track !== undefined) {\n        var kind = track.kind === \"audio\" ? track.kind : \"video\";\n        trackStats = new MediaTrackStats(trackID, type, kind);\n        this.track2stats.set(trackID, trackStats);\n      } else {\n        return undefined;\n      }\n    }\n    return trackStats;\n  }\n  findLocalVideoTrackStats(report) {\n    var localVideoTracks = this.mediaTrackHandler.getLocalTracks(\"video\");\n    if (localVideoTracks.length === 0) {\n      return undefined;\n    }\n    return this.findTrack2Stats(report, \"local\");\n  }\n  getTrack2stats() {\n    return this.track2stats;\n  }\n  findTransceiverByTrackId(trackID) {\n    return this.mediaTrackHandler.getTransceiverByTrackId(trackID);\n  }\n}\n//# sourceMappingURL=mediaTrackStatsHandler.js.map","/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n    http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nexport class ValueFormatter {\n  static getNonNegativeValue(imput) {\n    var value = imput;\n    if (typeof value !== \"number\") {\n      value = Number(value);\n    }\n    if (isNaN(value)) {\n      return 0;\n    }\n    return Math.max(0, value);\n  }\n}\n//# sourceMappingURL=valueFormatter.js.map","import { ValueFormatter } from \"./valueFormatter.js\";\nexport class TrackStatsBuilder {\n  static buildFramerateResolution(trackStats, now) {\n    var resolution = {\n      height: now.frameHeight,\n      width: now.frameWidth\n    };\n    var frameRate = now.framesPerSecond;\n    if (resolution.height && resolution.width) {\n      trackStats.setResolution(resolution);\n    }\n    trackStats.setFramerate(Math.round(frameRate || 0));\n  }\n  static calculateSimulcastFramerate(trackStats, now, before, layer) {\n    var frameRate = trackStats.getFramerate();\n    if (!frameRate) {\n      if (before) {\n        var timeMs = now.timestamp - before.timestamp;\n        if (timeMs > 0 && now.framesSent) {\n          var numberOfFramesSinceBefore = now.framesSent - before.framesSent;\n          frameRate = numberOfFramesSinceBefore / timeMs * 1000;\n        }\n      }\n      if (!frameRate) {\n        return;\n      }\n    }\n\n    // Reset frame rate to 0 when video is suspended as a result of endpoint falling out of last-n.\n    frameRate = layer ? Math.round(frameRate / layer) : 0;\n    trackStats.setFramerate(frameRate);\n  }\n  static buildCodec(report, trackStats, now) {\n    var codec = report === null || report === void 0 ? void 0 : report.get(now.codecId);\n    if (codec) {\n      /**\n       * The mime type has the following form: video/VP8 or audio/ISAC,\n       * so we what to keep just the type after the '/', audio and video\n       * keys will be added on the processing side.\n       */\n      var codecShortType = codec.mimeType.split(\"/\")[1];\n      if (codecShortType) trackStats.setCodec(codecShortType);\n    }\n  }\n  static buildBitrateReceived(trackStats, now, before) {\n    trackStats.setBitrate({\n      download: TrackStatsBuilder.calculateBitrate(now.bytesReceived, before.bytesReceived, now.timestamp, before.timestamp),\n      upload: 0\n    });\n  }\n  static buildBitrateSend(trackStats, now, before) {\n    trackStats.setBitrate({\n      download: 0,\n      upload: this.calculateBitrate(now.bytesSent, before.bytesSent, now.timestamp, before.timestamp)\n    });\n  }\n  static buildPacketsLost(trackStats, now, before) {\n    var key = now.type === \"outbound-rtp\" ? \"packetsSent\" : \"packetsReceived\";\n    var packetsNow = now[key];\n    if (!packetsNow || packetsNow < 0) {\n      packetsNow = 0;\n    }\n    var packetsBefore = ValueFormatter.getNonNegativeValue(before[key]);\n    var packetsDiff = Math.max(0, packetsNow - packetsBefore);\n    var packetsLostNow = ValueFormatter.getNonNegativeValue(now.packetsLost);\n    var packetsLostBefore = ValueFormatter.getNonNegativeValue(before.packetsLost);\n    var packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);\n    trackStats.setLoss({\n      packetsTotal: packetsDiff + packetsLostDiff,\n      packetsLost: packetsLostDiff,\n      isDownloadStream: now.type !== \"outbound-rtp\"\n    });\n  }\n  static calculateBitrate(bytesNowAny, bytesBeforeAny, nowTimestamp, beforeTimestamp) {\n    var bytesNow = ValueFormatter.getNonNegativeValue(bytesNowAny);\n    var bytesBefore = ValueFormatter.getNonNegativeValue(bytesBeforeAny);\n    var bytesProcessed = Math.max(0, bytesNow - bytesBefore);\n    var timeMs = nowTimestamp - beforeTimestamp;\n    var bitrateKbps = 0;\n    if (timeMs > 0) {\n      bitrateKbps = Math.round(bytesProcessed * 8 / timeMs);\n    }\n    return bitrateKbps;\n  }\n  static setTrackStatsState(trackStats, transceiver) {\n    var _transceiver$sender;\n    if (transceiver === undefined) {\n      trackStats.alive = false;\n      return;\n    }\n    var track = trackStats.getType() === \"remote\" ? transceiver.receiver.track : transceiver === null || transceiver === void 0 || (_transceiver$sender = transceiver.sender) === null || _transceiver$sender === void 0 ? void 0 : _transceiver$sender.track;\n    if (track === undefined || track === null) {\n      trackStats.alive = false;\n      return;\n    }\n    if (track.readyState === \"ended\") {\n      trackStats.alive = false;\n      return;\n    }\n    trackStats.muted = track.muted;\n    trackStats.enabled = track.enabled;\n    trackStats.alive = true;\n  }\n  static buildTrackSummary(trackStatsList) {\n    var videoTrackSummary = {\n      count: 0,\n      muted: 0,\n      maxJitter: 0,\n      maxPacketLoss: 0,\n      concealedAudio: 0,\n      totalAudio: 0\n    };\n    var audioTrackSummary = {\n      count: 0,\n      muted: 0,\n      maxJitter: 0,\n      maxPacketLoss: 0,\n      concealedAudio: 0,\n      totalAudio: 0\n    };\n    var remoteTrackList = trackStatsList.filter(t => t.getType() === \"remote\");\n    var audioTrackList = remoteTrackList.filter(t => t.kind === \"audio\");\n    remoteTrackList.forEach(stats => {\n      var trackSummary = stats.kind === \"video\" ? videoTrackSummary : audioTrackSummary;\n      trackSummary.count++;\n      if (stats.alive && stats.muted) {\n        trackSummary.muted++;\n      }\n      if (trackSummary.maxJitter < stats.getJitter()) {\n        trackSummary.maxJitter = stats.getJitter();\n      }\n      if (trackSummary.maxPacketLoss < stats.getLoss().packetsLost) {\n        trackSummary.maxPacketLoss = stats.getLoss().packetsLost;\n      }\n      if (audioTrackList.length > 0) {\n        var _stats$getAudioConcea, _stats$getAudioConcea2;\n        trackSummary.concealedAudio += (_stats$getAudioConcea = stats.getAudioConcealment()) === null || _stats$getAudioConcea === void 0 ? void 0 : _stats$getAudioConcea.concealedAudio;\n        trackSummary.totalAudio += (_stats$getAudioConcea2 = stats.getAudioConcealment()) === null || _stats$getAudioConcea2 === void 0 ? void 0 : _stats$getAudioConcea2.totalAudioDuration;\n      }\n    });\n    return {\n      audioTrackSummary,\n      videoTrackSummary\n    };\n  }\n  static buildJitter(trackStats, statsReport) {\n    if (statsReport.type !== \"inbound-rtp\") {\n      return;\n    }\n    var jitterStr = statsReport === null || statsReport === void 0 ? void 0 : statsReport.jitter;\n    if (jitterStr !== undefined) {\n      var jitter = ValueFormatter.getNonNegativeValue(jitterStr);\n      trackStats.setJitter(Math.round(jitter * 1000));\n    } else {\n      trackStats.setJitter(-1);\n    }\n  }\n  static buildAudioConcealment(trackStats, statsReport) {\n    if (statsReport.type !== \"inbound-rtp\") {\n      return;\n    }\n    var msPerSample = 1000 * (statsReport === null || statsReport === void 0 ? void 0 : statsReport.totalSamplesDuration) / (statsReport === null || statsReport === void 0 ? void 0 : statsReport.totalSamplesReceived);\n    var concealedAudioDuration = msPerSample * (statsReport === null || statsReport === void 0 ? void 0 : statsReport.concealedSamples);\n    var totalAudioDuration = 1000 * (statsReport === null || statsReport === void 0 ? void 0 : statsReport.totalSamplesDuration);\n    trackStats.setAudioConcealment(concealedAudioDuration, totalAudioDuration);\n  }\n}\n//# sourceMappingURL=trackStatsBuilder.js.map","/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class ConnectionStatsReportBuilder {\n  static build(stats) {\n    var report = {};\n\n    // process stats\n    var totalPackets = {\n      download: 0,\n      upload: 0\n    };\n    var lostPackets = {\n      download: 0,\n      upload: 0\n    };\n    var bitrateDownload = 0;\n    var bitrateUpload = 0;\n    var resolutions = {\n      local: new Map(),\n      remote: new Map()\n    };\n    var framerates = {\n      local: new Map(),\n      remote: new Map()\n    };\n    var codecs = {\n      local: new Map(),\n      remote: new Map()\n    };\n    var jitter = new Map();\n    var audioConcealment = new Map();\n    var audioBitrateDownload = 0;\n    var audioBitrateUpload = 0;\n    var videoBitrateDownload = 0;\n    var videoBitrateUpload = 0;\n    var totalConcealedAudio = 0;\n    var totalAudioDuration = 0;\n    for (var [trackId, trackStats] of stats) {\n      // process packet loss stats\n      var loss = trackStats.getLoss();\n      var type = loss.isDownloadStream ? \"download\" : \"upload\";\n      totalPackets[type] += loss.packetsTotal;\n      lostPackets[type] += loss.packetsLost;\n\n      // process bitrate stats\n      bitrateDownload += trackStats.getBitrate().download;\n      bitrateUpload += trackStats.getBitrate().upload;\n\n      // collect resolutions and framerates\n      if (trackStats.kind === \"audio\") {\n        // process audio quality stats\n        var audioConcealmentForTrack = trackStats.getAudioConcealment();\n        totalConcealedAudio += audioConcealmentForTrack.concealedAudio;\n        totalAudioDuration += audioConcealmentForTrack.totalAudioDuration;\n        audioBitrateDownload += trackStats.getBitrate().download;\n        audioBitrateUpload += trackStats.getBitrate().upload;\n      } else {\n        videoBitrateDownload += trackStats.getBitrate().download;\n        videoBitrateUpload += trackStats.getBitrate().upload;\n      }\n      resolutions[trackStats.getType()].set(trackId, trackStats.getResolution());\n      framerates[trackStats.getType()].set(trackId, trackStats.getFramerate());\n      codecs[trackStats.getType()].set(trackId, trackStats.getCodec());\n      if (trackStats.getType() === \"remote\") {\n        jitter.set(trackId, trackStats.getJitter());\n        if (trackStats.kind === \"audio\") {\n          audioConcealment.set(trackId, trackStats.getAudioConcealment());\n        }\n      }\n      trackStats.resetBitrate();\n    }\n    report.bitrate = {\n      upload: bitrateUpload,\n      download: bitrateDownload\n    };\n    report.bitrate.audio = {\n      upload: audioBitrateUpload,\n      download: audioBitrateDownload\n    };\n    report.bitrate.video = {\n      upload: videoBitrateUpload,\n      download: videoBitrateDownload\n    };\n    report.packetLoss = {\n      total: ConnectionStatsReportBuilder.calculatePacketLoss(lostPackets.download + lostPackets.upload, totalPackets.download + totalPackets.upload),\n      download: ConnectionStatsReportBuilder.calculatePacketLoss(lostPackets.download, totalPackets.download),\n      upload: ConnectionStatsReportBuilder.calculatePacketLoss(lostPackets.upload, totalPackets.upload)\n    };\n    report.audioConcealment = audioConcealment;\n    report.totalAudioConcealment = {\n      concealedAudio: totalConcealedAudio,\n      totalAudioDuration\n    };\n    report.framerate = framerates;\n    report.resolution = resolutions;\n    report.codec = codecs;\n    report.jitter = jitter;\n    return report;\n  }\n  static calculatePacketLoss(lostPackets, totalPackets) {\n    if (!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0) {\n      return 0;\n    }\n    return Math.round(lostPackets / totalPackets * 100);\n  }\n}\n//# sourceMappingURL=connectionStatsReportBuilder.js.map","/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class CallFeedStatsReporter {\n  static buildCallFeedReport(callId, opponentMemberId, pc) {\n    var rtpTransceivers = pc.getTransceivers();\n    var transceiver = [];\n    var callFeeds = [];\n    rtpTransceivers.forEach(t => {\n      var _t$sender;\n      var sender = (_t$sender = t.sender) !== null && _t$sender !== void 0 && _t$sender.track ? CallFeedStatsReporter.buildTrackStats(t.sender.track, \"sender\") : null;\n      var receiver = CallFeedStatsReporter.buildTrackStats(t.receiver.track, \"receiver\");\n      transceiver.push({\n        mid: t.mid == null ? \"null\" : t.mid,\n        direction: t.direction,\n        currentDirection: t.currentDirection == null ? \"null\" : t.currentDirection,\n        sender,\n        receiver\n      });\n    });\n    return {\n      callId,\n      opponentMemberId,\n      transceiver,\n      callFeeds\n    };\n  }\n  static buildTrackStats(track) {\n    var _track$getSettings, _track$getConstraints;\n    var label = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : \"--\";\n    var settingDeviceId = (_track$getSettings = track.getSettings()) === null || _track$getSettings === void 0 ? void 0 : _track$getSettings.deviceId;\n    var constrainDeviceId = (_track$getConstraints = track.getConstraints()) === null || _track$getConstraints === void 0 ? void 0 : _track$getConstraints.deviceId;\n    return {\n      id: track.id,\n      kind: track.kind,\n      settingDeviceId: settingDeviceId !== null && settingDeviceId !== void 0 ? settingDeviceId : \"unknown\",\n      constrainDeviceId: constrainDeviceId !== null && constrainDeviceId !== void 0 ? constrainDeviceId : \"unknown\",\n      muted: track.muted,\n      enabled: track.enabled,\n      readyState: track.readyState,\n      label\n    };\n  }\n  static expandCallFeedReport(report, callFeeds) {\n    var prefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : \"unknown\";\n    callFeeds.forEach(feed => {\n      var audioTracks = feed.stream.getAudioTracks();\n      var videoTracks = feed.stream.getVideoTracks();\n      var audio = audioTracks.length > 0 ? CallFeedStatsReporter.buildTrackStats(feed.stream.getAudioTracks()[0], feed.purpose) : null;\n      var video = videoTracks.length > 0 ? CallFeedStatsReporter.buildTrackStats(feed.stream.getVideoTracks()[0], feed.purpose) : null;\n      var feedStats = {\n        stream: feed.stream.id,\n        type: feed.isLocal() ? \"local\" : \"remote\",\n        audio,\n        video,\n        purpose: feed.purpose,\n        prefix,\n        isVideoMuted: feed.isVideoMuted(),\n        isAudioMuted: feed.isAudioMuted()\n      };\n      report.callFeeds.push(feedStats);\n    });\n    return report;\n  }\n}\n//# sourceMappingURL=callFeedStatsReporter.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { ConnectionStats } from \"./connectionStats.js\";\nimport { ConnectionStatsBuilder } from \"./connectionStatsBuilder.js\";\nimport { TransportStatsBuilder } from \"./transportStatsBuilder.js\";\nimport { MediaSsrcHandler } from \"./media/mediaSsrcHandler.js\";\nimport { MediaTrackHandler } from \"./media/mediaTrackHandler.js\";\nimport { MediaTrackStatsHandler } from \"./media/mediaTrackStatsHandler.js\";\nimport { TrackStatsBuilder } from \"./trackStatsBuilder.js\";\nimport { ConnectionStatsReportBuilder } from \"./connectionStatsReportBuilder.js\";\nimport { ValueFormatter } from \"./valueFormatter.js\";\nimport { logger } from \"../../logger.js\";\nimport { CallFeedStatsReporter } from \"./callFeedStatsReporter.js\";\nexport class CallStatsReportGatherer {\n  constructor(callId, opponentMemberId, pc, emitter) {\n    var isFocus = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n    this.callId = callId;\n    this.opponentMemberId = opponentMemberId;\n    this.pc = pc;\n    this.emitter = emitter;\n    this.isFocus = isFocus;\n    _defineProperty(this, \"isActive\", true);\n    _defineProperty(this, \"previousStatsReport\", void 0);\n    _defineProperty(this, \"currentStatsReport\", void 0);\n    _defineProperty(this, \"connectionStats\", new ConnectionStats());\n    _defineProperty(this, \"trackStats\", void 0);\n    pc.addEventListener(\"signalingstatechange\", this.onSignalStateChange.bind(this));\n    this.trackStats = new MediaTrackStatsHandler(new MediaSsrcHandler(), new MediaTrackHandler(pc));\n  }\n  processStats(groupCallId, localUserId) {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      var summary = {\n        isFirstCollection: _this.previousStatsReport === undefined,\n        receivedMedia: 0,\n        receivedAudioMedia: 0,\n        receivedVideoMedia: 0,\n        audioTrackSummary: {\n          count: 0,\n          muted: 0,\n          maxPacketLoss: 0,\n          maxJitter: 0,\n          concealedAudio: 0,\n          totalAudio: 0\n        },\n        videoTrackSummary: {\n          count: 0,\n          muted: 0,\n          maxPacketLoss: 0,\n          maxJitter: 0,\n          concealedAudio: 0,\n          totalAudio: 0\n        }\n      };\n      if (_this.isActive) {\n        var statsPromise = _this.pc.getStats();\n        if (typeof (statsPromise === null || statsPromise === void 0 ? void 0 : statsPromise.then) === \"function\") {\n          return statsPromise.then(report => {\n            var _this$connectionStats, _this$connectionStats2;\n            // @ts-ignore\n            _this.currentStatsReport = typeof (report === null || report === void 0 ? void 0 : report.result) === \"function\" ? report.result() : report;\n            try {\n              _this.processStatsReport(groupCallId, localUserId);\n            } catch (error) {\n              _this.handleError(error);\n              return summary;\n            }\n            _this.previousStatsReport = _this.currentStatsReport;\n            summary.receivedMedia = _this.connectionStats.bitrate.download;\n            summary.receivedAudioMedia = ((_this$connectionStats = _this.connectionStats.bitrate.audio) === null || _this$connectionStats === void 0 ? void 0 : _this$connectionStats.download) || 0;\n            summary.receivedVideoMedia = ((_this$connectionStats2 = _this.connectionStats.bitrate.video) === null || _this$connectionStats2 === void 0 ? void 0 : _this$connectionStats2.download) || 0;\n            var trackSummary = TrackStatsBuilder.buildTrackSummary(Array.from(_this.trackStats.getTrack2stats().values()));\n            return _objectSpread(_objectSpread({}, summary), {}, {\n              audioTrackSummary: trackSummary.audioTrackSummary,\n              videoTrackSummary: trackSummary.videoTrackSummary\n            });\n          }).catch(error => {\n            _this.handleError(error);\n            return summary;\n          });\n        }\n        _this.isActive = false;\n      }\n      return Promise.resolve(summary);\n    })();\n  }\n  processStatsReport(groupCallId, localUserId) {\n    var _this$currentStatsRep;\n    var byteSentStatsReport = new Map();\n    byteSentStatsReport.callId = this.callId;\n    byteSentStatsReport.opponentMemberId = this.opponentMemberId;\n    (_this$currentStatsRep = this.currentStatsReport) === null || _this$currentStatsRep === void 0 || _this$currentStatsRep.forEach(now => {\n      var before = this.previousStatsReport ? this.previousStatsReport.get(now.id) : null;\n      // RTCIceCandidatePairStats - https://w3c.github.io/webrtc-stats/#candidatepair-dict*\n      if (now.type === \"candidate-pair\" && now.nominated && now.state === \"succeeded\") {\n        this.connectionStats.bandwidth = ConnectionStatsBuilder.buildBandwidthReport(now);\n        this.connectionStats.transport = TransportStatsBuilder.buildReport(this.currentStatsReport, now, this.connectionStats.transport, this.isFocus);\n\n        // RTCReceivedRtpStreamStats\n        // https://w3c.github.io/webrtc-stats/#receivedrtpstats-dict*\n        // RTCSentRtpStreamStats\n        // https://w3c.github.io/webrtc-stats/#sentrtpstats-dict*\n      } else if (now.type === \"inbound-rtp\" || now.type === \"outbound-rtp\") {\n        var trackStats = this.trackStats.findTrack2Stats(now, now.type === \"inbound-rtp\" ? \"remote\" : \"local\");\n        if (!trackStats) {\n          return;\n        }\n        if (before) {\n          TrackStatsBuilder.buildPacketsLost(trackStats, now, before);\n        }\n\n        // Get the resolution and framerate for only remote video sources here. For the local video sources,\n        // 'track' stats will be used since they have the updated resolution based on the simulcast streams\n        // currently being sent. Promise based getStats reports three 'outbound-rtp' streams and there will be\n        // more calculations needed to determine what is the highest resolution stream sent by the client if the\n        // 'outbound-rtp' stats are used.\n        if (now.type === \"inbound-rtp\") {\n          TrackStatsBuilder.buildFramerateResolution(trackStats, now);\n          if (before) {\n            TrackStatsBuilder.buildBitrateReceived(trackStats, now, before);\n          }\n          var ts = this.trackStats.findTransceiverByTrackId(trackStats.trackId);\n          TrackStatsBuilder.setTrackStatsState(trackStats, ts);\n          TrackStatsBuilder.buildJitter(trackStats, now);\n          TrackStatsBuilder.buildAudioConcealment(trackStats, now);\n        } else if (before) {\n          byteSentStatsReport.set(trackStats.trackId, ValueFormatter.getNonNegativeValue(now.bytesSent));\n          TrackStatsBuilder.buildBitrateSend(trackStats, now, before);\n        }\n        TrackStatsBuilder.buildCodec(this.currentStatsReport, trackStats, now);\n      } else if (now.type === \"track\" && now.kind === \"video\" && !now.remoteSource) {\n        var _trackStats = this.trackStats.findLocalVideoTrackStats(now);\n        if (!_trackStats) {\n          return;\n        }\n        TrackStatsBuilder.buildFramerateResolution(_trackStats, now);\n        TrackStatsBuilder.calculateSimulcastFramerate(_trackStats, now, before, this.trackStats.mediaTrackHandler.getActiveSimulcastStreams());\n      }\n    });\n    this.emitter.emitByteSendReport(byteSentStatsReport);\n    this.emitter.emitCallFeedReport(CallFeedStatsReporter.buildCallFeedReport(this.callId, this.opponentMemberId, this.pc));\n    this.processAndEmitConnectionStatsReport();\n  }\n  setActive(isActive) {\n    this.isActive = isActive;\n  }\n  getActive() {\n    return this.isActive;\n  }\n  handleError(error) {\n    this.isActive = false;\n    logger.warn(\"CallStatsReportGatherer \".concat(this.callId, \" processStatsReport fails and set to inactive \").concat(error));\n  }\n  processAndEmitConnectionStatsReport() {\n    var report = ConnectionStatsReportBuilder.build(this.trackStats.getTrack2stats());\n    report.callId = this.callId;\n    report.opponentMemberId = this.opponentMemberId;\n    this.connectionStats.bandwidth = report.bandwidth;\n    this.connectionStats.bitrate = report.bitrate;\n    this.connectionStats.packetLoss = report.packetLoss;\n    this.emitter.emitConnectionStatsReport(_objectSpread(_objectSpread({}, report), {}, {\n      transport: this.connectionStats.transport\n    }));\n    this.connectionStats.transport = [];\n  }\n  stopProcessingStats() {}\n  onSignalStateChange() {\n    if (this.pc.signalingState === \"stable\") {\n      if (this.pc.currentRemoteDescription) {\n        this.trackStats.mediaSsrcHandler.parse(this.pc.currentRemoteDescription.sdp, \"remote\");\n      }\n      if (this.pc.currentLocalDescription) {\n        this.trackStats.mediaSsrcHandler.parse(this.pc.currentLocalDescription.sdp, \"local\");\n      }\n    }\n  }\n  setOpponentMemberId(id) {\n    this.opponentMemberId = id;\n  }\n}\n//# sourceMappingURL=callStatsReportGatherer.js.map","/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport var StatsReport = /*#__PURE__*/function (StatsReport) {\n  StatsReport[\"CONNECTION_STATS\"] = \"StatsReport.connection_stats\";\n  StatsReport[\"CALL_FEED_REPORT\"] = \"StatsReport.call_feed_report\";\n  StatsReport[\"BYTE_SENT_STATS\"] = \"StatsReport.byte_sent_stats\";\n  StatsReport[\"SUMMARY_STATS\"] = \"StatsReport.summary_stats\";\n  return StatsReport;\n}({});\n\n/// ByteSentStatsReport ################################################################################################\n\n/// ConnectionStatsReport ##############################################################################################\n\n/// SummaryStatsReport #################################################################################################\n\n/// CallFeedReport #####################################################################################################\n//# sourceMappingURL=statsReport.js.map","/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { TypedEventEmitter } from \"../../models/typed-event-emitter.js\";\nimport { StatsReport } from \"./statsReport.js\";\nexport class StatsReportEmitter extends TypedEventEmitter {\n  emitByteSendReport(byteSentStats) {\n    this.emit(StatsReport.BYTE_SENT_STATS, byteSentStats);\n  }\n  emitConnectionStatsReport(report) {\n    this.emit(StatsReport.CONNECTION_STATS, report);\n  }\n  emitCallFeedReport(report) {\n    this.emit(StatsReport.CALL_FEED_REPORT, report);\n  }\n  emitSummaryStatsReport(report) {\n    this.emit(StatsReport.SUMMARY_STATS, report);\n  }\n}\n//# sourceMappingURL=statsReportEmitter.js.map","/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n    http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class SummaryStatsReportGatherer {\n  constructor(emitter) {\n    this.emitter = emitter;\n  }\n  build(allSummary) {\n    // Filter all stats which collect the first time webrtc stats.\n    // Because stats based on time interval and the first collection of a summery stats has no previous\n    // webrtcStats as basement all the calculation are 0. We don't want track the 0 stats.\n    var summary = allSummary.filter(s => !s.isFirstCollection);\n    var summaryTotalCount = summary.length;\n    // For counting the peer connections we also want to consider the ignored summaries\n    var peerConnectionsCount = allSummary.length;\n    if (summaryTotalCount === 0) {\n      return;\n    }\n    var summaryCounter = {\n      receivedAudio: 0,\n      receivedVideo: 0,\n      receivedMedia: 0,\n      concealedAudio: 0,\n      totalAudio: 0\n    };\n    var maxJitter = 0;\n    var maxPacketLoss = 0;\n    summary.forEach(stats => {\n      this.countTrackListReceivedMedia(summaryCounter, stats);\n      this.countConcealedAudio(summaryCounter, stats);\n      maxJitter = this.buildMaxJitter(maxJitter, stats);\n      maxPacketLoss = this.buildMaxPacketLoss(maxPacketLoss, stats);\n    });\n    var decimalPlaces = 5;\n    var report = {\n      percentageReceivedMedia: Number((summaryCounter.receivedMedia / summaryTotalCount).toFixed(decimalPlaces)),\n      percentageReceivedVideoMedia: Number((summaryCounter.receivedVideo / summaryTotalCount).toFixed(decimalPlaces)),\n      percentageReceivedAudioMedia: Number((summaryCounter.receivedAudio / summaryTotalCount).toFixed(decimalPlaces)),\n      maxJitter,\n      maxPacketLoss,\n      percentageConcealedAudio: Number(summaryCounter.totalAudio > 0 ? (summaryCounter.concealedAudio / summaryCounter.totalAudio).toFixed(decimalPlaces) : 0),\n      peerConnections: peerConnectionsCount\n    };\n    this.emitter.emitSummaryStatsReport(report);\n  }\n  static extendSummaryReport(report, callParticipants) {\n    // Calculate the actual number of devices based on the participants state event\n    // (this is used, to compare the expected participant count from the room state with the acutal peer connections)\n    // const devices = callParticipants.()\n    var devices = [];\n    var users = [];\n    for (var userEntry of callParticipants) {\n      users.push(userEntry);\n      for (var device of userEntry[1]) {\n        devices.push(device);\n      }\n    }\n    report.opponentDevicesInCall = Math.max(0, devices.length - 1);\n    report.opponentUsersInCall = Math.max(0, users.length - 1);\n    report.diffDevicesToPeerConnections = Math.max(0, devices.length - 1) - report.peerConnections;\n    report.ratioPeerConnectionToDevices = Math.max(0, devices.length - 1) == 0 ? 0 : report.peerConnections / (devices.length - 1);\n  }\n  countTrackListReceivedMedia(counter, stats) {\n    var hasReceivedAudio = false;\n    var hasReceivedVideo = false;\n    if (stats.receivedAudioMedia > 0 || stats.audioTrackSummary.count === 0) {\n      counter.receivedAudio++;\n      hasReceivedAudio = true;\n    }\n    if (stats.receivedVideoMedia > 0 || stats.videoTrackSummary.count === 0) {\n      counter.receivedVideo++;\n      hasReceivedVideo = true;\n    } else {\n      if (stats.videoTrackSummary.muted > 0 && stats.videoTrackSummary.muted === stats.videoTrackSummary.count) {\n        counter.receivedVideo++;\n        hasReceivedVideo = true;\n      }\n    }\n    if (hasReceivedVideo && hasReceivedAudio) {\n      counter.receivedMedia++;\n    }\n  }\n  buildMaxJitter(maxJitter, stats) {\n    if (maxJitter < stats.videoTrackSummary.maxJitter) {\n      maxJitter = stats.videoTrackSummary.maxJitter;\n    }\n    if (maxJitter < stats.audioTrackSummary.maxJitter) {\n      maxJitter = stats.audioTrackSummary.maxJitter;\n    }\n    return maxJitter;\n  }\n  buildMaxPacketLoss(maxPacketLoss, stats) {\n    if (maxPacketLoss < stats.videoTrackSummary.maxPacketLoss) {\n      maxPacketLoss = stats.videoTrackSummary.maxPacketLoss;\n    }\n    if (maxPacketLoss < stats.audioTrackSummary.maxPacketLoss) {\n      maxPacketLoss = stats.audioTrackSummary.maxPacketLoss;\n    }\n    return maxPacketLoss;\n  }\n  countConcealedAudio(summaryCounter, stats) {\n    summaryCounter.concealedAudio += stats.audioTrackSummary.concealedAudio;\n    summaryCounter.totalAudio += stats.audioTrackSummary.totalAudio;\n  }\n}\n//# sourceMappingURL=summaryStatsReportGatherer.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport { CallStatsReportGatherer } from \"./callStatsReportGatherer.js\";\nimport { StatsReportEmitter } from \"./statsReportEmitter.js\";\nimport { SummaryStatsReportGatherer } from \"./summaryStatsReportGatherer.js\";\nimport { logger } from \"../../logger.js\";\nexport class GroupCallStats {\n  constructor(groupCallId, userId) {\n    var interval = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10000;\n    this.groupCallId = groupCallId;\n    this.userId = userId;\n    this.interval = interval;\n    _defineProperty(this, \"timer\", void 0);\n    _defineProperty(this, \"gatherers\", new Map());\n    _defineProperty(this, \"reports\", new StatsReportEmitter());\n    _defineProperty(this, \"summaryStatsReportGatherer\", new SummaryStatsReportGatherer(this.reports));\n  }\n  start() {\n    if (this.timer === undefined && this.interval > 0) {\n      this.timer = setInterval(() => {\n        this.processStats();\n      }, this.interval);\n    }\n  }\n  stop() {\n    if (this.timer !== undefined) {\n      clearInterval(this.timer);\n      this.gatherers.forEach(c => c.stopProcessingStats());\n    }\n  }\n  hasStatsReportGatherer(callId) {\n    return this.gatherers.has(callId);\n  }\n  addStatsReportGatherer(callId, opponentMemberId, peerConnection) {\n    if (this.hasStatsReportGatherer(callId)) {\n      return false;\n    }\n    this.gatherers.set(callId, new CallStatsReportGatherer(callId, opponentMemberId, peerConnection, this.reports));\n    return true;\n  }\n  removeStatsReportGatherer(callId) {\n    return this.gatherers.delete(callId);\n  }\n  getStatsReportGatherer(callId) {\n    return this.hasStatsReportGatherer(callId) ? this.gatherers.get(callId) : undefined;\n  }\n  updateOpponentMember(callId, opponentMember) {\n    var _this$getStatsReportG;\n    (_this$getStatsReportG = this.getStatsReportGatherer(callId)) === null || _this$getStatsReportG === void 0 || _this$getStatsReportG.setOpponentMemberId(opponentMember);\n  }\n  processStats() {\n    var summary = [];\n    this.gatherers.forEach(c => {\n      summary.push(c.processStats(this.groupCallId, this.userId));\n    });\n    Promise.all(summary).then(s => this.summaryStatsReportGatherer.build(s)).catch(err => {\n      logger.error(\"Could not build summary stats report\", err);\n    });\n  }\n  setInterval(interval) {\n    this.interval = interval;\n  }\n}\n//# sourceMappingURL=groupCallStats.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.js\";\nimport { CallFeed, SPEAKING_THRESHOLD } from \"./callFeed.js\";\nimport { CallErrorCode, CallEvent, CallState, genCallID, setTracksEnabled, createNewMatrixCall, CallError } from \"./call.js\";\nimport { RoomStateEvent } from \"../models/room-state.js\";\nimport { logger } from \"../logger.js\";\nimport { ReEmitter } from \"../ReEmitter.js\";\nimport { SDPStreamMetadataPurpose } from \"./callEventTypes.js\";\nimport { EventType } from \"../@types/event.js\";\nimport { CallEventHandlerEvent } from \"./callEventHandler.js\";\nimport { GroupCallEventHandlerEvent } from \"./groupCallEventHandler.js\";\nimport { mapsEqual } from \"../utils.js\";\nimport { GroupCallStats } from \"./stats/groupCallStats.js\";\nimport { StatsReport } from \"./stats/statsReport.js\";\nimport { SummaryStatsReportGatherer } from \"./stats/summaryStatsReportGatherer.js\";\nimport { CallFeedStatsReporter } from \"./stats/callFeedStatsReporter.js\";\nimport { KnownMembership } from \"../@types/membership.js\";\nexport var GroupCallIntent = /*#__PURE__*/function (GroupCallIntent) {\n  GroupCallIntent[\"Ring\"] = \"m.ring\";\n  GroupCallIntent[\"Prompt\"] = \"m.prompt\";\n  GroupCallIntent[\"Room\"] = \"m.room\";\n  return GroupCallIntent;\n}({});\nexport var GroupCallType = /*#__PURE__*/function (GroupCallType) {\n  GroupCallType[\"Video\"] = \"m.video\";\n  GroupCallType[\"Voice\"] = \"m.voice\";\n  return GroupCallType;\n}({});\nexport var GroupCallTerminationReason = /*#__PURE__*/function (GroupCallTerminationReason) {\n  GroupCallTerminationReason[\"CallEnded\"] = \"call_ended\";\n  return GroupCallTerminationReason;\n}({});\n/**\n * Because event names are just strings, they do need\n * to be unique over all event types of event emitter.\n * Some objects could emit more then one set of events.\n */\nexport var GroupCallEvent = /*#__PURE__*/function (GroupCallEvent) {\n  GroupCallEvent[\"GroupCallStateChanged\"] = \"group_call_state_changed\";\n  GroupCallEvent[\"ActiveSpeakerChanged\"] = \"active_speaker_changed\";\n  GroupCallEvent[\"CallsChanged\"] = \"calls_changed\";\n  GroupCallEvent[\"UserMediaFeedsChanged\"] = \"user_media_feeds_changed\";\n  GroupCallEvent[\"ScreenshareFeedsChanged\"] = \"screenshare_feeds_changed\";\n  GroupCallEvent[\"LocalScreenshareStateChanged\"] = \"local_screenshare_state_changed\";\n  GroupCallEvent[\"LocalMuteStateChanged\"] = \"local_mute_state_changed\";\n  GroupCallEvent[\"ParticipantsChanged\"] = \"participants_changed\";\n  GroupCallEvent[\"Error\"] = \"group_call_error\";\n  return GroupCallEvent;\n}({});\nexport var GroupCallStatsReportEvent = /*#__PURE__*/function (GroupCallStatsReportEvent) {\n  GroupCallStatsReportEvent[\"ConnectionStats\"] = \"GroupCall.connection_stats\";\n  GroupCallStatsReportEvent[\"ByteSentStats\"] = \"GroupCall.byte_sent_stats\";\n  GroupCallStatsReportEvent[\"SummaryStats\"] = \"GroupCall.summary_stats\";\n  GroupCallStatsReportEvent[\"CallFeedStats\"] = \"GroupCall.call_feed_stats\";\n  return GroupCallStatsReportEvent;\n}({});\n\n/**\n * The final report-events that get consumed by client.\n */\n\nexport var GroupCallErrorCode = /*#__PURE__*/function (GroupCallErrorCode) {\n  GroupCallErrorCode[\"NoUserMedia\"] = \"no_user_media\";\n  GroupCallErrorCode[\"UnknownDevice\"] = \"unknown_device\";\n  GroupCallErrorCode[\"PlaceCallFailed\"] = \"place_call_failed\";\n  return GroupCallErrorCode;\n}({});\nexport class GroupCallError extends Error {\n  constructor(code, msg, err) {\n    // Still don't think there's any way to have proper nested errors\n    if (err) {\n      super(msg + \": \" + err);\n      _defineProperty(this, \"code\", void 0);\n    } else {\n      super(msg);\n      _defineProperty(this, \"code\", void 0);\n    }\n    this.code = code;\n  }\n}\nexport class GroupCallUnknownDeviceError extends GroupCallError {\n  constructor(userId) {\n    super(GroupCallErrorCode.UnknownDevice, \"No device found for \" + userId);\n    this.userId = userId;\n  }\n}\nexport class OtherUserSpeakingError extends Error {\n  constructor() {\n    super(\"Cannot unmute: another user is speaking\");\n  }\n}\nexport var GroupCallState = /*#__PURE__*/function (GroupCallState) {\n  GroupCallState[\"LocalCallFeedUninitialized\"] = \"local_call_feed_uninitialized\";\n  GroupCallState[\"InitializingLocalCallFeed\"] = \"initializing_local_call_feed\";\n  GroupCallState[\"LocalCallFeedInitialized\"] = \"local_call_feed_initialized\";\n  GroupCallState[\"Entered\"] = \"entered\";\n  GroupCallState[\"Ended\"] = \"ended\";\n  return GroupCallState;\n}({});\nvar DEVICE_TIMEOUT = 1000 * 60 * 60; // 1 hour\n\nfunction getCallUserId(call) {\n  var _call$getOpponentMemb;\n  return ((_call$getOpponentMemb = call.getOpponentMember()) === null || _call$getOpponentMemb === void 0 ? void 0 : _call$getOpponentMemb.userId) || call.invitee || null;\n}\nexport class GroupCall extends TypedEventEmitter {\n  constructor(client, room, type, isPtt, intent, groupCallId, dataChannelsEnabled, dataChannelOptions, isCallWithoutVideoAndAudio) {\n    var _room$currentState$ge, _room$currentState$ge2;\n    var useLivekit = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : false;\n    var livekitServiceURL = arguments.length > 10 ? arguments[10] : undefined;\n    super();\n    this.client = client;\n    this.room = room;\n    this.type = type;\n    this.isPtt = isPtt;\n    this.intent = intent;\n    this.dataChannelsEnabled = dataChannelsEnabled;\n    this.dataChannelOptions = dataChannelOptions;\n    this.useLivekit = useLivekit;\n    // Config\n    _defineProperty(this, \"activeSpeakerInterval\", 1000);\n    _defineProperty(this, \"retryCallInterval\", 5000);\n    _defineProperty(this, \"participantTimeout\", 1000 * 15);\n    _defineProperty(this, \"pttMaxTransmitTime\", 1000 * 20);\n    _defineProperty(this, \"activeSpeaker\", void 0);\n    _defineProperty(this, \"localCallFeed\", void 0);\n    _defineProperty(this, \"localScreenshareFeed\", void 0);\n    _defineProperty(this, \"localDesktopCapturerSourceId\", void 0);\n    _defineProperty(this, \"userMediaFeeds\", []);\n    _defineProperty(this, \"screenshareFeeds\", []);\n    _defineProperty(this, \"groupCallId\", void 0);\n    _defineProperty(this, \"allowCallWithoutVideoAndAudio\", void 0);\n    _defineProperty(this, \"calls\", new Map());\n    // user_id -> device_id -> MatrixCall\n    _defineProperty(this, \"callHandlers\", new Map());\n    // user_id -> device_id -> ICallHandlers\n    _defineProperty(this, \"activeSpeakerLoopInterval\", void 0);\n    _defineProperty(this, \"retryCallLoopInterval\", void 0);\n    _defineProperty(this, \"retryCallCounts\", new Map());\n    // user_id -> device_id -> count\n    _defineProperty(this, \"reEmitter\", void 0);\n    _defineProperty(this, \"transmitTimer\", null);\n    _defineProperty(this, \"participantsExpirationTimer\", null);\n    _defineProperty(this, \"resendMemberStateTimer\", null);\n    _defineProperty(this, \"initWithAudioMuted\", false);\n    _defineProperty(this, \"initWithVideoMuted\", false);\n    _defineProperty(this, \"initCallFeedPromise\", void 0);\n    _defineProperty(this, \"_livekitServiceURL\", void 0);\n    _defineProperty(this, \"stats\", void 0);\n    /**\n     * Configure default webrtc stats collection interval in ms\n     * Disable collecting webrtc stats by setting interval to 0\n     */\n    _defineProperty(this, \"statsCollectIntervalTime\", 0);\n    _defineProperty(this, \"onConnectionStats\", report => {\n      // Final emit of the summary event, to be consumed by the client\n      this.emit(GroupCallStatsReportEvent.ConnectionStats, {\n        report\n      });\n    });\n    _defineProperty(this, \"onByteSentStats\", report => {\n      // Final emit of the summary event, to be consumed by the client\n      this.emit(GroupCallStatsReportEvent.ByteSentStats, {\n        report\n      });\n    });\n    _defineProperty(this, \"onSummaryStats\", report => {\n      SummaryStatsReportGatherer.extendSummaryReport(report, this.participants);\n      // Final emit of the summary event, to be consumed by the client\n      this.emit(GroupCallStatsReportEvent.SummaryStats, {\n        report\n      });\n    });\n    _defineProperty(this, \"onCallFeedReport\", report => {\n      if (this.localCallFeed) {\n        report = CallFeedStatsReporter.expandCallFeedReport(report, [this.localCallFeed], \"from-local-feed\");\n      }\n      var callFeeds = [];\n      this.forEachCall(call => {\n        if (call.callId === report.callId) {\n          call.getFeeds().forEach(f => callFeeds.push(f));\n        }\n      });\n      report = CallFeedStatsReporter.expandCallFeedReport(report, callFeeds, \"from-call-feed\");\n      this.emit(GroupCallStatsReportEvent.CallFeedStats, {\n        report\n      });\n    });\n    _defineProperty(this, \"_state\", GroupCallState.LocalCallFeedUninitialized);\n    _defineProperty(this, \"_participants\", new Map());\n    _defineProperty(this, \"_creationTs\", null);\n    _defineProperty(this, \"_enteredViaAnotherSession\", false);\n    /*\n     * Call Setup\n     *\n     * There are two different paths for calls to be created:\n     * 1. Incoming calls triggered by the Call.incoming event.\n     * 2. Outgoing calls to the initial members of a room or new members\n     *    as they are observed by the RoomState.members event.\n     */\n    _defineProperty(this, \"onIncomingCall\", newCall => {\n      var _newCall$getOpponentM, _this$calls$get;\n      // The incoming calls may be for another room, which we will ignore.\n      if (newCall.roomId !== this.room.roomId) {\n        return;\n      }\n      if (newCall.state !== CallState.Ringing) {\n        logger.warn(\"GroupCall \".concat(this.groupCallId, \" onIncomingCall() incoming call no longer in ringing state - ignoring\"));\n        return;\n      }\n      if (!newCall.groupCallId || newCall.groupCallId !== this.groupCallId) {\n        logger.log(\"GroupCall \".concat(this.groupCallId, \" onIncomingCall() ignored because it doesn't match the current group call\"));\n        newCall.reject();\n        return;\n      }\n      var opponentUserId = (_newCall$getOpponentM = newCall.getOpponentMember()) === null || _newCall$getOpponentM === void 0 ? void 0 : _newCall$getOpponentM.userId;\n      if (opponentUserId === undefined) {\n        logger.warn(\"GroupCall \".concat(this.groupCallId, \" onIncomingCall() incoming call with no member - ignoring\"));\n        return;\n      }\n      if (this.useLivekit) {\n        logger.info(\"Received incoming call whilst in signaling-only mode! Ignoring.\");\n        return;\n      }\n      var deviceMap = (_this$calls$get = this.calls.get(opponentUserId)) !== null && _this$calls$get !== void 0 ? _this$calls$get : new Map();\n      var prevCall = deviceMap.get(newCall.getOpponentDeviceId());\n      if ((prevCall === null || prevCall === void 0 ? void 0 : prevCall.callId) === newCall.callId) return;\n      logger.log(\"GroupCall \".concat(this.groupCallId, \" onIncomingCall() incoming call (userId=\").concat(opponentUserId, \", callId=\").concat(newCall.callId, \")\"));\n      if (prevCall) prevCall.hangup(CallErrorCode.Replaced, false);\n      // We must do this before we start initialising / answering the call as we\n      // need to know it is the active call for this user+deviceId and to not ignore\n      // events from it.\n      deviceMap.set(newCall.getOpponentDeviceId(), newCall);\n      this.calls.set(opponentUserId, deviceMap);\n      this.initCall(newCall);\n      var feeds = this.getLocalFeeds().map(feed => feed.clone());\n      if (!this.callExpected(newCall)) {\n        // Disable our tracks for users not explicitly participating in the\n        // call but trying to receive the feeds\n        for (var feed of feeds) {\n          setTracksEnabled(feed.stream.getAudioTracks(), false);\n          setTracksEnabled(feed.stream.getVideoTracks(), false);\n        }\n      }\n      newCall.answerWithCallFeeds(feeds);\n      this.emit(GroupCallEvent.CallsChanged, this.calls);\n    });\n    _defineProperty(this, \"onRetryCallLoop\", () => {\n      var needsRetry = false;\n      for (var [{\n        userId: _userId\n      }, participantMap] of this.participants) {\n        var callMap = this.calls.get(_userId);\n        var retriesMap = this.retryCallCounts.get(_userId);\n        for (var [deviceId, participant] of participantMap) {\n          var _retriesMap$get, _retriesMap;\n          var call = callMap === null || callMap === void 0 ? void 0 : callMap.get(deviceId);\n          var retries = (_retriesMap$get = (_retriesMap = retriesMap) === null || _retriesMap === void 0 ? void 0 : _retriesMap.get(deviceId)) !== null && _retriesMap$get !== void 0 ? _retriesMap$get : 0;\n          if ((call === null || call === void 0 ? void 0 : call.getOpponentSessionId()) !== participant.sessionId && this.wantsOutgoingCall(_userId, deviceId) && retries < 3) {\n            if (retriesMap === undefined) {\n              retriesMap = new Map();\n              this.retryCallCounts.set(_userId, retriesMap);\n            }\n            retriesMap.set(deviceId, retries + 1);\n            needsRetry = true;\n          }\n        }\n      }\n      if (needsRetry) this.placeOutgoingCalls();\n    });\n    _defineProperty(this, \"onCallFeedsChanged\", call => {\n      var opponentMemberId = getCallUserId(call);\n      var opponentDeviceId = call.getOpponentDeviceId();\n      if (!opponentMemberId) {\n        throw new Error(\"Cannot change call feeds without user id\");\n      }\n      var currentUserMediaFeed = this.getUserMediaFeed(opponentMemberId, opponentDeviceId);\n      var remoteUsermediaFeed = call.remoteUsermediaFeed;\n      var remoteFeedChanged = remoteUsermediaFeed !== currentUserMediaFeed;\n      var deviceMap = this.calls.get(opponentMemberId);\n      var currentCallForUserDevice = deviceMap === null || deviceMap === void 0 ? void 0 : deviceMap.get(opponentDeviceId);\n      if ((currentCallForUserDevice === null || currentCallForUserDevice === void 0 ? void 0 : currentCallForUserDevice.callId) !== call.callId) {\n        // the call in question is not the current call for this user/deviceId\n        // so ignore feed events from it otherwise we'll remove our real feeds\n        return;\n      }\n      if (remoteFeedChanged) {\n        if (!currentUserMediaFeed && remoteUsermediaFeed) {\n          this.addUserMediaFeed(remoteUsermediaFeed);\n        } else if (currentUserMediaFeed && remoteUsermediaFeed) {\n          this.replaceUserMediaFeed(currentUserMediaFeed, remoteUsermediaFeed);\n        } else if (currentUserMediaFeed && !remoteUsermediaFeed) {\n          this.removeUserMediaFeed(currentUserMediaFeed);\n        }\n      }\n      var currentScreenshareFeed = this.getScreenshareFeed(opponentMemberId, opponentDeviceId);\n      var remoteScreensharingFeed = call.remoteScreensharingFeed;\n      var remoteScreenshareFeedChanged = remoteScreensharingFeed !== currentScreenshareFeed;\n      if (remoteScreenshareFeedChanged) {\n        if (!currentScreenshareFeed && remoteScreensharingFeed) {\n          this.addScreenshareFeed(remoteScreensharingFeed);\n        } else if (currentScreenshareFeed && remoteScreensharingFeed) {\n          this.replaceScreenshareFeed(currentScreenshareFeed, remoteScreensharingFeed);\n        } else if (currentScreenshareFeed && !remoteScreensharingFeed) {\n          this.removeScreenshareFeed(currentScreenshareFeed);\n        }\n      }\n    });\n    _defineProperty(this, \"onCallStateChanged\", (call, state, _oldState) => {\n      var _call$getOpponentMemb2;\n      if (state === CallState.Ended) return;\n      var audioMuted = this.localCallFeed.isAudioMuted();\n      if (call.localUsermediaStream && call.isMicrophoneMuted() !== audioMuted) {\n        call.setMicrophoneMuted(audioMuted);\n      }\n      var videoMuted = this.localCallFeed.isVideoMuted();\n      if (call.localUsermediaStream && call.isLocalVideoMuted() !== videoMuted) {\n        call.setLocalVideoMuted(videoMuted);\n      }\n      var opponentUserId = (_call$getOpponentMemb2 = call.getOpponentMember()) === null || _call$getOpponentMemb2 === void 0 ? void 0 : _call$getOpponentMemb2.userId;\n      if (state === CallState.Connected && opponentUserId) {\n        var retriesMap = this.retryCallCounts.get(opponentUserId);\n        retriesMap === null || retriesMap === void 0 || retriesMap.delete(call.getOpponentDeviceId());\n        if ((retriesMap === null || retriesMap === void 0 ? void 0 : retriesMap.size) === 0) this.retryCallCounts.delete(opponentUserId);\n      }\n    });\n    _defineProperty(this, \"onCallHangup\", call => {\n      var _call$getOpponentMemb3, _call$getOpponentMemb4;\n      if (call.hangupReason === CallErrorCode.Replaced) return;\n      var opponentUserId = (_call$getOpponentMemb3 = (_call$getOpponentMemb4 = call.getOpponentMember()) === null || _call$getOpponentMemb4 === void 0 ? void 0 : _call$getOpponentMemb4.userId) !== null && _call$getOpponentMemb3 !== void 0 ? _call$getOpponentMemb3 : this.room.getMember(call.invitee).userId;\n      var deviceMap = this.calls.get(opponentUserId);\n\n      // Sanity check that this call is in fact in the map\n      if ((deviceMap === null || deviceMap === void 0 ? void 0 : deviceMap.get(call.getOpponentDeviceId())) === call) {\n        this.disposeCall(call, call.hangupReason);\n        deviceMap.delete(call.getOpponentDeviceId());\n        if (deviceMap.size === 0) this.calls.delete(opponentUserId);\n        this.emit(GroupCallEvent.CallsChanged, this.calls);\n      }\n    });\n    _defineProperty(this, \"onCallReplaced\", (prevCall, newCall) => {\n      var opponentUserId = prevCall.getOpponentMember().userId;\n      var deviceMap = this.calls.get(opponentUserId);\n      if (deviceMap === undefined) {\n        deviceMap = new Map();\n        this.calls.set(opponentUserId, deviceMap);\n      }\n      prevCall.hangup(CallErrorCode.Replaced, false);\n      this.initCall(newCall);\n      deviceMap.set(prevCall.getOpponentDeviceId(), newCall);\n      this.emit(GroupCallEvent.CallsChanged, this.calls);\n    });\n    _defineProperty(this, \"onActiveSpeakerLoop\", () => {\n      var topAvg = undefined;\n      var nextActiveSpeaker = undefined;\n      for (var callFeed of this.userMediaFeeds) {\n        if (callFeed.isLocal() && this.userMediaFeeds.length > 1) continue;\n        var total = callFeed.speakingVolumeSamples.reduce((acc, volume) => acc + Math.max(volume, SPEAKING_THRESHOLD));\n        var avg = total / callFeed.speakingVolumeSamples.length;\n        if (!topAvg || avg > topAvg) {\n          topAvg = avg;\n          nextActiveSpeaker = callFeed;\n        }\n      }\n      if (nextActiveSpeaker && this.activeSpeaker !== nextActiveSpeaker && topAvg && topAvg > SPEAKING_THRESHOLD) {\n        this.activeSpeaker = nextActiveSpeaker;\n        this.emit(GroupCallEvent.ActiveSpeakerChanged, this.activeSpeaker);\n      }\n    });\n    _defineProperty(this, \"onRoomState\", () => this.updateParticipants());\n    _defineProperty(this, \"onParticipantsChanged\", () => {\n      // Re-run setTracksEnabled on all calls, so that participants that just\n      // left get denied access to our media, and participants that just\n      // joined get granted access\n      this.forEachCall(call => {\n        var expected = this.callExpected(call);\n        for (var feed of call.getLocalFeeds()) {\n          setTracksEnabled(feed.stream.getAudioTracks(), !feed.isAudioMuted() && expected);\n          setTracksEnabled(feed.stream.getVideoTracks(), !feed.isVideoMuted() && expected);\n        }\n      });\n      if (this.state === GroupCallState.Entered && !this.useLivekit) this.placeOutgoingCalls();\n\n      // Update the participants stored in the stats object\n    });\n    _defineProperty(this, \"onStateChanged\", (newState, oldState) => {\n      if (newState === GroupCallState.Entered || oldState === GroupCallState.Entered || newState === GroupCallState.Ended) {\n        // We either entered, left, or ended the call\n        this.updateParticipants();\n        this.updateMemberState().catch(e => logger.error(\"GroupCall \".concat(this.groupCallId, \" onStateChanged() failed to update member state devices\\\"\"), e));\n      }\n    });\n    _defineProperty(this, \"onLocalFeedsChanged\", () => {\n      if (this.state === GroupCallState.Entered) {\n        this.updateMemberState().catch(e => logger.error(\"GroupCall \".concat(this.groupCallId, \" onLocalFeedsChanged() failed to update member state feeds\"), e));\n      }\n    });\n    this.reEmitter = new ReEmitter(this);\n    this.groupCallId = groupCallId !== null && groupCallId !== void 0 ? groupCallId : genCallID();\n    this._livekitServiceURL = livekitServiceURL;\n    this.creationTs = (_room$currentState$ge = (_room$currentState$ge2 = room.currentState.getStateEvents(EventType.GroupCallPrefix, this.groupCallId)) === null || _room$currentState$ge2 === void 0 ? void 0 : _room$currentState$ge2.getTs()) !== null && _room$currentState$ge !== void 0 ? _room$currentState$ge : null;\n    this.updateParticipants();\n    room.on(RoomStateEvent.Update, this.onRoomState);\n    this.on(GroupCallEvent.ParticipantsChanged, this.onParticipantsChanged);\n    this.on(GroupCallEvent.GroupCallStateChanged, this.onStateChanged);\n    this.on(GroupCallEvent.LocalScreenshareStateChanged, this.onLocalFeedsChanged);\n    this.allowCallWithoutVideoAndAudio = !!isCallWithoutVideoAndAudio;\n  }\n  create() {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      _this.creationTs = Date.now();\n      _this.client.groupCallEventHandler.groupCalls.set(_this.room.roomId, _this);\n      _this.client.emit(GroupCallEventHandlerEvent.Outgoing, _this);\n      yield _this.sendCallStateEvent();\n      return _this;\n    })();\n  }\n  sendCallStateEvent() {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      var groupCallState = {\n        \"m.intent\": _this2.intent,\n        \"m.type\": _this2.type,\n        \"io.element.ptt\": _this2.isPtt,\n        // TODO: Specify data-channels better\n        \"dataChannelsEnabled\": _this2.dataChannelsEnabled,\n        \"dataChannelOptions\": _this2.dataChannelsEnabled ? _this2.dataChannelOptions : undefined\n      };\n      if (_this2.livekitServiceURL) {\n        groupCallState[\"io.element.livekit_service_url\"] = _this2.livekitServiceURL;\n      }\n      yield _this2.client.sendStateEvent(_this2.room.roomId, EventType.GroupCallPrefix, groupCallState, _this2.groupCallId);\n    })();\n  }\n  get livekitServiceURL() {\n    return this._livekitServiceURL;\n  }\n  updateLivekitServiceURL(newURL) {\n    this._livekitServiceURL = newURL;\n    return this.sendCallStateEvent();\n  }\n  /**\n   * The group call's state.\n   */\n  get state() {\n    return this._state;\n  }\n  set state(value) {\n    var prevValue = this._state;\n    if (value !== prevValue) {\n      this._state = value;\n      this.emit(GroupCallEvent.GroupCallStateChanged, value, prevValue);\n    }\n  }\n  /**\n   * The current participants in the call, as a map from members to device IDs\n   * to participant info.\n   */\n  get participants() {\n    return this._participants;\n  }\n  set participants(value) {\n    var prevValue = this._participants;\n    var participantStateEqual = (x, y) => x.sessionId === y.sessionId && x.screensharing === y.screensharing;\n    var deviceMapsEqual = (x, y) => mapsEqual(x, y, participantStateEqual);\n\n    // Only update if the map actually changed\n    if (!mapsEqual(value, prevValue, deviceMapsEqual)) {\n      this._participants = value;\n      this.emit(GroupCallEvent.ParticipantsChanged, value);\n    }\n  }\n  /**\n   * The timestamp at which the call was created, or null if it has not yet\n   * been created.\n   */\n  get creationTs() {\n    return this._creationTs;\n  }\n  set creationTs(value) {\n    this._creationTs = value;\n  }\n  /**\n   * Whether the local device has entered this call via another session, such\n   * as a widget.\n   */\n  get enteredViaAnotherSession() {\n    return this._enteredViaAnotherSession;\n  }\n  set enteredViaAnotherSession(value) {\n    this._enteredViaAnotherSession = value;\n    this.updateParticipants();\n  }\n\n  /**\n   * Executes the given callback on all calls in this group call.\n   * @param f - The callback.\n   */\n  forEachCall(f) {\n    for (var deviceMap of this.calls.values()) {\n      for (var call of deviceMap.values()) f(call);\n    }\n  }\n  getLocalFeeds() {\n    var feeds = [];\n    if (this.localCallFeed) feeds.push(this.localCallFeed);\n    if (this.localScreenshareFeed) feeds.push(this.localScreenshareFeed);\n    return feeds;\n  }\n  hasLocalParticipant() {\n    var _this$participants$ge, _this$participants$ge2;\n    return (_this$participants$ge = (_this$participants$ge2 = this.participants.get(this.room.getMember(this.client.getUserId()))) === null || _this$participants$ge2 === void 0 ? void 0 : _this$participants$ge2.has(this.client.getDeviceId())) !== null && _this$participants$ge !== void 0 ? _this$participants$ge : false;\n  }\n\n  /**\n   * Determines whether the given call is one that we were expecting to exist\n   * given our knowledge of who is participating in the group call.\n   */\n  callExpected(call) {\n    var _this$participants$ge3;\n    var userId = getCallUserId(call);\n    var member = userId === null ? null : this.room.getMember(userId);\n    var deviceId = call.getOpponentDeviceId();\n    return member !== null && deviceId !== undefined && ((_this$participants$ge3 = this.participants.get(member)) === null || _this$participants$ge3 === void 0 ? void 0 : _this$participants$ge3.get(deviceId)) !== undefined;\n  }\n  initLocalCallFeed() {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      if (_this3.useLivekit) {\n        logger.info(\"Livekit group call: not starting local call feed.\");\n        return;\n      }\n      if (_this3.state !== GroupCallState.LocalCallFeedUninitialized) {\n        throw new Error(\"Cannot initialize local call feed in the \\\"\".concat(_this3.state, \"\\\" state.\"));\n      }\n      _this3.state = GroupCallState.InitializingLocalCallFeed;\n\n      // wraps the real method to serialise calls, because we don't want to try starting\n      // multiple call feeds at once\n      if (_this3.initCallFeedPromise) return _this3.initCallFeedPromise;\n      try {\n        _this3.initCallFeedPromise = _this3.initLocalCallFeedInternal();\n        yield _this3.initCallFeedPromise;\n      } finally {\n        _this3.initCallFeedPromise = undefined;\n      }\n    })();\n  }\n  initLocalCallFeedInternal() {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      logger.log(\"GroupCall \".concat(_this4.groupCallId, \" initLocalCallFeedInternal() running\"));\n      var stream;\n      try {\n        stream = yield _this4.client.getMediaHandler().getUserMediaStream(true, _this4.type === GroupCallType.Video);\n      } catch (error) {\n        // If is allowed to join a call without a media stream, then we\n        // don't throw an error here. But we need an empty Local Feed to establish\n        // a connection later.\n        if (_this4.allowCallWithoutVideoAndAudio) {\n          stream = new MediaStream();\n        } else {\n          _this4.state = GroupCallState.LocalCallFeedUninitialized;\n          throw error;\n        }\n      }\n\n      // The call could've been disposed while we were waiting, and could\n      // also have been started back up again (hello, React 18) so if we're\n      // still in this 'initializing' state, carry on, otherwise bail.\n      if (_this4._state !== GroupCallState.InitializingLocalCallFeed) {\n        _this4.client.getMediaHandler().stopUserMediaStream(stream);\n        throw new Error(\"Group call disposed while gathering media stream\");\n      }\n      var callFeed = new CallFeed({\n        client: _this4.client,\n        roomId: _this4.room.roomId,\n        userId: _this4.client.getUserId(),\n        deviceId: _this4.client.getDeviceId(),\n        stream,\n        purpose: SDPStreamMetadataPurpose.Usermedia,\n        audioMuted: _this4.initWithAudioMuted || stream.getAudioTracks().length === 0 || _this4.isPtt,\n        videoMuted: _this4.initWithVideoMuted || stream.getVideoTracks().length === 0\n      });\n      setTracksEnabled(stream.getAudioTracks(), !callFeed.isAudioMuted());\n      setTracksEnabled(stream.getVideoTracks(), !callFeed.isVideoMuted());\n      _this4.localCallFeed = callFeed;\n      _this4.addUserMediaFeed(callFeed);\n      _this4.state = GroupCallState.LocalCallFeedInitialized;\n    })();\n  }\n  updateLocalUsermediaStream(stream) {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      if (_this5.localCallFeed) {\n        var oldStream = _this5.localCallFeed.stream;\n        _this5.localCallFeed.setNewStream(stream);\n        var micShouldBeMuted = _this5.localCallFeed.isAudioMuted();\n        var vidShouldBeMuted = _this5.localCallFeed.isVideoMuted();\n        logger.log(\"GroupCall \".concat(_this5.groupCallId, \" updateLocalUsermediaStream() (oldStreamId=\").concat(oldStream.id, \", newStreamId=\").concat(stream.id, \", micShouldBeMuted=\").concat(micShouldBeMuted, \", vidShouldBeMuted=\").concat(vidShouldBeMuted, \")\"));\n        setTracksEnabled(stream.getAudioTracks(), !micShouldBeMuted);\n        setTracksEnabled(stream.getVideoTracks(), !vidShouldBeMuted);\n        _this5.client.getMediaHandler().stopUserMediaStream(oldStream);\n      }\n    })();\n  }\n  enter() {\n    var _this6 = this;\n    return _asyncToGenerator(function* () {\n      if (_this6.state === GroupCallState.LocalCallFeedUninitialized) {\n        yield _this6.initLocalCallFeed();\n      } else if (_this6.state !== GroupCallState.LocalCallFeedInitialized) {\n        throw new Error(\"Cannot enter call in the \\\"\".concat(_this6.state, \"\\\" state\"));\n      }\n      logger.log(\"GroupCall \".concat(_this6.groupCallId, \" enter() running\"));\n      _this6.state = GroupCallState.Entered;\n      _this6.client.on(CallEventHandlerEvent.Incoming, _this6.onIncomingCall);\n      for (var call of _this6.client.callEventHandler.calls.values()) {\n        _this6.onIncomingCall(call);\n      }\n      if (!_this6.useLivekit) {\n        _this6.retryCallLoopInterval = setInterval(_this6.onRetryCallLoop, _this6.retryCallInterval);\n        _this6.activeSpeaker = undefined;\n        _this6.onActiveSpeakerLoop();\n        _this6.activeSpeakerLoopInterval = setInterval(_this6.onActiveSpeakerLoop, _this6.activeSpeakerInterval);\n      }\n    })();\n  }\n  dispose() {\n    var _this$stats;\n    if (this.localCallFeed) {\n      this.removeUserMediaFeed(this.localCallFeed);\n      this.localCallFeed = undefined;\n    }\n    if (this.localScreenshareFeed) {\n      this.client.getMediaHandler().stopScreensharingStream(this.localScreenshareFeed.stream);\n      this.removeScreenshareFeed(this.localScreenshareFeed);\n      this.localScreenshareFeed = undefined;\n      this.localDesktopCapturerSourceId = undefined;\n    }\n    this.client.getMediaHandler().stopAllStreams();\n    if (this.transmitTimer !== null) {\n      clearTimeout(this.transmitTimer);\n      this.transmitTimer = null;\n    }\n    if (this.retryCallLoopInterval !== undefined) {\n      clearInterval(this.retryCallLoopInterval);\n      this.retryCallLoopInterval = undefined;\n    }\n    if (this.participantsExpirationTimer !== null) {\n      clearTimeout(this.participantsExpirationTimer);\n      this.participantsExpirationTimer = null;\n    }\n    if (this.state !== GroupCallState.Entered) {\n      return;\n    }\n    this.forEachCall(call => call.hangup(CallErrorCode.UserHangup, false));\n    this.activeSpeaker = undefined;\n    clearInterval(this.activeSpeakerLoopInterval);\n    this.retryCallCounts.clear();\n    clearInterval(this.retryCallLoopInterval);\n    this.client.removeListener(CallEventHandlerEvent.Incoming, this.onIncomingCall);\n    (_this$stats = this.stats) === null || _this$stats === void 0 || _this$stats.stop();\n  }\n  leave() {\n    this.dispose();\n    this.state = GroupCallState.LocalCallFeedUninitialized;\n  }\n  terminate() {\n    var _arguments = arguments,\n      _this7 = this;\n    return _asyncToGenerator(function* () {\n      var emitStateEvent = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : true;\n      _this7.dispose();\n      _this7.room.off(RoomStateEvent.Update, _this7.onRoomState);\n      _this7.client.groupCallEventHandler.groupCalls.delete(_this7.room.roomId);\n      _this7.client.emit(GroupCallEventHandlerEvent.Ended, _this7);\n      _this7.state = GroupCallState.Ended;\n      if (emitStateEvent) {\n        var existingStateEvent = _this7.room.currentState.getStateEvents(EventType.GroupCallPrefix, _this7.groupCallId);\n        yield _this7.client.sendStateEvent(_this7.room.roomId, EventType.GroupCallPrefix, _objectSpread(_objectSpread({}, existingStateEvent.getContent()), {}, {\n          \"m.terminated\": GroupCallTerminationReason.CallEnded\n        }), _this7.groupCallId);\n      }\n    })();\n  }\n\n  /*\n   * Local Usermedia\n   */\n\n  isLocalVideoMuted() {\n    if (this.localCallFeed) {\n      return this.localCallFeed.isVideoMuted();\n    }\n    return true;\n  }\n  isMicrophoneMuted() {\n    if (this.localCallFeed) {\n      return this.localCallFeed.isAudioMuted();\n    }\n    return true;\n  }\n\n  /**\n   * Sets the mute state of the local participants's microphone.\n   * @param muted - Whether to mute the microphone\n   * @returns Whether muting/unmuting was successful\n   */\n  setMicrophoneMuted(muted) {\n    var _this8 = this;\n    return _asyncToGenerator(function* () {\n      // hasAudioDevice can block indefinitely if the window has lost focus,\n      // and it doesn't make much sense to keep a device from being muted, so\n      // we always allow muted = true changes to go through\n      if (!muted && !(yield _this8.client.getMediaHandler().hasAudioDevice())) {\n        return false;\n      }\n      var sendUpdatesBefore = !muted && _this8.isPtt;\n\n      // set a timer for the maximum transmit time on PTT calls\n      if (_this8.isPtt) {\n        // Set or clear the max transmit timer\n        if (!muted && _this8.isMicrophoneMuted()) {\n          _this8.transmitTimer = setTimeout(() => {\n            _this8.setMicrophoneMuted(true);\n          }, _this8.pttMaxTransmitTime);\n        } else if (muted && !_this8.isMicrophoneMuted()) {\n          if (_this8.transmitTimer !== null) clearTimeout(_this8.transmitTimer);\n          _this8.transmitTimer = null;\n        }\n      }\n      _this8.forEachCall(call => {\n        var _call$localUsermediaF;\n        return (_call$localUsermediaF = call.localUsermediaFeed) === null || _call$localUsermediaF === void 0 ? void 0 : _call$localUsermediaF.setAudioVideoMuted(muted, null);\n      });\n      var sendUpdates = /*#__PURE__*/function () {\n        var _ref = _asyncToGenerator(function* () {\n          var updates = [];\n          _this8.forEachCall(call => updates.push(call.sendMetadataUpdate()));\n          yield Promise.all(updates).catch(e => logger.info(\"GroupCall \".concat(_this8.groupCallId, \" setMicrophoneMuted() failed to send some metadata updates\"), e));\n        });\n        return function sendUpdates() {\n          return _ref.apply(this, arguments);\n        };\n      }();\n      if (sendUpdatesBefore) yield sendUpdates();\n      if (_this8.localCallFeed) {\n        logger.log(\"GroupCall \".concat(_this8.groupCallId, \" setMicrophoneMuted() (streamId=\").concat(_this8.localCallFeed.stream.id, \", muted=\").concat(muted, \")\"));\n        var hasPermission = yield _this8.checkAudioPermissionIfNecessary(muted);\n        if (!hasPermission) {\n          return false;\n        }\n        _this8.localCallFeed.setAudioVideoMuted(muted, null);\n        // I don't believe its actually necessary to enable these tracks: they\n        // are the one on the GroupCall's own CallFeed and are cloned before being\n        // given to any of the actual calls, so these tracks don't actually go\n        // anywhere. Let's do it anyway to avoid confusion.\n        setTracksEnabled(_this8.localCallFeed.stream.getAudioTracks(), !muted);\n      } else {\n        logger.log(\"GroupCall \".concat(_this8.groupCallId, \" setMicrophoneMuted() no stream muted (muted=\").concat(muted, \")\"));\n        _this8.initWithAudioMuted = muted;\n      }\n      _this8.forEachCall(call => setTracksEnabled(call.localUsermediaFeed.stream.getAudioTracks(), !muted && _this8.callExpected(call)));\n      _this8.emit(GroupCallEvent.LocalMuteStateChanged, muted, _this8.isLocalVideoMuted());\n      if (!sendUpdatesBefore) yield sendUpdates();\n      return true;\n    })();\n  }\n\n  /**\n   * If we allow entering a call without a camera and without video, it can happen that the access rights to the\n   * devices have not yet been queried. If a stream does not yet have an audio track, we assume that the rights have\n   * not yet been checked.\n   *\n   * `this.client.getMediaHandler().getUserMediaStream` clones the current stream, so it only wanted to be called when\n   * not Audio Track exists.\n   * As such, this is a compromise, because, the access rights should always be queried before the call.\n   */\n  checkAudioPermissionIfNecessary(muted) {\n    var _this9 = this;\n    return _asyncToGenerator(function* () {\n      // We needed this here to avoid an error in case user join a call without a device.\n      try {\n        if (!muted && _this9.localCallFeed && !_this9.localCallFeed.hasAudioTrack) {\n          var stream = yield _this9.client.getMediaHandler().getUserMediaStream(true, !_this9.localCallFeed.isVideoMuted());\n          if ((stream === null || stream === void 0 ? void 0 : stream.getTracks().length) === 0) {\n            // if case permission denied to get a stream stop this here\n            /* istanbul ignore next */\n            logger.log(\"GroupCall \".concat(_this9.groupCallId, \" setMicrophoneMuted() no device to receive local stream, muted=\").concat(muted));\n            return false;\n          }\n        }\n      } catch (_unused) {\n        /* istanbul ignore next */\n        logger.log(\"GroupCall \".concat(_this9.groupCallId, \" setMicrophoneMuted() no device or permission to receive local stream, muted=\").concat(muted));\n        return false;\n      }\n      return true;\n    })();\n  }\n\n  /**\n   * Sets the mute state of the local participants's video.\n   * @param muted - Whether to mute the video\n   * @returns Whether muting/unmuting was successful\n   */\n  setLocalVideoMuted(muted) {\n    var _this0 = this;\n    return _asyncToGenerator(function* () {\n      // hasAudioDevice can block indefinitely if the window has lost focus,\n      // and it doesn't make much sense to keep a device from being muted, so\n      // we always allow muted = true changes to go through\n      if (!muted && !(yield _this0.client.getMediaHandler().hasVideoDevice())) {\n        return false;\n      }\n      if (_this0.localCallFeed) {\n        /* istanbul ignore next */\n        logger.log(\"GroupCall \".concat(_this0.groupCallId, \" setLocalVideoMuted() (stream=\").concat(_this0.localCallFeed.stream.id, \", muted=\").concat(muted, \")\"));\n        try {\n          var stream = yield _this0.client.getMediaHandler().getUserMediaStream(true, !muted);\n          yield _this0.updateLocalUsermediaStream(stream);\n          _this0.localCallFeed.setAudioVideoMuted(null, muted);\n          setTracksEnabled(_this0.localCallFeed.stream.getVideoTracks(), !muted);\n        } catch (_unused2) {\n          // No permission to video device\n          /* istanbul ignore next */\n          logger.log(\"GroupCall \".concat(_this0.groupCallId, \" setLocalVideoMuted() no device or permission to receive local stream, muted=\").concat(muted));\n          return false;\n        }\n      } else {\n        logger.log(\"GroupCall \".concat(_this0.groupCallId, \" setLocalVideoMuted() no stream muted (muted=\").concat(muted, \")\"));\n        _this0.initWithVideoMuted = muted;\n      }\n      var updates = [];\n      _this0.forEachCall(call => updates.push(call.setLocalVideoMuted(muted)));\n      yield Promise.all(updates);\n\n      // We setTracksEnabled again, independently from the call doing it\n      // internally, since we might not be expecting the call\n      _this0.forEachCall(call => setTracksEnabled(call.localUsermediaFeed.stream.getVideoTracks(), !muted && _this0.callExpected(call)));\n      _this0.emit(GroupCallEvent.LocalMuteStateChanged, _this0.isMicrophoneMuted(), muted);\n      return true;\n    })();\n  }\n  setScreensharingEnabled(enabled) {\n    var _arguments2 = arguments,\n      _this1 = this;\n    return _asyncToGenerator(function* () {\n      var opts = _arguments2.length > 1 && _arguments2[1] !== undefined ? _arguments2[1] : {};\n      if (enabled === _this1.isScreensharing()) {\n        return enabled;\n      }\n      if (enabled) {\n        try {\n          logger.log(\"GroupCall \".concat(_this1.groupCallId, \" setScreensharingEnabled() is asking for screensharing permissions\"));\n          var stream = yield _this1.client.getMediaHandler().getScreensharingStream(opts);\n          var _loop = function* _loop(track) {\n            var onTrackEnded = () => {\n              _this1.setScreensharingEnabled(false);\n              track.removeEventListener(\"ended\", onTrackEnded);\n            };\n            track.addEventListener(\"ended\", onTrackEnded);\n          };\n          for (var track of stream.getTracks()) {\n            yield* _loop(track);\n          }\n          logger.log(\"GroupCall \".concat(_this1.groupCallId, \" setScreensharingEnabled() granted screensharing permissions. Setting screensharing enabled on all calls\"));\n          _this1.localDesktopCapturerSourceId = opts.desktopCapturerSourceId;\n          _this1.localScreenshareFeed = new CallFeed({\n            client: _this1.client,\n            roomId: _this1.room.roomId,\n            userId: _this1.client.getUserId(),\n            deviceId: _this1.client.getDeviceId(),\n            stream,\n            purpose: SDPStreamMetadataPurpose.Screenshare,\n            audioMuted: false,\n            videoMuted: false\n          });\n          _this1.addScreenshareFeed(_this1.localScreenshareFeed);\n          _this1.emit(GroupCallEvent.LocalScreenshareStateChanged, true, _this1.localScreenshareFeed, _this1.localDesktopCapturerSourceId);\n\n          // TODO: handle errors\n          _this1.forEachCall(call => call.pushLocalFeed(_this1.localScreenshareFeed.clone()));\n          return true;\n        } catch (error) {\n          if (opts.throwOnFail) throw error;\n          logger.error(\"GroupCall \".concat(_this1.groupCallId, \" setScreensharingEnabled() enabling screensharing error\"), error);\n          _this1.emit(GroupCallEvent.Error, new GroupCallError(GroupCallErrorCode.NoUserMedia, \"Failed to get screen-sharing stream: \", error));\n          return false;\n        }\n      } else {\n        _this1.forEachCall(call => {\n          if (call.localScreensharingFeed) call.removeLocalFeed(call.localScreensharingFeed);\n        });\n        _this1.client.getMediaHandler().stopScreensharingStream(_this1.localScreenshareFeed.stream);\n        _this1.removeScreenshareFeed(_this1.localScreenshareFeed);\n        _this1.localScreenshareFeed = undefined;\n        _this1.localDesktopCapturerSourceId = undefined;\n        _this1.emit(GroupCallEvent.LocalScreenshareStateChanged, false, undefined, undefined);\n        return false;\n      }\n    })();\n  }\n  isScreensharing() {\n    return !!this.localScreenshareFeed;\n  }\n  /**\n   * Determines whether a given participant expects us to call them (versus\n   * them calling us).\n   * @param userId - The participant's user ID.\n   * @param deviceId - The participant's device ID.\n   * @returns Whether we need to place an outgoing call to the participant.\n   */\n  wantsOutgoingCall(userId, deviceId) {\n    var localUserId = this.client.getUserId();\n    var localDeviceId = this.client.getDeviceId();\n    return (\n      // If a user's ID is less than our own, they'll call us\n      userId >= localUserId && (\n      // If this is another one of our devices, compare device IDs to tell whether it'll call us\n      userId !== localUserId || deviceId > localDeviceId)\n    );\n  }\n\n  /**\n   * Places calls to all participants that we're responsible for calling.\n   */\n  placeOutgoingCalls() {\n    var _this10 = this;\n    var callsChanged = false;\n    var _loop2 = function _loop2(_userId2) {\n      var _this10$calls$get;\n      var callMap = (_this10$calls$get = _this10.calls.get(_userId2)) !== null && _this10$calls$get !== void 0 ? _this10$calls$get : new Map();\n      var _loop3 = function _loop3(deviceId) {\n        var prevCall = callMap.get(deviceId);\n        if ((prevCall === null || prevCall === void 0 ? void 0 : prevCall.getOpponentSessionId()) !== participant.sessionId && _this10.wantsOutgoingCall(_userId2, deviceId)) {\n          callsChanged = true;\n          if (prevCall !== undefined) {\n            logger.debug(\"GroupCall \".concat(_this10.groupCallId, \" placeOutgoingCalls() replacing call (userId=\").concat(_userId2, \", deviceId=\").concat(deviceId, \", callId=\").concat(prevCall.callId, \")\"));\n            prevCall.hangup(CallErrorCode.NewSession, false);\n          }\n          var newCall = createNewMatrixCall(_this10.client, _this10.room.roomId, {\n            invitee: _userId2,\n            opponentDeviceId: deviceId,\n            opponentSessionId: participant.sessionId,\n            groupCallId: _this10.groupCallId\n          });\n          if (newCall === null) {\n            logger.error(\"GroupCall \".concat(_this10.groupCallId, \" placeOutgoingCalls() failed to create call (userId=\").concat(_userId2, \", device=\").concat(deviceId, \")\"));\n            callMap.delete(deviceId);\n          } else {\n            _this10.initCall(newCall);\n            callMap.set(deviceId, newCall);\n            logger.debug(\"GroupCall \".concat(_this10.groupCallId, \" placeOutgoingCalls() placing call (userId=\").concat(_userId2, \", deviceId=\").concat(deviceId, \", sessionId=\").concat(participant.sessionId, \")\"));\n            newCall.placeCallWithCallFeeds(_this10.getLocalFeeds().map(feed => feed.clone()), participant.screensharing).then(() => {\n              if (_this10.dataChannelsEnabled) {\n                newCall.createDataChannel(\"datachannel\", _this10.dataChannelOptions);\n              }\n            }).catch(e => {\n              logger.warn(\"GroupCall \".concat(_this10.groupCallId, \" placeOutgoingCalls() failed to place call (userId=\").concat(_userId2, \")\"), e);\n              if (e instanceof CallError && e.code === GroupCallErrorCode.UnknownDevice) {\n                _this10.emit(GroupCallEvent.Error, e);\n              } else {\n                _this10.emit(GroupCallEvent.Error, new GroupCallError(GroupCallErrorCode.PlaceCallFailed, \"Failed to place call to \".concat(_userId2)));\n              }\n              newCall.hangup(CallErrorCode.SignallingFailed, false);\n              if (callMap.get(deviceId) === newCall) callMap.delete(deviceId);\n            });\n          }\n        }\n      };\n      for (var [deviceId, participant] of participantMap) {\n        _loop3(deviceId);\n      }\n      if (callMap.size > 0) {\n        _this10.calls.set(_userId2, callMap);\n      } else {\n        _this10.calls.delete(_userId2);\n      }\n    };\n    for (var [{\n      userId: _userId2\n    }, participantMap] of this.participants) {\n      _loop2(_userId2);\n    }\n    if (callsChanged) this.emit(GroupCallEvent.CallsChanged, this.calls);\n  }\n\n  /*\n   * Room Member State\n   */\n\n  getMemberStateEvents(userId) {\n    return userId === undefined ? this.room.currentState.getStateEvents(EventType.GroupCallMemberPrefix) : this.room.currentState.getStateEvents(EventType.GroupCallMemberPrefix, userId);\n  }\n  initCall(call) {\n    var opponentMemberId = getCallUserId(call);\n    if (!opponentMemberId) {\n      throw new Error(\"Cannot init call without user id\");\n    }\n    var onCallFeedsChanged = () => this.onCallFeedsChanged(call);\n    var onCallStateChanged = (state, oldState) => this.onCallStateChanged(call, state, oldState);\n    var onCallHangup = this.onCallHangup;\n    var onCallReplaced = newCall => this.onCallReplaced(call, newCall);\n    var deviceMap = this.callHandlers.get(opponentMemberId);\n    if (deviceMap === undefined) {\n      deviceMap = new Map();\n      this.callHandlers.set(opponentMemberId, deviceMap);\n    }\n    deviceMap.set(call.getOpponentDeviceId(), {\n      onCallFeedsChanged,\n      onCallStateChanged,\n      onCallHangup,\n      onCallReplaced\n    });\n    call.on(CallEvent.FeedsChanged, onCallFeedsChanged);\n    call.on(CallEvent.State, onCallStateChanged);\n    call.on(CallEvent.Hangup, onCallHangup);\n    call.on(CallEvent.Replaced, onCallReplaced);\n    call.isPtt = this.isPtt;\n    this.reEmitter.reEmit(call, Object.values(CallEvent));\n    call.initStats(this.getGroupCallStats());\n    onCallFeedsChanged();\n  }\n  disposeCall(call, hangupReason) {\n    var opponentMemberId = getCallUserId(call);\n    var opponentDeviceId = call.getOpponentDeviceId();\n    if (!opponentMemberId) {\n      throw new Error(\"Cannot dispose call without user id\");\n    }\n    var deviceMap = this.callHandlers.get(opponentMemberId);\n    var {\n      onCallFeedsChanged,\n      onCallStateChanged,\n      onCallHangup,\n      onCallReplaced\n    } = deviceMap.get(opponentDeviceId);\n    call.removeListener(CallEvent.FeedsChanged, onCallFeedsChanged);\n    call.removeListener(CallEvent.State, onCallStateChanged);\n    call.removeListener(CallEvent.Hangup, onCallHangup);\n    call.removeListener(CallEvent.Replaced, onCallReplaced);\n    deviceMap.delete(opponentMemberId);\n    if (deviceMap.size === 0) this.callHandlers.delete(opponentMemberId);\n    if (call.hangupReason === CallErrorCode.Replaced) {\n      return;\n    }\n    var usermediaFeed = this.getUserMediaFeed(opponentMemberId, opponentDeviceId);\n    if (usermediaFeed) {\n      this.removeUserMediaFeed(usermediaFeed);\n    }\n    var screenshareFeed = this.getScreenshareFeed(opponentMemberId, opponentDeviceId);\n    if (screenshareFeed) {\n      this.removeScreenshareFeed(screenshareFeed);\n    }\n  }\n  /*\n   * UserMedia CallFeed Event Handlers\n   */\n\n  getUserMediaFeed(userId, deviceId) {\n    return this.userMediaFeeds.find(f => f.userId === userId && f.deviceId === deviceId);\n  }\n  addUserMediaFeed(callFeed) {\n    this.userMediaFeeds.push(callFeed);\n    callFeed.measureVolumeActivity(true);\n    this.emit(GroupCallEvent.UserMediaFeedsChanged, this.userMediaFeeds);\n  }\n  replaceUserMediaFeed(existingFeed, replacementFeed) {\n    var feedIndex = this.userMediaFeeds.findIndex(f => f.userId === existingFeed.userId && f.deviceId === existingFeed.deviceId);\n    if (feedIndex === -1) {\n      throw new Error(\"Couldn't find user media feed to replace\");\n    }\n    this.userMediaFeeds.splice(feedIndex, 1, replacementFeed);\n    existingFeed.dispose();\n    replacementFeed.measureVolumeActivity(true);\n    this.emit(GroupCallEvent.UserMediaFeedsChanged, this.userMediaFeeds);\n  }\n  removeUserMediaFeed(callFeed) {\n    var feedIndex = this.userMediaFeeds.findIndex(f => f.userId === callFeed.userId && f.deviceId === callFeed.deviceId);\n    if (feedIndex === -1) {\n      throw new Error(\"Couldn't find user media feed to remove\");\n    }\n    this.userMediaFeeds.splice(feedIndex, 1);\n    callFeed.dispose();\n    this.emit(GroupCallEvent.UserMediaFeedsChanged, this.userMediaFeeds);\n    if (this.activeSpeaker === callFeed) {\n      this.activeSpeaker = this.userMediaFeeds[0];\n      this.emit(GroupCallEvent.ActiveSpeakerChanged, this.activeSpeaker);\n    }\n  }\n  /*\n   * Screenshare Call Feed Event Handlers\n   */\n\n  getScreenshareFeed(userId, deviceId) {\n    return this.screenshareFeeds.find(f => f.userId === userId && f.deviceId === deviceId);\n  }\n  addScreenshareFeed(callFeed) {\n    this.screenshareFeeds.push(callFeed);\n    this.emit(GroupCallEvent.ScreenshareFeedsChanged, this.screenshareFeeds);\n  }\n  replaceScreenshareFeed(existingFeed, replacementFeed) {\n    var feedIndex = this.screenshareFeeds.findIndex(f => f.userId === existingFeed.userId && f.deviceId === existingFeed.deviceId);\n    if (feedIndex === -1) {\n      throw new Error(\"Couldn't find screenshare feed to replace\");\n    }\n    this.screenshareFeeds.splice(feedIndex, 1, replacementFeed);\n    existingFeed.dispose();\n    this.emit(GroupCallEvent.ScreenshareFeedsChanged, this.screenshareFeeds);\n  }\n  removeScreenshareFeed(callFeed) {\n    var feedIndex = this.screenshareFeeds.findIndex(f => f.userId === callFeed.userId && f.deviceId === callFeed.deviceId);\n    if (feedIndex === -1) {\n      throw new Error(\"Couldn't find screenshare feed to remove\");\n    }\n    this.screenshareFeeds.splice(feedIndex, 1);\n    callFeed.dispose();\n    this.emit(GroupCallEvent.ScreenshareFeedsChanged, this.screenshareFeeds);\n  }\n\n  /**\n   * Recalculates and updates the participant map to match the room state.\n   */\n  updateParticipants() {\n    var localMember = this.room.getMember(this.client.getSafeUserId());\n    if (!localMember) {\n      // The client hasn't fetched enough of the room state to get our own member\n      // event. This probably shouldn't happen, but sanity check & exit for now.\n      logger.warn(\"GroupCall \".concat(this.groupCallId, \" updateParticipants() tried to update participants before local room member is available\"));\n      return;\n    }\n    if (this.participantsExpirationTimer !== null) {\n      clearTimeout(this.participantsExpirationTimer);\n      this.participantsExpirationTimer = null;\n    }\n    if (this.state === GroupCallState.Ended) {\n      this.participants = new Map();\n      return;\n    }\n    var participants = new Map();\n    var now = Date.now();\n    var entered = this.state === GroupCallState.Entered || this.enteredViaAnotherSession;\n    var nextExpiration = Infinity;\n    for (var e of this.getMemberStateEvents()) {\n      var member = this.room.getMember(e.getStateKey());\n      var content = e.getContent();\n      var calls = Array.isArray(content[\"m.calls\"]) ? content[\"m.calls\"] : [];\n      var call = calls.find(call => call[\"m.call_id\"] === this.groupCallId);\n      var devices = Array.isArray(call === null || call === void 0 ? void 0 : call[\"m.devices\"]) ? call[\"m.devices\"] : [];\n\n      // Filter out invalid and expired devices\n      var validDevices = devices.filter(d => typeof d.device_id === \"string\" && typeof d.session_id === \"string\" && typeof d.expires_ts === \"number\" && d.expires_ts > now && Array.isArray(d.feeds));\n\n      // Apply local echo for the unentered case\n      if (!entered && (member === null || member === void 0 ? void 0 : member.userId) === this.client.getUserId()) {\n        validDevices = validDevices.filter(d => d.device_id !== this.client.getDeviceId());\n      }\n\n      // Must have a connected device and be joined to the room\n      if (validDevices.length > 0 && (member === null || member === void 0 ? void 0 : member.membership) === KnownMembership.Join) {\n        var deviceMap = new Map();\n        participants.set(member, deviceMap);\n        for (var d of validDevices) {\n          deviceMap.set(d.device_id, {\n            sessionId: d.session_id,\n            screensharing: d.feeds.some(f => f.purpose === SDPStreamMetadataPurpose.Screenshare)\n          });\n          if (d.expires_ts < nextExpiration) nextExpiration = d.expires_ts;\n        }\n      }\n    }\n\n    // Apply local echo for the entered case\n    if (entered) {\n      var _deviceMap = participants.get(localMember);\n      if (_deviceMap === undefined) {\n        _deviceMap = new Map();\n        participants.set(localMember, _deviceMap);\n      }\n      if (!_deviceMap.has(this.client.getDeviceId())) {\n        _deviceMap.set(this.client.getDeviceId(), {\n          sessionId: this.client.getSessionId(),\n          screensharing: this.getLocalFeeds().some(f => f.purpose === SDPStreamMetadataPurpose.Screenshare)\n        });\n      }\n    }\n    this.participants = participants;\n    if (nextExpiration < Infinity) {\n      this.participantsExpirationTimer = setTimeout(() => this.updateParticipants(), nextExpiration - now);\n    }\n  }\n\n  /**\n   * Updates the local user's member state with the devices returned by the given function.\n   * @param fn - A function from the current devices to the new devices. If it\n   *   returns null, the update will be skipped.\n   * @param keepAlive - Whether the request should outlive the window.\n   */\n  updateDevices(fn) {\n    var _arguments3 = arguments,\n      _this11 = this;\n    return _asyncToGenerator(function* () {\n      var _event$getContent;\n      var keepAlive = _arguments3.length > 1 && _arguments3[1] !== undefined ? _arguments3[1] : false;\n      var now = Date.now();\n      var localUserId = _this11.client.getUserId();\n      var event = _this11.getMemberStateEvents(localUserId);\n      var content = (_event$getContent = event === null || event === void 0 ? void 0 : event.getContent()) !== null && _event$getContent !== void 0 ? _event$getContent : {};\n      var calls = Array.isArray(content[\"m.calls\"]) ? content[\"m.calls\"] : [];\n      var call = null;\n      var otherCalls = [];\n      for (var c of calls) {\n        if (c[\"m.call_id\"] === _this11.groupCallId) {\n          call = c;\n        } else {\n          otherCalls.push(c);\n        }\n      }\n      if (call === null) call = {};\n      var devices = Array.isArray(call[\"m.devices\"]) ? call[\"m.devices\"] : [];\n\n      // Filter out invalid and expired devices\n      var validDevices = devices.filter(d => typeof d.device_id === \"string\" && typeof d.session_id === \"string\" && typeof d.expires_ts === \"number\" && d.expires_ts > now && Array.isArray(d.feeds));\n      var newDevices = fn(validDevices);\n      if (newDevices === null) return;\n      var newCalls = [...otherCalls];\n      if (newDevices.length > 0) {\n        newCalls.push(_objectSpread(_objectSpread({}, call), {}, {\n          \"m.call_id\": _this11.groupCallId,\n          \"m.devices\": newDevices\n        }));\n      }\n      var newContent = {\n        \"m.calls\": newCalls\n      };\n      yield _this11.client.sendStateEvent(_this11.room.roomId, EventType.GroupCallMemberPrefix, newContent, localUserId, {\n        keepAlive\n      });\n    })();\n  }\n  addDeviceToMemberState() {\n    var _this12 = this;\n    return _asyncToGenerator(function* () {\n      yield _this12.updateDevices(devices => [...devices.filter(d => d.device_id !== _this12.client.getDeviceId()), {\n        device_id: _this12.client.getDeviceId(),\n        session_id: _this12.client.getSessionId(),\n        expires_ts: Date.now() + DEVICE_TIMEOUT,\n        feeds: _this12.getLocalFeeds().map(feed => ({\n          purpose: feed.purpose\n        }))\n        // TODO: Add data channels\n      }]);\n    })();\n  }\n  updateMemberState() {\n    var _this13 = this;\n    return _asyncToGenerator(function* () {\n      // Clear the old update interval before proceeding\n      if (_this13.resendMemberStateTimer !== null) {\n        clearInterval(_this13.resendMemberStateTimer);\n        _this13.resendMemberStateTimer = null;\n      }\n      if (_this13.state === GroupCallState.Entered) {\n        // Add the local device\n        yield _this13.addDeviceToMemberState();\n\n        // Resend the state event every so often so it doesn't become stale\n        _this13.resendMemberStateTimer = setInterval(/*#__PURE__*/_asyncToGenerator(function* () {\n          logger.log(\"GroupCall \".concat(_this13.groupCallId, \" updateMemberState() resending call member state\\\"\"));\n          try {\n            yield _this13.addDeviceToMemberState();\n          } catch (e) {\n            logger.error(\"GroupCall \".concat(_this13.groupCallId, \" updateMemberState() failed to resend call member state\"), e);\n          }\n        }), DEVICE_TIMEOUT * 3 / 4);\n      } else {\n        // Remove the local device\n        yield _this13.updateDevices(devices => devices.filter(d => d.device_id !== _this13.client.getDeviceId()), true);\n      }\n    })();\n  }\n\n  /**\n   * Cleans up our member state by filtering out logged out devices, inactive\n   * devices, and our own device (if we know we haven't entered).\n   */\n  cleanMemberState() {\n    var _this14 = this;\n    return _asyncToGenerator(function* () {\n      var {\n        devices: myDevices\n      } = yield _this14.client.getDevices();\n      var deviceMap = new Map(myDevices.map(d => [d.device_id, d]));\n\n      // updateDevices takes care of filtering out inactive devices for us\n      yield _this14.updateDevices(devices => {\n        var newDevices = devices.filter(d => {\n          var device = deviceMap.get(d.device_id);\n          return (device === null || device === void 0 ? void 0 : device.last_seen_ts) !== undefined && !(d.device_id === _this14.client.getDeviceId() && _this14.state !== GroupCallState.Entered && !_this14.enteredViaAnotherSession);\n        });\n\n        // Skip the update if the devices are unchanged\n        return newDevices.length === devices.length ? null : newDevices;\n      });\n    })();\n  }\n  getGroupCallStats() {\n    if (this.stats === undefined) {\n      var userID = this.client.getUserId() || \"unknown\";\n      this.stats = new GroupCallStats(this.groupCallId, userID, this.statsCollectIntervalTime);\n      this.stats.reports.on(StatsReport.CONNECTION_STATS, this.onConnectionStats);\n      this.stats.reports.on(StatsReport.BYTE_SENT_STATS, this.onByteSentStats);\n      this.stats.reports.on(StatsReport.SUMMARY_STATS, this.onSummaryStats);\n      this.stats.reports.on(StatsReport.CALL_FEED_REPORT, this.onCallFeedReport);\n    }\n    return this.stats;\n  }\n  setGroupCallStatsInterval(interval) {\n    this.statsCollectIntervalTime = interval;\n    if (this.stats !== undefined) {\n      this.stats.stop();\n      this.stats.setInterval(interval);\n      if (interval > 0) {\n        this.stats.start();\n      }\n    }\n  }\n}\n//# sourceMappingURL=groupCall.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\nCopyright 2019, 2020 The Matrix.org Foundation C.I.C.\nCopyright 2021 - 2022 Šimon Brandner <simon.bra.ag@gmail.com>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link createNewMatrixCall} for the public API.\n */\n\nimport { v4 as uuidv4 } from \"uuid\";\nimport { parse as parseSdp, write as writeSdp } from \"sdp-transform\";\nimport { logger } from \"../logger.js\";\nimport { checkObjectHasKeys, isNullOrUndefined, recursivelyAssign } from \"../utils.js\";\nimport { EventType, ToDeviceMessageId } from \"../@types/event.js\";\nimport { secureRandomString } from \"../randomstring.js\";\nimport { SDPStreamMetadataPurpose, SDPStreamMetadataKey } from \"./callEventTypes.js\";\nimport { CallFeed } from \"./callFeed.js\";\nimport { EventEmitterEvents, TypedEventEmitter } from \"../models/typed-event-emitter.js\";\nimport { GroupCallUnknownDeviceError } from \"./groupCall.js\";\nimport { MatrixError } from \"../http-api/index.js\";\nvar MediaType = /*#__PURE__*/function (MediaType) {\n  MediaType[\"AUDIO\"] = \"audio\";\n  MediaType[\"VIDEO\"] = \"video\";\n  return MediaType;\n}(MediaType || {});\nvar CodecName = /*#__PURE__*/function (CodecName) {\n  CodecName[\"OPUS\"] = \"opus\"; // add more as needed\n  return CodecName;\n}(CodecName || {}); // Used internally to specify modifications to codec parameters in SDP\nexport var CallState = /*#__PURE__*/function (CallState) {\n  CallState[\"Fledgling\"] = \"fledgling\";\n  CallState[\"InviteSent\"] = \"invite_sent\";\n  CallState[\"WaitLocalMedia\"] = \"wait_local_media\";\n  CallState[\"CreateOffer\"] = \"create_offer\";\n  CallState[\"CreateAnswer\"] = \"create_answer\";\n  CallState[\"Connecting\"] = \"connecting\";\n  CallState[\"Connected\"] = \"connected\";\n  CallState[\"Ringing\"] = \"ringing\";\n  CallState[\"Ended\"] = \"ended\";\n  return CallState;\n}({});\nexport var CallType = /*#__PURE__*/function (CallType) {\n  CallType[\"Voice\"] = \"voice\";\n  CallType[\"Video\"] = \"video\";\n  return CallType;\n}({});\nexport var CallDirection = /*#__PURE__*/function (CallDirection) {\n  CallDirection[\"Inbound\"] = \"inbound\";\n  CallDirection[\"Outbound\"] = \"outbound\";\n  return CallDirection;\n}({});\nexport var CallParty = /*#__PURE__*/function (CallParty) {\n  CallParty[\"Local\"] = \"local\";\n  CallParty[\"Remote\"] = \"remote\";\n  return CallParty;\n}({});\nexport var CallEvent = /*#__PURE__*/function (CallEvent) {\n  CallEvent[\"Hangup\"] = \"hangup\";\n  CallEvent[\"State\"] = \"state\";\n  CallEvent[\"Error\"] = \"error\";\n  CallEvent[\"Replaced\"] = \"replaced\";\n  // The value of isLocalOnHold() has changed\n  CallEvent[\"LocalHoldUnhold\"] = \"local_hold_unhold\";\n  // The value of isRemoteOnHold() has changed\n  CallEvent[\"RemoteHoldUnhold\"] = \"remote_hold_unhold\";\n  // backwards compat alias for LocalHoldUnhold: remove in a major version bump\n  CallEvent[\"HoldUnhold\"] = \"hold_unhold\";\n  // Feeds have changed\n  CallEvent[\"FeedsChanged\"] = \"feeds_changed\";\n  CallEvent[\"AssertedIdentityChanged\"] = \"asserted_identity_changed\";\n  CallEvent[\"LengthChanged\"] = \"length_changed\";\n  CallEvent[\"DataChannel\"] = \"datachannel\";\n  CallEvent[\"SendVoipEvent\"] = \"send_voip_event\";\n  // When the call instantiates its peer connection\n  // For apps that want to access the underlying peer connection, eg for debugging\n  CallEvent[\"PeerConnectionCreated\"] = \"peer_connection_created\";\n  return CallEvent;\n}({});\nexport var CallErrorCode = /*#__PURE__*/function (CallErrorCode) {\n  /** The user chose to end the call */\n  CallErrorCode[\"UserHangup\"] = \"user_hangup\";\n  /** An error code when the local client failed to create an offer. */\n  CallErrorCode[\"LocalOfferFailed\"] = \"local_offer_failed\";\n  /**\n   * An error code when there is no local mic/camera to use. This may be because\n   * the hardware isn't plugged in, or the user has explicitly denied access.\n   */\n  CallErrorCode[\"NoUserMedia\"] = \"no_user_media\";\n  /**\n   * Error code used when a call event failed to send\n   * because unknown devices were present in the room\n   */\n  CallErrorCode[\"UnknownDevices\"] = \"unknown_devices\";\n  /**\n   * Error code used when we fail to send the invite\n   * for some reason other than there being unknown devices\n   */\n  CallErrorCode[\"SendInvite\"] = \"send_invite\";\n  /**\n   * An answer could not be created\n   */\n  CallErrorCode[\"CreateAnswer\"] = \"create_answer\";\n  /**\n   * An offer could not be created\n   */\n  CallErrorCode[\"CreateOffer\"] = \"create_offer\";\n  /**\n   * Error code used when we fail to send the answer\n   * for some reason other than there being unknown devices\n   */\n  CallErrorCode[\"SendAnswer\"] = \"send_answer\";\n  /**\n   * The session description from the other side could not be set\n   */\n  CallErrorCode[\"SetRemoteDescription\"] = \"set_remote_description\";\n  /**\n   * The session description from this side could not be set\n   */\n  CallErrorCode[\"SetLocalDescription\"] = \"set_local_description\";\n  /**\n   * A different device answered the call\n   */\n  CallErrorCode[\"AnsweredElsewhere\"] = \"answered_elsewhere\";\n  /**\n   * No media connection could be established to the other party\n   */\n  CallErrorCode[\"IceFailed\"] = \"ice_failed\";\n  /**\n   * The invite timed out whilst waiting for an answer\n   */\n  CallErrorCode[\"InviteTimeout\"] = \"invite_timeout\";\n  /**\n   * The call was replaced by another call\n   */\n  CallErrorCode[\"Replaced\"] = \"replaced\";\n  /**\n   * Signalling for the call could not be sent (other than the initial invite)\n   */\n  CallErrorCode[\"SignallingFailed\"] = \"signalling_timeout\";\n  /**\n   * The remote party is busy\n   */\n  CallErrorCode[\"UserBusy\"] = \"user_busy\";\n  /**\n   * We transferred the call off to somewhere else\n   */\n  CallErrorCode[\"Transferred\"] = \"transferred\";\n  /**\n   * A call from the same user was found with a new session id\n   */\n  CallErrorCode[\"NewSession\"] = \"new_session\";\n  return CallErrorCode;\n}({});\n\n/**\n * The version field that we set in m.call.* events\n */\nvar VOIP_PROTO_VERSION = \"1\";\n\n/** The fallback ICE server to use for STUN or TURN protocols. */\nexport var FALLBACK_ICE_SERVER = \"stun:turn.matrix.org\";\n\n/** The length of time a call can be ringing for. */\nvar CALL_TIMEOUT_MS = 60 * 1000; // ms\n/** The time after which we increment callLength */\nvar CALL_LENGTH_INTERVAL = 1000; // ms\n/** The time after which we end the call, if ICE got disconnected */\nvar ICE_DISCONNECTED_TIMEOUT = 30 * 1000; // ms\n/** The time after which we try a ICE restart, if ICE got disconnected */\nvar ICE_RECONNECTING_TIMEOUT = 2 * 1000; // ms\nexport class CallError extends Error {\n  constructor(code, msg, err) {\n    // Still don't think there's any way to have proper nested errors\n    super(msg + \": \" + err);\n    _defineProperty(this, \"code\", void 0);\n    this.code = code;\n  }\n}\nexport function genCallID() {\n  return Date.now().toString() + secureRandomString(16);\n}\nfunction getCodecParamMods(isPtt) {\n  var mods = [{\n    mediaType: \"audio\",\n    codec: \"opus\",\n    enableDtx: true,\n    maxAverageBitrate: isPtt ? 12000 : undefined\n  }];\n  return mods;\n}\n\n/**\n * These now all have the call object as an argument. Why? Well, to know which call a given event is\n * about you have three options:\n *  1. Use a closure as the callback that remembers what call it's listening to. This can be\n *     a pain because you need to pass the listener function again when you remove the listener,\n *     which might be somewhere else.\n *  2. Use not-very-well-known fact that EventEmitter sets 'this' to the emitter object in the\n *     callback. This doesn't really play well with modern Typescript and eslint and doesn't work\n *     with our pattern of re-emitting events.\n *  3. Pass the object in question as an argument to the callback.\n *\n * Now that we have group calls which have to deal with multiple call objects, this will\n * become more important, and I think methods 1 and 2 are just going to cause issues.\n */\n\n// The key of the transceiver map (purpose + media type, separated by ':')\n\n// generates keys for the map of transceivers\n// kind is unfortunately a string rather than MediaType as this is the type of\n// track.kind\nfunction getTransceiverKey(purpose, kind) {\n  return purpose + \":\" + kind;\n}\nexport class MatrixCall extends TypedEventEmitter {\n  /**\n   * Construct a new Matrix Call.\n   * @param opts - Config options.\n   */\n  constructor(opts) {\n    var _this, _opts$forceTURN;\n    super();\n    _this = this;\n    _defineProperty(this, \"roomId\", void 0);\n    _defineProperty(this, \"callId\", void 0);\n    _defineProperty(this, \"invitee\", void 0);\n    _defineProperty(this, \"hangupParty\", void 0);\n    _defineProperty(this, \"hangupReason\", void 0);\n    _defineProperty(this, \"direction\", void 0);\n    _defineProperty(this, \"ourPartyId\", void 0);\n    _defineProperty(this, \"peerConn\", void 0);\n    _defineProperty(this, \"toDeviceSeq\", 0);\n    // whether this call should have push-to-talk semantics\n    // This should be set by the consumer on incoming & outgoing calls.\n    _defineProperty(this, \"isPtt\", false);\n    _defineProperty(this, \"_state\", CallState.Fledgling);\n    _defineProperty(this, \"client\", void 0);\n    _defineProperty(this, \"forceTURN\", void 0);\n    _defineProperty(this, \"turnServers\", void 0);\n    // A queue for candidates waiting to go out.\n    // We try to amalgamate candidates into a single candidate message where\n    // possible\n    _defineProperty(this, \"candidateSendQueue\", []);\n    _defineProperty(this, \"candidateSendTries\", 0);\n    _defineProperty(this, \"candidatesEnded\", false);\n    _defineProperty(this, \"feeds\", []);\n    // our transceivers for each purpose and type of media\n    _defineProperty(this, \"transceivers\", new Map());\n    _defineProperty(this, \"inviteOrAnswerSent\", false);\n    _defineProperty(this, \"waitForLocalAVStream\", false);\n    _defineProperty(this, \"successor\", void 0);\n    _defineProperty(this, \"opponentMember\", void 0);\n    _defineProperty(this, \"opponentVersion\", void 0);\n    // The party ID of the other side: undefined if we haven't chosen a partner\n    // yet, null if we have but they didn't send a party ID.\n    _defineProperty(this, \"opponentPartyId\", void 0);\n    _defineProperty(this, \"opponentCaps\", void 0);\n    _defineProperty(this, \"iceDisconnectedTimeout\", void 0);\n    _defineProperty(this, \"iceReconnectionTimeOut\", void 0);\n    _defineProperty(this, \"inviteTimeout\", void 0);\n    _defineProperty(this, \"removeTrackListeners\", new Map());\n    // The logic of when & if a call is on hold is nontrivial and explained in is*OnHold\n    // This flag represents whether we want the other party to be on hold\n    _defineProperty(this, \"remoteOnHold\", false);\n    // the stats for the call at the point it ended. We can't get these after we\n    // tear the call down, so we just grab a snapshot before we stop the call.\n    // The typescript definitions have this type as 'any' :(\n    _defineProperty(this, \"callStatsAtEnd\", void 0);\n    // Perfect negotiation state: https://www.w3.org/TR/webrtc/#perfect-negotiation-example\n    _defineProperty(this, \"makingOffer\", false);\n    _defineProperty(this, \"ignoreOffer\", false);\n    _defineProperty(this, \"isSettingRemoteAnswerPending\", false);\n    _defineProperty(this, \"responsePromiseChain\", void 0);\n    // If candidates arrive before we've picked an opponent (which, in particular,\n    // will happen if the opponent sends candidates eagerly before the user answers\n    // the call) we buffer them up here so we can then add the ones from the party we pick\n    _defineProperty(this, \"remoteCandidateBuffer\", new Map());\n    _defineProperty(this, \"remoteAssertedIdentity\", void 0);\n    _defineProperty(this, \"remoteSDPStreamMetadata\", void 0);\n    _defineProperty(this, \"callLengthInterval\", void 0);\n    _defineProperty(this, \"callStartTime\", void 0);\n    _defineProperty(this, \"opponentDeviceId\", void 0);\n    _defineProperty(this, \"hasOpponentDeviceInfo\", void 0);\n    _defineProperty(this, \"opponentSessionId\", void 0);\n    _defineProperty(this, \"groupCallId\", void 0);\n    // Used to keep the timer for the delay before actually stopping our\n    // video track after muting (see setLocalVideoMuted)\n    _defineProperty(this, \"stopVideoTrackTimer\", void 0);\n    // Used to allow connection without Video and Audio. To establish a webrtc connection without media a Data channel is\n    // needed At the moment this property is true if we allow MatrixClient with isVoipWithNoMediaAllowed = true\n    _defineProperty(this, \"isOnlyDataChannelAllowed\", void 0);\n    _defineProperty(this, \"stats\", void 0);\n    /**\n     * Internal\n     */\n    _defineProperty(this, \"gotLocalIceCandidate\", event => {\n      if (event.candidate) {\n        if (this.candidatesEnded) {\n          logger.warn(\"Call \".concat(this.callId, \" gotLocalIceCandidate() got candidate after candidates have ended!\"));\n        }\n        logger.debug(\"Call \".concat(this.callId, \" got local ICE \").concat(event.candidate.sdpMid, \" \").concat(event.candidate.candidate));\n        if (this.callHasEnded()) return;\n\n        // As with the offer, note we need to make a copy of this object, not\n        // pass the original: that broke in Chrome ~m43.\n        if (event.candidate.candidate === \"\") {\n          this.queueCandidate(null);\n        } else {\n          this.queueCandidate(event.candidate);\n        }\n      }\n    });\n    _defineProperty(this, \"onIceGatheringStateChange\", event => {\n      var _this$peerConn;\n      logger.debug(\"Call \".concat(this.callId, \" onIceGatheringStateChange() ice gathering state changed to \").concat(this.peerConn.iceGatheringState));\n      if (((_this$peerConn = this.peerConn) === null || _this$peerConn === void 0 ? void 0 : _this$peerConn.iceGatheringState) === \"complete\") {\n        this.queueCandidate(null); // We should leave it to WebRTC to announce the end\n        logger.debug(\"Call \".concat(this.callId, \" onIceGatheringStateChange() ice gathering state complete, set candidates have ended\"));\n      }\n    });\n    _defineProperty(this, \"getLocalOfferFailed\", err => {\n      logger.error(\"Call \".concat(this.callId, \" getLocalOfferFailed() running\"), err);\n      this.emit(CallEvent.Error, new CallError(CallErrorCode.LocalOfferFailed, \"Failed to get local offer!\", err), this);\n      this.terminate(CallParty.Local, CallErrorCode.LocalOfferFailed, false);\n    });\n    _defineProperty(this, \"getUserMediaFailed\", err => {\n      if (this.successor) {\n        this.successor.getUserMediaFailed(err);\n        return;\n      }\n      logger.warn(\"Call \".concat(this.callId, \" getUserMediaFailed() failed to get user media - ending call\"), err);\n      this.emit(CallEvent.Error, new CallError(CallErrorCode.NoUserMedia, \"Couldn't start capturing media! Is your microphone set up and does this app have permission?\", err), this);\n      this.terminate(CallParty.Local, CallErrorCode.NoUserMedia, false);\n    });\n    _defineProperty(this, \"placeCallFailed\", err => {\n      if (this.successor) {\n        this.successor.placeCallFailed(err);\n        return;\n      }\n      logger.warn(\"Call \".concat(this.callId, \" placeCallWithCallFeeds() failed - ending call\"), err);\n      this.emit(CallEvent.Error, new CallError(CallErrorCode.IceFailed, \"Couldn't start call! Invalid ICE server configuration.\", err), this);\n      this.terminate(CallParty.Local, CallErrorCode.IceFailed, false);\n    });\n    _defineProperty(this, \"onIceConnectionStateChanged\", () => {\n      var _this$peerConn2, _this$peerConn3, _this$peerConn$iceCon, _this$peerConn4, _this$peerConn5, _this$peerConn8;\n      if (this.callHasEnded()) {\n        return; // because ICE can still complete as we're ending the call\n      }\n      logger.debug(\"Call \".concat(this.callId, \" onIceConnectionStateChanged() running (state=\").concat((_this$peerConn2 = this.peerConn) === null || _this$peerConn2 === void 0 ? void 0 : _this$peerConn2.iceConnectionState, \", conn=\").concat((_this$peerConn3 = this.peerConn) === null || _this$peerConn3 === void 0 ? void 0 : _this$peerConn3.connectionState, \")\"));\n\n      // ideally we'd consider the call to be connected when we get media but\n      // chrome doesn't implement any of the 'onstarted' events yet\n      if ([\"connected\", \"completed\"].includes((_this$peerConn$iceCon = (_this$peerConn4 = this.peerConn) === null || _this$peerConn4 === void 0 ? void 0 : _this$peerConn4.iceConnectionState) !== null && _this$peerConn$iceCon !== void 0 ? _this$peerConn$iceCon : \"\")) {\n        clearTimeout(this.iceDisconnectedTimeout);\n        this.iceDisconnectedTimeout = undefined;\n        if (this.iceReconnectionTimeOut) {\n          clearTimeout(this.iceReconnectionTimeOut);\n        }\n        this.state = CallState.Connected;\n        if (!this.callLengthInterval && !this.callStartTime) {\n          this.callStartTime = Date.now();\n          this.callLengthInterval = setInterval(() => {\n            this.emit(CallEvent.LengthChanged, Math.round((Date.now() - this.callStartTime) / 1000), this);\n          }, CALL_LENGTH_INTERVAL);\n        }\n      } else if (((_this$peerConn5 = this.peerConn) === null || _this$peerConn5 === void 0 ? void 0 : _this$peerConn5.iceConnectionState) == \"failed\") {\n        var _this$peerConn6;\n        this.candidatesEnded = false;\n        // Firefox for Android does not yet have support for restartIce()\n        // (the types say it's always defined though, so we have to cast\n        // to prevent typescript from warning).\n        if ((_this$peerConn6 = this.peerConn) !== null && _this$peerConn6 !== void 0 && _this$peerConn6.restartIce) {\n          var _this$peerConn7;\n          this.candidatesEnded = false;\n          logger.debug(\"Call \".concat(this.callId, \" onIceConnectionStateChanged() ice restart (state=\").concat((_this$peerConn7 = this.peerConn) === null || _this$peerConn7 === void 0 ? void 0 : _this$peerConn7.iceConnectionState, \")\"));\n          this.peerConn.restartIce();\n        } else {\n          logger.info(\"Call \".concat(this.callId, \" onIceConnectionStateChanged() hanging up call (ICE failed and no ICE restart method)\"));\n          this.hangup(CallErrorCode.IceFailed, false);\n        }\n      } else if (((_this$peerConn8 = this.peerConn) === null || _this$peerConn8 === void 0 ? void 0 : _this$peerConn8.iceConnectionState) == \"disconnected\") {\n        this.candidatesEnded = false;\n        this.iceReconnectionTimeOut = setTimeout(() => {\n          var _this$peerConn9, _this$peerConn0, _this$peerConn1;\n          logger.info(\"Call \".concat(this.callId, \" onIceConnectionStateChanged() ICE restarting because of ICE disconnected, (state=\").concat((_this$peerConn9 = this.peerConn) === null || _this$peerConn9 === void 0 ? void 0 : _this$peerConn9.iceConnectionState, \", conn=\").concat((_this$peerConn0 = this.peerConn) === null || _this$peerConn0 === void 0 ? void 0 : _this$peerConn0.connectionState, \")\"));\n          if ((_this$peerConn1 = this.peerConn) !== null && _this$peerConn1 !== void 0 && _this$peerConn1.restartIce) {\n            this.candidatesEnded = false;\n            this.peerConn.restartIce();\n          }\n          this.iceReconnectionTimeOut = undefined;\n        }, ICE_RECONNECTING_TIMEOUT);\n        this.iceDisconnectedTimeout = setTimeout(() => {\n          logger.info(\"Call \".concat(this.callId, \" onIceConnectionStateChanged() hanging up call (ICE disconnected for too long)\"));\n          this.hangup(CallErrorCode.IceFailed, false);\n        }, ICE_DISCONNECTED_TIMEOUT);\n        this.state = CallState.Connecting;\n      }\n\n      // In PTT mode, override feed status to muted when we lose connection to\n      // the peer, since we don't want to block the line if they're not saying anything.\n      // Experimenting in Chrome, this happens after 5 or 6 seconds, which is probably\n      // fast enough.\n      if (this.isPtt && [\"failed\", \"disconnected\"].includes(this.peerConn.iceConnectionState)) {\n        for (var feed of this.getRemoteFeeds()) {\n          feed.setAudioVideoMuted(true, true);\n        }\n      }\n    });\n    _defineProperty(this, \"onSignallingStateChanged\", () => {\n      var _this$peerConn10;\n      logger.debug(\"Call \".concat(this.callId, \" onSignallingStateChanged() running (state=\").concat((_this$peerConn10 = this.peerConn) === null || _this$peerConn10 === void 0 ? void 0 : _this$peerConn10.signalingState, \")\"));\n    });\n    _defineProperty(this, \"onTrack\", ev => {\n      if (ev.streams.length === 0) {\n        logger.warn(\"Call \".concat(this.callId, \" onTrack() called with streamless track streamless (kind=\").concat(ev.track.kind, \")\"));\n        return;\n      }\n      var stream = ev.streams[0];\n      this.pushRemoteFeed(stream);\n      if (!this.removeTrackListeners.has(stream)) {\n        var onRemoveTrack = () => {\n          if (stream.getTracks().length === 0) {\n            logger.info(\"Call \".concat(this.callId, \" onTrack() removing track (streamId=\").concat(stream.id, \")\"));\n            this.deleteFeedByStream(stream);\n            stream.removeEventListener(\"removetrack\", onRemoveTrack);\n            this.removeTrackListeners.delete(stream);\n          }\n        };\n        stream.addEventListener(\"removetrack\", onRemoveTrack);\n        this.removeTrackListeners.set(stream, onRemoveTrack);\n      }\n    });\n    _defineProperty(this, \"onDataChannel\", ev => {\n      this.emit(CallEvent.DataChannel, ev.channel, this);\n    });\n    _defineProperty(this, \"onNegotiationNeeded\", /*#__PURE__*/_asyncToGenerator(function* () {\n      logger.info(\"Call \".concat(_this.callId, \" onNegotiationNeeded() negotiation is needed!\"));\n      if (_this.state !== CallState.CreateOffer && _this.opponentVersion === 0) {\n        logger.info(\"Call \".concat(_this.callId, \" onNegotiationNeeded() opponent does not support renegotiation: ignoring negotiationneeded event\"));\n        return;\n      }\n      _this.queueGotLocalOffer();\n    }));\n    _defineProperty(this, \"onHangupReceived\", msg => {\n      logger.debug(\"Call \".concat(this.callId, \" onHangupReceived() running\"));\n\n      // party ID must match (our chosen partner hanging up the call) or be undefined (we haven't chosen\n      // a partner yet but we're treating the hangup as a reject as per VoIP v0)\n      if (this.partyIdMatches(msg) || this.state === CallState.Ringing) {\n        // default reason is user_hangup\n        this.terminate(CallParty.Remote, msg.reason || CallErrorCode.UserHangup, true);\n      } else {\n        logger.info(\"Call \".concat(this.callId, \" onHangupReceived() ignoring message from party ID \").concat(msg.party_id, \": our partner is \").concat(this.opponentPartyId));\n      }\n    });\n    _defineProperty(this, \"onRejectReceived\", msg => {\n      logger.debug(\"Call \".concat(this.callId, \" onRejectReceived() running\"));\n\n      // No need to check party_id for reject because if we'd received either\n      // an answer or reject, we wouldn't be in state InviteSent\n\n      var shouldTerminate =\n      // reject events also end the call if it's ringing: it's another of\n      // our devices rejecting the call.\n      [CallState.InviteSent, CallState.Ringing].includes(this.state) ||\n      // also if we're in the init state and it's an inbound call, since\n      // this means we just haven't entered the ringing state yet\n      this.state === CallState.Fledgling && this.direction === CallDirection.Inbound;\n      if (shouldTerminate) {\n        this.terminate(CallParty.Remote, msg.reason || CallErrorCode.UserHangup, true);\n      } else {\n        logger.debug(\"Call \".concat(this.callId, \" onRejectReceived() called in wrong state (state=\").concat(this.state, \")\"));\n      }\n    });\n    _defineProperty(this, \"onAnsweredElsewhere\", msg => {\n      logger.debug(\"Call \".concat(this.callId, \" onAnsweredElsewhere() running\"));\n      this.terminate(CallParty.Remote, CallErrorCode.AnsweredElsewhere, true);\n    });\n    this.roomId = opts.roomId;\n    this.invitee = opts.invitee;\n    this.client = opts.client;\n    if (!this.client.deviceId) throw new Error(\"Client must have a device ID to start calls\");\n    this.forceTURN = (_opts$forceTURN = opts.forceTURN) !== null && _opts$forceTURN !== void 0 ? _opts$forceTURN : false;\n    this.ourPartyId = this.client.deviceId;\n    this.opponentDeviceId = opts.opponentDeviceId;\n    this.opponentSessionId = opts.opponentSessionId;\n    this.groupCallId = opts.groupCallId;\n    // Array of Objects with urls, username, credential keys\n    this.turnServers = opts.turnServers || [];\n    if (this.turnServers.length === 0 && this.client.isFallbackICEServerAllowed()) {\n      this.turnServers.push({\n        urls: [FALLBACK_ICE_SERVER]\n      });\n    }\n    for (var server of this.turnServers) {\n      checkObjectHasKeys(server, [\"urls\"]);\n    }\n    this.callId = genCallID();\n    // If the Client provides calls without audio and video we need a datachannel for a webrtc connection\n    this.isOnlyDataChannelAllowed = this.client.isVoipWithNoMediaAllowed;\n  }\n\n  /**\n   * Place a voice call to this room.\n   * @throws If you have not specified a listener for 'error' events.\n   */\n  placeVoiceCall() {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      yield _this2.placeCall(true, false);\n    })();\n  }\n\n  /**\n   * Place a video call to this room.\n   * @throws If you have not specified a listener for 'error' events.\n   */\n  placeVideoCall() {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      yield _this3.placeCall(true, true);\n    })();\n  }\n\n  /**\n   * Create a datachannel using this call's peer connection.\n   * @param label - A human readable label for this datachannel\n   * @param options - An object providing configuration options for the data channel.\n   */\n  createDataChannel(label, options) {\n    var dataChannel = this.peerConn.createDataChannel(label, options);\n    this.emit(CallEvent.DataChannel, dataChannel, this);\n    return dataChannel;\n  }\n  getOpponentMember() {\n    return this.opponentMember;\n  }\n  getOpponentDeviceId() {\n    return this.opponentDeviceId;\n  }\n  getOpponentSessionId() {\n    return this.opponentSessionId;\n  }\n  opponentCanBeTransferred() {\n    return Boolean(this.opponentCaps && this.opponentCaps[\"m.call.transferee\"]);\n  }\n  opponentSupportsDTMF() {\n    return Boolean(this.opponentCaps && this.opponentCaps[\"m.call.dtmf\"]);\n  }\n  getRemoteAssertedIdentity() {\n    return this.remoteAssertedIdentity;\n  }\n  get state() {\n    return this._state;\n  }\n  set state(state) {\n    var oldState = this._state;\n    this._state = state;\n    this.emit(CallEvent.State, state, oldState, this);\n  }\n  get type() {\n    // we may want to look for a video receiver here rather than a track to match the\n    // sender behaviour, although in practice they should be the same thing\n    return this.hasUserMediaVideoSender || this.hasRemoteUserMediaVideoTrack ? CallType.Video : CallType.Voice;\n  }\n  get hasLocalUserMediaVideoTrack() {\n    var _this$localUsermediaS;\n    return !!((_this$localUsermediaS = this.localUsermediaStream) !== null && _this$localUsermediaS !== void 0 && _this$localUsermediaS.getVideoTracks().length);\n  }\n  get hasRemoteUserMediaVideoTrack() {\n    return this.getRemoteFeeds().some(feed => {\n      var _feed$stream;\n      return feed.purpose === SDPStreamMetadataPurpose.Usermedia && ((_feed$stream = feed.stream) === null || _feed$stream === void 0 ? void 0 : _feed$stream.getVideoTracks().length);\n    });\n  }\n  get hasLocalUserMediaAudioTrack() {\n    var _this$localUsermediaS2;\n    return !!((_this$localUsermediaS2 = this.localUsermediaStream) !== null && _this$localUsermediaS2 !== void 0 && _this$localUsermediaS2.getAudioTracks().length);\n  }\n  get hasRemoteUserMediaAudioTrack() {\n    return this.getRemoteFeeds().some(feed => {\n      var _feed$stream2;\n      return feed.purpose === SDPStreamMetadataPurpose.Usermedia && !!((_feed$stream2 = feed.stream) !== null && _feed$stream2 !== void 0 && _feed$stream2.getAudioTracks().length);\n    });\n  }\n  get hasUserMediaAudioSender() {\n    var _this$transceivers$ge;\n    return Boolean((_this$transceivers$ge = this.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Usermedia, \"audio\"))) === null || _this$transceivers$ge === void 0 ? void 0 : _this$transceivers$ge.sender);\n  }\n  get hasUserMediaVideoSender() {\n    var _this$transceivers$ge2;\n    return Boolean((_this$transceivers$ge2 = this.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Usermedia, \"video\"))) === null || _this$transceivers$ge2 === void 0 ? void 0 : _this$transceivers$ge2.sender);\n  }\n  get localUsermediaFeed() {\n    return this.getLocalFeeds().find(feed => feed.purpose === SDPStreamMetadataPurpose.Usermedia);\n  }\n  get localScreensharingFeed() {\n    return this.getLocalFeeds().find(feed => feed.purpose === SDPStreamMetadataPurpose.Screenshare);\n  }\n  get localUsermediaStream() {\n    var _this$localUsermediaF;\n    return (_this$localUsermediaF = this.localUsermediaFeed) === null || _this$localUsermediaF === void 0 ? void 0 : _this$localUsermediaF.stream;\n  }\n  get localScreensharingStream() {\n    var _this$localScreenshar;\n    return (_this$localScreenshar = this.localScreensharingFeed) === null || _this$localScreenshar === void 0 ? void 0 : _this$localScreenshar.stream;\n  }\n  get remoteUsermediaFeed() {\n    return this.getRemoteFeeds().find(feed => feed.purpose === SDPStreamMetadataPurpose.Usermedia);\n  }\n  get remoteScreensharingFeed() {\n    return this.getRemoteFeeds().find(feed => feed.purpose === SDPStreamMetadataPurpose.Screenshare);\n  }\n  get remoteUsermediaStream() {\n    var _this$remoteUsermedia;\n    return (_this$remoteUsermedia = this.remoteUsermediaFeed) === null || _this$remoteUsermedia === void 0 ? void 0 : _this$remoteUsermedia.stream;\n  }\n  get remoteScreensharingStream() {\n    var _this$remoteScreensha;\n    return (_this$remoteScreensha = this.remoteScreensharingFeed) === null || _this$remoteScreensha === void 0 ? void 0 : _this$remoteScreensha.stream;\n  }\n  getFeedByStreamId(streamId) {\n    return this.getFeeds().find(feed => feed.stream.id === streamId);\n  }\n\n  /**\n   * Returns an array of all CallFeeds\n   * @returns CallFeeds\n   */\n  getFeeds() {\n    return this.feeds;\n  }\n\n  /**\n   * Returns an array of all local CallFeeds\n   * @returns local CallFeeds\n   */\n  getLocalFeeds() {\n    return this.feeds.filter(feed => feed.isLocal());\n  }\n\n  /**\n   * Returns an array of all remote CallFeeds\n   * @returns remote CallFeeds\n   */\n  getRemoteFeeds() {\n    return this.feeds.filter(feed => !feed.isLocal());\n  }\n  initOpponentCrypto() {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      var _this4$getOpponentMem;\n      if (!_this4.opponentDeviceId) return;\n      if (!_this4.client.getUseE2eForGroupCall()) return;\n      // It's possible to want E2EE and yet not have the means to manage E2EE\n      // ourselves (for example if the client is a RoomWidgetClient)\n      if (!_this4.client.getCrypto()) {\n        // All we know is the device ID\n        _this4.hasOpponentDeviceInfo = true;\n        return;\n      }\n      var userId = _this4.invitee || ((_this4$getOpponentMem = _this4.getOpponentMember()) === null || _this4$getOpponentMem === void 0 ? void 0 : _this4$getOpponentMem.userId);\n      if (!userId) throw new Error(\"Couldn't find opponent user ID to init crypto\");\n\n      // Here we were calling `MatrixClient.crypto.deviceList.downloadKeys` which is not supported by the rust cryptography.\n      _this4.hasOpponentDeviceInfo = false;\n      throw new GroupCallUnknownDeviceError(userId);\n    })();\n  }\n\n  /**\n   * Generates and returns localSDPStreamMetadata\n   * @returns localSDPStreamMetadata\n   */\n  getLocalSDPStreamMetadata() {\n    var updateStreamIds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n    var metadata = {};\n    for (var localFeed of this.getLocalFeeds()) {\n      if (updateStreamIds) {\n        localFeed.sdpMetadataStreamId = localFeed.stream.id;\n      }\n      metadata[localFeed.sdpMetadataStreamId] = {\n        purpose: localFeed.purpose,\n        audio_muted: localFeed.isAudioMuted(),\n        video_muted: localFeed.isVideoMuted()\n      };\n    }\n    return metadata;\n  }\n\n  /**\n   * Returns true if there are no incoming feeds,\n   * otherwise returns false\n   * @returns no incoming feeds\n   */\n  noIncomingFeeds() {\n    return !this.feeds.some(feed => !feed.isLocal());\n  }\n  pushRemoteFeed(stream) {\n    // Fallback to old behavior if the other side doesn't support SDPStreamMetadata\n    if (!this.opponentSupportsSDPStreamMetadata()) {\n      this.pushRemoteFeedWithoutMetadata(stream);\n      return;\n    }\n    var userId = this.getOpponentMember().userId;\n    var purpose = this.remoteSDPStreamMetadata[stream.id].purpose;\n    var audioMuted = this.remoteSDPStreamMetadata[stream.id].audio_muted;\n    var videoMuted = this.remoteSDPStreamMetadata[stream.id].video_muted;\n    if (!purpose) {\n      logger.warn(\"Call \".concat(this.callId, \" pushRemoteFeed() ignoring stream because we didn't get any metadata about it (streamId=\").concat(stream.id, \")\"));\n      return;\n    }\n    if (this.getFeedByStreamId(stream.id)) {\n      logger.warn(\"Call \".concat(this.callId, \" pushRemoteFeed() ignoring stream because we already have a feed for it (streamId=\").concat(stream.id, \")\"));\n      return;\n    }\n    this.feeds.push(new CallFeed({\n      client: this.client,\n      call: this,\n      roomId: this.roomId,\n      userId,\n      deviceId: this.getOpponentDeviceId(),\n      stream,\n      purpose,\n      audioMuted,\n      videoMuted\n    }));\n    this.emit(CallEvent.FeedsChanged, this.feeds, this);\n    logger.info(\"Call \".concat(this.callId, \" pushRemoteFeed() pushed stream (streamId=\").concat(stream.id, \", active=\").concat(stream.active, \", purpose=\").concat(purpose, \")\"));\n  }\n\n  /**\n   * This method is used ONLY if the other client doesn't support sending SDPStreamMetadata\n   */\n  pushRemoteFeedWithoutMetadata(stream) {\n    var _this$feeds$find;\n    var userId = this.getOpponentMember().userId;\n    // We can guess the purpose here since the other client can only send one stream\n    var purpose = SDPStreamMetadataPurpose.Usermedia;\n    var oldRemoteStream = (_this$feeds$find = this.feeds.find(feed => !feed.isLocal())) === null || _this$feeds$find === void 0 ? void 0 : _this$feeds$find.stream;\n\n    // Note that we check by ID and always set the remote stream: Chrome appears\n    // to make new stream objects when transceiver directionality is changed and the 'active'\n    // status of streams change - Dave\n    // If we already have a stream, check this stream has the same id\n    if (oldRemoteStream && stream.id !== oldRemoteStream.id) {\n      logger.warn(\"Call \".concat(this.callId, \" pushRemoteFeedWithoutMetadata() ignoring new stream because we already have stream (streamId=\").concat(stream.id, \")\"));\n      return;\n    }\n    if (this.getFeedByStreamId(stream.id)) {\n      logger.warn(\"Call \".concat(this.callId, \" pushRemoteFeedWithoutMetadata() ignoring stream because we already have a feed for it (streamId=\").concat(stream.id, \")\"));\n      return;\n    }\n    this.feeds.push(new CallFeed({\n      client: this.client,\n      call: this,\n      roomId: this.roomId,\n      audioMuted: false,\n      videoMuted: false,\n      userId,\n      deviceId: this.getOpponentDeviceId(),\n      stream,\n      purpose\n    }));\n    this.emit(CallEvent.FeedsChanged, this.feeds, this);\n    logger.info(\"Call \".concat(this.callId, \" pushRemoteFeedWithoutMetadata() pushed stream (streamId=\").concat(stream.id, \", active=\").concat(stream.active, \")\"));\n  }\n  pushNewLocalFeed(stream, purpose) {\n    var addToPeerConnection = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n    var userId = this.client.getUserId();\n\n    // Tracks don't always start off enabled, eg. chrome will give a disabled\n    // audio track if you ask for user media audio and already had one that\n    // you'd set to disabled (presumably because it clones them internally).\n    setTracksEnabled(stream.getAudioTracks(), true);\n    setTracksEnabled(stream.getVideoTracks(), true);\n    if (this.getFeedByStreamId(stream.id)) {\n      logger.warn(\"Call \".concat(this.callId, \" pushNewLocalFeed() ignoring stream because we already have a feed for it (streamId=\").concat(stream.id, \")\"));\n      return;\n    }\n    this.pushLocalFeed(new CallFeed({\n      client: this.client,\n      roomId: this.roomId,\n      audioMuted: false,\n      videoMuted: false,\n      userId,\n      deviceId: this.getOpponentDeviceId(),\n      stream,\n      purpose\n    }), addToPeerConnection);\n  }\n\n  /**\n   * Pushes supplied feed to the call\n   * @param callFeed - to push\n   * @param addToPeerConnection - whether to add the tracks to the peer connection\n   */\n  pushLocalFeed(callFeed) {\n    var _this5 = this;\n    var addToPeerConnection = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n    if (this.feeds.some(feed => callFeed.stream.id === feed.stream.id)) {\n      logger.info(\"Call \".concat(this.callId, \" pushLocalFeed() ignoring duplicate local stream (streamId=\").concat(callFeed.stream.id, \")\"));\n      return;\n    }\n    this.feeds.push(callFeed);\n    if (addToPeerConnection) {\n      var _loop = function _loop() {\n        logger.info(\"Call \".concat(_this5.callId, \" pushLocalFeed() adding track to peer connection (id=\").concat(track.id, \", kind=\").concat(track.kind, \", streamId=\").concat(callFeed.stream.id, \", streamPurpose=\").concat(callFeed.purpose, \", enabled=\").concat(track.enabled, \")\"));\n        var tKey = getTransceiverKey(callFeed.purpose, track.kind);\n        if (_this5.transceivers.has(tKey)) {\n          // we already have a sender, so we re-use it. We try to re-use transceivers as much\n          // as possible because they can't be removed once added, so otherwise they just\n          // accumulate which makes the SDP very large very quickly: in fact it only takes\n          // about 6 video tracks to exceed the maximum size of an Olm-encrypted\n          // Matrix event.\n          var transceiver = _this5.transceivers.get(tKey);\n          transceiver.sender.replaceTrack(track);\n          // set the direction to indicate we're going to start sending again\n          // (this will trigger the re-negotiation)\n          transceiver.direction = transceiver.direction === \"inactive\" ? \"sendonly\" : \"sendrecv\";\n        } else {\n          // create a new one. We need to use addTrack rather addTransceiver for this because firefox\n          // doesn't yet implement RTCRTPSender.setStreams()\n          // (https://bugzilla.mozilla.org/show_bug.cgi?id=1510802) so we'd have no way to group the\n          // two tracks together into a stream.\n          var newSender = _this5.peerConn.addTrack(track, callFeed.stream);\n\n          // now go & fish for the new transceiver\n          var newTransceiver = _this5.peerConn.getTransceivers().find(t => t.sender === newSender);\n          if (newTransceiver) {\n            _this5.transceivers.set(tKey, newTransceiver);\n          } else {\n            logger.warn(\"Call \".concat(_this5.callId, \" pushLocalFeed() didn't find a matching transceiver after adding track!\"));\n          }\n        }\n      };\n      for (var track of callFeed.stream.getTracks()) {\n        _loop();\n      }\n    }\n    logger.info(\"Call \".concat(this.callId, \" pushLocalFeed() pushed stream (id=\").concat(callFeed.stream.id, \", active=\").concat(callFeed.stream.active, \", purpose=\").concat(callFeed.purpose, \")\"));\n    this.emit(CallEvent.FeedsChanged, this.feeds, this);\n  }\n\n  /**\n   * Removes local call feed from the call and its tracks from the peer\n   * connection\n   * @param callFeed - to remove\n   */\n  removeLocalFeed(callFeed) {\n    var audioTransceiverKey = getTransceiverKey(callFeed.purpose, \"audio\");\n    var videoTransceiverKey = getTransceiverKey(callFeed.purpose, \"video\");\n    for (var transceiverKey of [audioTransceiverKey, videoTransceiverKey]) {\n      // this is slightly mixing the track and transceiver API but is basically just shorthand.\n      // There is no way to actually remove a transceiver, so this just sets it to inactive\n      // (or recvonly) and replaces the source with nothing.\n      if (this.transceivers.has(transceiverKey)) {\n        var transceiver = this.transceivers.get(transceiverKey);\n        if (transceiver.sender) this.peerConn.removeTrack(transceiver.sender);\n      }\n    }\n    if (callFeed.purpose === SDPStreamMetadataPurpose.Screenshare) {\n      this.client.getMediaHandler().stopScreensharingStream(callFeed.stream);\n    }\n    this.deleteFeed(callFeed);\n  }\n  deleteAllFeeds() {\n    for (var feed of this.feeds) {\n      if (!feed.isLocal() || !this.groupCallId) {\n        feed.dispose();\n      }\n    }\n    this.feeds = [];\n    this.emit(CallEvent.FeedsChanged, this.feeds, this);\n  }\n  deleteFeedByStream(stream) {\n    var feed = this.getFeedByStreamId(stream.id);\n    if (!feed) {\n      logger.warn(\"Call \".concat(this.callId, \" deleteFeedByStream() didn't find the feed to delete (streamId=\").concat(stream.id, \")\"));\n      return;\n    }\n    this.deleteFeed(feed);\n  }\n  deleteFeed(feed) {\n    feed.dispose();\n    this.feeds.splice(this.feeds.indexOf(feed), 1);\n    this.emit(CallEvent.FeedsChanged, this.feeds, this);\n  }\n\n  // The typescript definitions have this type as 'any' :(\n  getCurrentCallStats() {\n    var _this6 = this;\n    return _asyncToGenerator(function* () {\n      if (_this6.callHasEnded()) {\n        return _this6.callStatsAtEnd;\n      }\n      return _this6.collectCallStats();\n    })();\n  }\n  collectCallStats() {\n    var _this7 = this;\n    return _asyncToGenerator(function* () {\n      // This happens when the call fails before it starts.\n      // For example when we fail to get capture sources\n      if (!_this7.peerConn) return;\n      var statsReport = yield _this7.peerConn.getStats();\n      var stats = [];\n      statsReport.forEach(item => {\n        stats.push(item);\n      });\n      return stats;\n    })();\n  }\n\n  /**\n   * Configure this call from an invite event. Used by MatrixClient.\n   * @param event - The m.call.invite event\n   */\n  initWithInvite(event) {\n    var _this8 = this;\n    return _asyncToGenerator(function* () {\n      var _this8$feeds$find;\n      var invite = event.getContent();\n      _this8.direction = CallDirection.Inbound;\n\n      // make sure we have valid turn creds. Unless something's gone wrong, it should\n      // poll and keep the credentials valid so this should be instant.\n      var haveTurnCreds = yield _this8.client.checkTurnServers();\n      if (!haveTurnCreds) {\n        logger.warn(\"Call \".concat(_this8.callId, \" initWithInvite() failed to get TURN credentials! Proceeding with call anyway...\"));\n      }\n      var sdpStreamMetadata = invite[SDPStreamMetadataKey];\n      if (sdpStreamMetadata) {\n        _this8.updateRemoteSDPStreamMetadata(sdpStreamMetadata);\n      } else {\n        logger.debug(\"Call \".concat(_this8.callId, \" initWithInvite() did not get any SDPStreamMetadata! Can not send/receive multiple streams\"));\n      }\n      _this8.peerConn = _this8.createPeerConnection();\n      _this8.emit(CallEvent.PeerConnectionCreated, _this8.peerConn, _this8);\n      // we must set the party ID before await-ing on anything: the call event\n      // handler will start giving us more call events (eg. candidates) so if\n      // we haven't set the party ID, we'll ignore them.\n      _this8.chooseOpponent(event);\n      yield _this8.initOpponentCrypto();\n      try {\n        yield _this8.peerConn.setRemoteDescription(invite.offer);\n        logger.debug(\"Call \".concat(_this8.callId, \" initWithInvite() set remote description: \").concat(invite.offer.type));\n        yield _this8.addBufferedIceCandidates();\n      } catch (e) {\n        logger.debug(\"Call \".concat(_this8.callId, \" initWithInvite() failed to set remote description\"), e);\n        _this8.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);\n        return;\n      }\n      var remoteStream = (_this8$feeds$find = _this8.feeds.find(feed => !feed.isLocal())) === null || _this8$feeds$find === void 0 ? void 0 : _this8$feeds$find.stream;\n\n      // According to previous comments in this file, firefox at some point did not\n      // add streams until media started arriving on them. Testing latest firefox\n      // (81 at time of writing), this is no longer a problem, so let's do it the correct way.\n      //\n      // For example in case of no media webrtc connections like screen share only call we have to allow webrtc\n      // connections without remote media. In this case we always use a data channel. At the moment we allow as well\n      // only data channel as media in the WebRTC connection with this setup here.\n      if (!_this8.isOnlyDataChannelAllowed && (!remoteStream || remoteStream.getTracks().length === 0)) {\n        logger.error(\"Call \".concat(_this8.callId, \" initWithInvite() no remote stream or no tracks after setting remote description!\"));\n        _this8.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);\n        return;\n      }\n      _this8.state = CallState.Ringing;\n      if (event.getLocalAge()) {\n        // Time out the call if it's ringing for too long\n        var ringingTimer = setTimeout(() => {\n          if (_this8.state == CallState.Ringing) {\n            var _this8$stats;\n            logger.debug(\"Call \".concat(_this8.callId, \" initWithInvite() invite has expired. Hanging up.\"));\n            _this8.hangupParty = CallParty.Remote; // effectively\n            _this8.state = CallState.Ended;\n            _this8.stopAllMedia();\n            if (_this8.peerConn.signalingState != \"closed\") {\n              _this8.peerConn.close();\n            }\n            (_this8$stats = _this8.stats) === null || _this8$stats === void 0 || _this8$stats.removeStatsReportGatherer(_this8.callId);\n            _this8.emit(CallEvent.Hangup, _this8);\n          }\n        }, invite.lifetime - event.getLocalAge());\n        var onState = state => {\n          if (state !== CallState.Ringing) {\n            clearTimeout(ringingTimer);\n            _this8.off(CallEvent.State, onState);\n          }\n        };\n        _this8.on(CallEvent.State, onState);\n      }\n    })();\n  }\n\n  /**\n   * Configure this call from a hangup or reject event. Used by MatrixClient.\n   * @param event - The m.call.hangup event\n   */\n  initWithHangup(event) {\n    // perverse as it may seem, sometimes we want to instantiate a call with a\n    // hangup message (because when getting the state of the room on load, events\n    // come in reverse order and we want to remember that a call has been hung up)\n    this.state = CallState.Ended;\n  }\n  shouldAnswerWithMediaType(wantedValue, valueOfTheOtherSide, type) {\n    if (wantedValue && !valueOfTheOtherSide) {\n      // TODO: Figure out how to do this\n      logger.warn(\"Call \".concat(this.callId, \" shouldAnswerWithMediaType() unable to answer with \").concat(type, \" because the other side isn't sending it either.\"));\n      return false;\n    } else if (!isNullOrUndefined(wantedValue) && wantedValue !== valueOfTheOtherSide && !this.opponentSupportsSDPStreamMetadata()) {\n      logger.warn(\"Call \".concat(this.callId, \" shouldAnswerWithMediaType() unable to answer with \").concat(type, \"=\").concat(wantedValue, \" because the other side doesn't support it. Answering with \").concat(type, \"=\").concat(valueOfTheOtherSide, \".\"));\n      return valueOfTheOtherSide;\n    }\n    return wantedValue !== null && wantedValue !== void 0 ? wantedValue : valueOfTheOtherSide;\n  }\n\n  /**\n   * Answer a call.\n   */\n  answer(audio, video) {\n    var _this9 = this;\n    return _asyncToGenerator(function* () {\n      if (_this9.inviteOrAnswerSent) return;\n      // TODO: Figure out how to do this\n      if (audio === false && video === false) throw new Error(\"You CANNOT answer a call without media\");\n      if (!_this9.localUsermediaStream && !_this9.waitForLocalAVStream) {\n        var prevState = _this9.state;\n        var answerWithAudio = _this9.shouldAnswerWithMediaType(audio, _this9.hasRemoteUserMediaAudioTrack, \"audio\");\n        var answerWithVideo = _this9.shouldAnswerWithMediaType(video, _this9.hasRemoteUserMediaVideoTrack, \"video\");\n        _this9.state = CallState.WaitLocalMedia;\n        _this9.waitForLocalAVStream = true;\n        try {\n          var _this9$client$getDevi;\n          var stream = yield _this9.client.getMediaHandler().getUserMediaStream(answerWithAudio, answerWithVideo);\n          _this9.waitForLocalAVStream = false;\n          var usermediaFeed = new CallFeed({\n            client: _this9.client,\n            roomId: _this9.roomId,\n            userId: _this9.client.getUserId(),\n            deviceId: (_this9$client$getDevi = _this9.client.getDeviceId()) !== null && _this9$client$getDevi !== void 0 ? _this9$client$getDevi : undefined,\n            stream,\n            purpose: SDPStreamMetadataPurpose.Usermedia,\n            audioMuted: false,\n            videoMuted: false\n          });\n          var feeds = [usermediaFeed];\n          if (_this9.localScreensharingFeed) {\n            feeds.push(_this9.localScreensharingFeed);\n          }\n          _this9.answerWithCallFeeds(feeds);\n        } catch (e) {\n          if (answerWithVideo) {\n            // Try to answer without video\n            logger.warn(\"Call \".concat(_this9.callId, \" answer() failed to getUserMedia(), trying to getUserMedia() without video\"));\n            _this9.state = prevState;\n            _this9.waitForLocalAVStream = false;\n            yield _this9.answer(answerWithAudio, false);\n          } else {\n            _this9.getUserMediaFailed(e);\n            return;\n          }\n        }\n      } else if (_this9.waitForLocalAVStream) {\n        _this9.state = CallState.WaitLocalMedia;\n      }\n    })();\n  }\n  answerWithCallFeeds(callFeeds) {\n    if (this.inviteOrAnswerSent) return;\n    this.queueGotCallFeedsForAnswer(callFeeds);\n  }\n\n  /**\n   * Replace this call with a new call, e.g. for glare resolution. Used by\n   * MatrixClient.\n   * @param newCall - The new call.\n   */\n  replacedBy(newCall) {\n    logger.debug(\"Call \".concat(this.callId, \" replacedBy() running (newCallId=\").concat(newCall.callId, \")\"));\n    if (this.state === CallState.WaitLocalMedia) {\n      logger.debug(\"Call \".concat(this.callId, \" replacedBy() telling new call to wait for local media (newCallId=\").concat(newCall.callId, \")\"));\n      newCall.waitForLocalAVStream = true;\n    } else if ([CallState.CreateOffer, CallState.InviteSent].includes(this.state)) {\n      if (newCall.direction === CallDirection.Outbound) {\n        newCall.queueGotCallFeedsForAnswer([]);\n      } else {\n        logger.debug(\"Call \".concat(this.callId, \" replacedBy() handing local stream to new call(newCallId=\").concat(newCall.callId, \")\"));\n        newCall.queueGotCallFeedsForAnswer(this.getLocalFeeds().map(feed => feed.clone()));\n      }\n    }\n    this.successor = newCall;\n    this.emit(CallEvent.Replaced, newCall, this);\n    this.hangup(CallErrorCode.Replaced, true);\n  }\n\n  /**\n   * Hangup a call.\n   * @param reason - The reason why the call is being hung up.\n   * @param suppressEvent - True to suppress emitting an event.\n   */\n  hangup(reason, suppressEvent) {\n    if (this.callHasEnded()) return;\n    logger.debug(\"Call \".concat(this.callId, \" hangup() ending call (reason=\").concat(reason, \")\"));\n    this.terminate(CallParty.Local, reason, !suppressEvent);\n    // We don't want to send hangup here if we didn't even get to sending an invite\n    if ([CallState.Fledgling, CallState.WaitLocalMedia].includes(this.state)) return;\n    var content = {};\n    // Don't send UserHangup reason to older clients\n    if (this.opponentVersion && this.opponentVersion !== 0 || reason !== CallErrorCode.UserHangup) {\n      content[\"reason\"] = reason;\n    }\n    this.sendVoipEvent(EventType.CallHangup, content);\n  }\n\n  /**\n   * Reject a call\n   * This used to be done by calling hangup, but is a separate method and protocol\n   * event as of MSC2746.\n   */\n  reject() {\n    if (this.state !== CallState.Ringing) {\n      throw Error(\"Call must be in 'ringing' state to reject!\");\n    }\n    if (this.opponentVersion === 0) {\n      logger.info(\"Call \".concat(this.callId, \" reject() opponent version is less than 1: sending hangup instead of reject (opponentVersion=\").concat(this.opponentVersion, \")\"));\n      this.hangup(CallErrorCode.UserHangup, true);\n      return;\n    }\n    logger.debug(\"Rejecting call: \" + this.callId);\n    this.terminate(CallParty.Local, CallErrorCode.UserHangup, true);\n    this.sendVoipEvent(EventType.CallReject, {});\n  }\n\n  /**\n   * Adds an audio and/or video track - upgrades the call\n   * @param audio - should add an audio track\n   * @param video - should add an video track\n   */\n  upgradeCall(audio, video) {\n    var _this0 = this;\n    return _asyncToGenerator(function* () {\n      // We don't do call downgrades\n      if (!audio && !video) return;\n      if (!_this0.opponentSupportsSDPStreamMetadata()) return;\n      try {\n        logger.debug(\"Call \".concat(_this0.callId, \" upgradeCall() upgrading call (audio=\").concat(audio, \", video=\").concat(video, \")\"));\n        var getAudio = audio || _this0.hasLocalUserMediaAudioTrack;\n        var getVideo = video || _this0.hasLocalUserMediaVideoTrack;\n\n        // updateLocalUsermediaStream() will take the tracks, use them as\n        // replacement and throw the stream away, so it isn't reusable\n        var stream = yield _this0.client.getMediaHandler().getUserMediaStream(getAudio, getVideo, false);\n        yield _this0.updateLocalUsermediaStream(stream, audio, video);\n      } catch (error) {\n        logger.error(\"Call \".concat(_this0.callId, \" upgradeCall() failed to upgrade the call\"), error);\n        _this0.emit(CallEvent.Error, new CallError(CallErrorCode.NoUserMedia, \"Failed to get camera access: \", error), _this0);\n      }\n    })();\n  }\n\n  /**\n   * Returns true if this.remoteSDPStreamMetadata is defined, otherwise returns false\n   * @returns can screenshare\n   */\n  opponentSupportsSDPStreamMetadata() {\n    return Boolean(this.remoteSDPStreamMetadata);\n  }\n\n  /**\n   * If there is a screensharing stream returns true, otherwise returns false\n   * @returns is screensharing\n   */\n  isScreensharing() {\n    return Boolean(this.localScreensharingStream);\n  }\n\n  /**\n   * Starts/stops screensharing\n   * @param enabled - the desired screensharing state\n   * @param opts - screen sharing options\n   * @returns new screensharing state\n   */\n  setScreensharingEnabled(enabled, opts) {\n    var _this1 = this;\n    return _asyncToGenerator(function* () {\n      // Skip if there is nothing to do\n      if (enabled && _this1.isScreensharing()) {\n        logger.warn(\"Call \".concat(_this1.callId, \" setScreensharingEnabled() there is already a screensharing stream - there is nothing to do!\"));\n        return true;\n      } else if (!enabled && !_this1.isScreensharing()) {\n        logger.warn(\"Call \".concat(_this1.callId, \" setScreensharingEnabled() there already isn't a screensharing stream - there is nothing to do!\"));\n        return false;\n      }\n\n      // Fallback to replaceTrack()\n      if (!_this1.opponentSupportsSDPStreamMetadata()) {\n        return _this1.setScreensharingEnabledWithoutMetadataSupport(enabled, opts);\n      }\n      logger.debug(\"Call \".concat(_this1.callId, \" setScreensharingEnabled() running (enabled=\").concat(enabled, \")\"));\n      if (enabled) {\n        try {\n          var stream = yield _this1.client.getMediaHandler().getScreensharingStream(opts);\n          if (!stream) return false;\n          _this1.pushNewLocalFeed(stream, SDPStreamMetadataPurpose.Screenshare);\n          return true;\n        } catch (err) {\n          logger.error(\"Call \".concat(_this1.callId, \" setScreensharingEnabled() failed to get screen-sharing stream:\"), err);\n          return false;\n        }\n      } else {\n        var audioTransceiver = _this1.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Screenshare, \"audio\"));\n        var videoTransceiver = _this1.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Screenshare, \"video\"));\n        for (var transceiver of [audioTransceiver, videoTransceiver]) {\n          // this is slightly mixing the track and transceiver API but is basically just shorthand\n          // for removing the sender.\n          if (transceiver && transceiver.sender) _this1.peerConn.removeTrack(transceiver.sender);\n        }\n        _this1.client.getMediaHandler().stopScreensharingStream(_this1.localScreensharingStream);\n        _this1.deleteFeedByStream(_this1.localScreensharingStream);\n        return false;\n      }\n    })();\n  }\n\n  /**\n   * Starts/stops screensharing\n   * Should be used ONLY if the opponent doesn't support SDPStreamMetadata\n   * @param enabled - the desired screensharing state\n   * @param opts - screen sharing options\n   * @returns new screensharing state\n   */\n  setScreensharingEnabledWithoutMetadataSupport(enabled, opts) {\n    var _this10 = this;\n    return _asyncToGenerator(function* () {\n      logger.debug(\"Call \".concat(_this10.callId, \" setScreensharingEnabledWithoutMetadataSupport() running (enabled=\").concat(enabled, \")\"));\n      if (enabled) {\n        try {\n          var _this10$transceivers$;\n          var stream = yield _this10.client.getMediaHandler().getScreensharingStream(opts);\n          if (!stream) return false;\n          var track = stream.getTracks().find(track => track.kind === \"video\");\n          var sender = (_this10$transceivers$ = _this10.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Usermedia, \"video\"))) === null || _this10$transceivers$ === void 0 ? void 0 : _this10$transceivers$.sender;\n          sender === null || sender === void 0 || sender.replaceTrack(track !== null && track !== void 0 ? track : null);\n          _this10.pushNewLocalFeed(stream, SDPStreamMetadataPurpose.Screenshare, false);\n          return true;\n        } catch (err) {\n          logger.error(\"Call \".concat(_this10.callId, \" setScreensharingEnabledWithoutMetadataSupport() failed to get screen-sharing stream:\"), err);\n          return false;\n        }\n      } else {\n        var _this10$localUsermedi, _this10$transceivers$2;\n        var _track = (_this10$localUsermedi = _this10.localUsermediaStream) === null || _this10$localUsermedi === void 0 ? void 0 : _this10$localUsermedi.getTracks().find(track => track.kind === \"video\");\n        var _sender = (_this10$transceivers$2 = _this10.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Usermedia, \"video\"))) === null || _this10$transceivers$2 === void 0 ? void 0 : _this10$transceivers$2.sender;\n        _sender === null || _sender === void 0 || _sender.replaceTrack(_track !== null && _track !== void 0 ? _track : null);\n        _this10.client.getMediaHandler().stopScreensharingStream(_this10.localScreensharingStream);\n        _this10.deleteFeedByStream(_this10.localScreensharingStream);\n        return false;\n      }\n    })();\n  }\n\n  /**\n   * Replaces/adds the tracks from the passed stream to the localUsermediaStream\n   * @param stream - to use a replacement for the local usermedia stream\n   */\n  updateLocalUsermediaStream(stream) {\n    var _arguments = arguments,\n      _this11 = this;\n    return _asyncToGenerator(function* () {\n      var forceAudio = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : false;\n      var forceVideo = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : false;\n      var callFeed = _this11.localUsermediaFeed;\n      var audioEnabled = forceAudio || !callFeed.isAudioMuted() && !_this11.remoteOnHold;\n      var videoEnabled = forceVideo || !callFeed.isVideoMuted() && !_this11.remoteOnHold;\n      logger.log(\"Call \".concat(_this11.callId, \" updateLocalUsermediaStream() running (streamId=\").concat(stream.id, \", audio=\").concat(audioEnabled, \", video=\").concat(videoEnabled, \")\"));\n      setTracksEnabled(stream.getAudioTracks(), audioEnabled);\n      setTracksEnabled(stream.getVideoTracks(), videoEnabled);\n\n      // We want to keep the same stream id, so we replace the tracks rather\n      // than the whole stream.\n\n      // Firstly, we replace the tracks in our localUsermediaStream.\n      for (var track of _this11.localUsermediaStream.getTracks()) {\n        _this11.localUsermediaStream.removeTrack(track);\n        track.stop();\n      }\n      for (var _track2 of stream.getTracks()) {\n        _this11.localUsermediaStream.addTrack(_track2);\n      }\n\n      // Then replace the old tracks, if possible.\n      var _loop2 = function* _loop2() {\n        var tKey = getTransceiverKey(SDPStreamMetadataPurpose.Usermedia, _track3.kind);\n        var transceiver = _this11.transceivers.get(tKey);\n        var oldSender = transceiver === null || transceiver === void 0 ? void 0 : transceiver.sender;\n        var added = false;\n        if (oldSender) {\n          try {\n            logger.info(\"Call \".concat(_this11.callId, \" updateLocalUsermediaStream() replacing track (id=\").concat(_track3.id, \", kind=\").concat(_track3.kind, \", streamId=\").concat(stream.id, \", streamPurpose=\").concat(callFeed.purpose, \")\"));\n            yield oldSender.replaceTrack(_track3);\n            // Set the direction to indicate we're going to be sending.\n            // This is only necessary in the cases where we're upgrading\n            // the call to video after downgrading it.\n            transceiver.direction = transceiver.direction === \"inactive\" ? \"sendonly\" : \"sendrecv\";\n            added = true;\n          } catch (error) {\n            logger.warn(\"Call \".concat(_this11.callId, \" updateLocalUsermediaStream() replaceTrack failed: adding new transceiver instead\"), error);\n          }\n        }\n        if (!added) {\n          logger.info(\"Call \".concat(_this11.callId, \" updateLocalUsermediaStream() adding track to peer connection (id=\").concat(_track3.id, \", kind=\").concat(_track3.kind, \", streamId=\").concat(stream.id, \", streamPurpose=\").concat(callFeed.purpose, \")\"));\n          var newSender = _this11.peerConn.addTrack(_track3, _this11.localUsermediaStream);\n          var newTransceiver = _this11.peerConn.getTransceivers().find(t => t.sender === newSender);\n          if (newTransceiver) {\n            _this11.transceivers.set(tKey, newTransceiver);\n          } else {\n            logger.warn(\"Call \".concat(_this11.callId, \" updateLocalUsermediaStream() couldn't find matching transceiver for newly added track!\"));\n          }\n        }\n      };\n      for (var _track3 of stream.getTracks()) {\n        yield* _loop2();\n      }\n    })();\n  }\n\n  /**\n   * Set whether our outbound video should be muted or not.\n   * @param muted - True to mute the outbound video.\n   * @returns the new mute state\n   */\n  setLocalVideoMuted(muted) {\n    var _this12 = this;\n    return _asyncToGenerator(function* () {\n      var _this12$localUsermedi2;\n      logger.log(\"Call \".concat(_this12.callId, \" setLocalVideoMuted() running \").concat(muted));\n\n      // if we were still thinking about stopping and removing the video\n      // track: don't, because we want it back.\n      if (!muted && _this12.stopVideoTrackTimer !== undefined) {\n        clearTimeout(_this12.stopVideoTrackTimer);\n        _this12.stopVideoTrackTimer = undefined;\n      }\n      if (!(yield _this12.client.getMediaHandler().hasVideoDevice())) {\n        return _this12.isLocalVideoMuted();\n      }\n      if (!_this12.hasUserMediaVideoSender && !muted) {\n        var _this12$localUsermedi;\n        (_this12$localUsermedi = _this12.localUsermediaFeed) === null || _this12$localUsermedi === void 0 || _this12$localUsermedi.setAudioVideoMuted(null, muted);\n        yield _this12.upgradeCall(false, true);\n        return _this12.isLocalVideoMuted();\n      }\n\n      // we may not have a video track - if not, re-request usermedia\n      if (!muted && _this12.localUsermediaStream.getVideoTracks().length === 0) {\n        var stream = yield _this12.client.getMediaHandler().getUserMediaStream(true, true);\n        yield _this12.updateLocalUsermediaStream(stream);\n      }\n      (_this12$localUsermedi2 = _this12.localUsermediaFeed) === null || _this12$localUsermedi2 === void 0 || _this12$localUsermedi2.setAudioVideoMuted(null, muted);\n      _this12.updateMuteStatus();\n      yield _this12.sendMetadataUpdate();\n\n      // if we're muting video, set a timeout to stop & remove the video track so we release\n      // the camera. We wait a short time to do this because when we disable a track, WebRTC\n      // will send black video for it. If we just stop and remove it straight away, the video\n      // will just freeze which means that when we unmute video, the other side will briefly\n      // get a static frame of us from before we muted. This way, the still frame is just black.\n      // A very small delay is not always enough so the theory here is that it needs to be long\n      // enough for WebRTC to encode a frame: 120ms should be long enough even if we're only\n      // doing 10fps.\n      if (muted) {\n        _this12.stopVideoTrackTimer = setTimeout(() => {\n          for (var t of _this12.localUsermediaStream.getVideoTracks()) {\n            t.stop();\n            _this12.localUsermediaStream.removeTrack(t);\n          }\n        }, 120);\n      }\n      return _this12.isLocalVideoMuted();\n    })();\n  }\n\n  /**\n   * Check if local video is muted.\n   *\n   * If there are multiple video tracks, <i>all</i> of the tracks need to be muted\n   * for this to return true. This means if there are no video tracks, this will\n   * return true.\n   * @returns True if the local preview video is muted, else false\n   * (including if the call is not set up yet).\n   */\n  isLocalVideoMuted() {\n    var _this$localUsermediaF2, _this$localUsermediaF3;\n    return (_this$localUsermediaF2 = (_this$localUsermediaF3 = this.localUsermediaFeed) === null || _this$localUsermediaF3 === void 0 ? void 0 : _this$localUsermediaF3.isVideoMuted()) !== null && _this$localUsermediaF2 !== void 0 ? _this$localUsermediaF2 : false;\n  }\n\n  /**\n   * Set whether the microphone should be muted or not.\n   * @param muted - True to mute the mic.\n   * @returns the new mute state\n   */\n  setMicrophoneMuted(muted) {\n    var _this13 = this;\n    return _asyncToGenerator(function* () {\n      var _this13$localUsermedi;\n      logger.log(\"Call \".concat(_this13.callId, \" setMicrophoneMuted() running \").concat(muted));\n      if (!(yield _this13.client.getMediaHandler().hasAudioDevice())) {\n        return _this13.isMicrophoneMuted();\n      }\n      if (!muted && (!_this13.hasUserMediaAudioSender || !_this13.hasLocalUserMediaAudioTrack)) {\n        yield _this13.upgradeCall(true, false);\n        return _this13.isMicrophoneMuted();\n      }\n      (_this13$localUsermedi = _this13.localUsermediaFeed) === null || _this13$localUsermedi === void 0 || _this13$localUsermedi.setAudioVideoMuted(muted, null);\n      _this13.updateMuteStatus();\n      yield _this13.sendMetadataUpdate();\n      return _this13.isMicrophoneMuted();\n    })();\n  }\n\n  /**\n   * Check if the microphone is muted.\n   *\n   * If there are multiple audio tracks, <i>all</i> of the tracks need to be muted\n   * for this to return true. This means if there are no audio tracks, this will\n   * return true.\n   * @returns True if the mic is muted, else false (including if the call\n   * is not set up yet).\n   */\n  isMicrophoneMuted() {\n    var _this$localUsermediaF4, _this$localUsermediaF5;\n    return (_this$localUsermediaF4 = (_this$localUsermediaF5 = this.localUsermediaFeed) === null || _this$localUsermediaF5 === void 0 ? void 0 : _this$localUsermediaF5.isAudioMuted()) !== null && _this$localUsermediaF4 !== void 0 ? _this$localUsermediaF4 : false;\n  }\n\n  /**\n   * @returns true if we have put the party on the other side of the call on hold\n   * (that is, we are signalling to them that we are not listening)\n   */\n  isRemoteOnHold() {\n    return this.remoteOnHold;\n  }\n  setRemoteOnHold(onHold) {\n    if (this.isRemoteOnHold() === onHold) return;\n    this.remoteOnHold = onHold;\n    for (var transceiver of this.peerConn.getTransceivers()) {\n      // We don't send hold music or anything so we're not actually\n      // sending anything, but sendrecv is fairly standard for hold and\n      // it makes it a lot easier to figure out who's put who on hold.\n      transceiver.direction = onHold ? \"sendonly\" : \"sendrecv\";\n    }\n    this.updateMuteStatus();\n    this.sendMetadataUpdate();\n    this.emit(CallEvent.RemoteHoldUnhold, this.remoteOnHold, this);\n  }\n\n  /**\n   * Indicates whether we are 'on hold' to the remote party (ie. if true,\n   * they cannot hear us).\n   * @returns true if the other party has put us on hold\n   */\n  isLocalOnHold() {\n    if (this.state !== CallState.Connected) return false;\n    var callOnHold = true;\n\n    // We consider a call to be on hold only if *all* the tracks are on hold\n    // (is this the right thing to do?)\n    for (var transceiver of this.peerConn.getTransceivers()) {\n      var trackOnHold = [\"inactive\", \"recvonly\"].includes(transceiver.currentDirection);\n      if (!trackOnHold) callOnHold = false;\n    }\n    return callOnHold;\n  }\n\n  /**\n   * Sends a DTMF digit to the other party\n   * @param digit - The digit (nb. string - '#' and '*' are dtmf too)\n   */\n  sendDtmfDigit(digit) {\n    for (var sender of this.peerConn.getSenders()) {\n      var _sender$track;\n      if (((_sender$track = sender.track) === null || _sender$track === void 0 ? void 0 : _sender$track.kind) === \"audio\" && sender.dtmf) {\n        sender.dtmf.insertDTMF(digit);\n        return;\n      }\n    }\n    throw new Error(\"Unable to find a track to send DTMF on\");\n  }\n  updateMuteStatus() {\n    var micShouldBeMuted = this.isMicrophoneMuted() || this.remoteOnHold;\n    var vidShouldBeMuted = this.isLocalVideoMuted() || this.remoteOnHold;\n    logger.log(\"Call \".concat(this.callId, \" updateMuteStatus stream \").concat(this.localUsermediaStream.id, \" micShouldBeMuted \").concat(micShouldBeMuted, \" vidShouldBeMuted \").concat(vidShouldBeMuted));\n    setTracksEnabled(this.localUsermediaStream.getAudioTracks(), !micShouldBeMuted);\n    setTracksEnabled(this.localUsermediaStream.getVideoTracks(), !vidShouldBeMuted);\n  }\n  sendMetadataUpdate() {\n    var _this14 = this;\n    return _asyncToGenerator(function* () {\n      yield _this14.sendVoipEvent(EventType.CallSDPStreamMetadataChangedPrefix, {\n        [SDPStreamMetadataKey]: _this14.getLocalSDPStreamMetadata()\n      });\n    })();\n  }\n  gotCallFeedsForInvite(callFeeds) {\n    var requestScreenshareFeed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n    if (this.successor) {\n      this.successor.queueGotCallFeedsForAnswer(callFeeds);\n      return;\n    }\n    if (this.callHasEnded()) {\n      this.stopAllMedia();\n      return;\n    }\n    for (var feed of callFeeds) {\n      this.pushLocalFeed(feed);\n    }\n    if (requestScreenshareFeed) {\n      this.peerConn.addTransceiver(\"video\", {\n        direction: \"recvonly\"\n      });\n    }\n    this.state = CallState.CreateOffer;\n    logger.debug(\"Call \".concat(this.callId, \" gotUserMediaForInvite() run\"));\n    // Now we wait for the negotiationneeded event\n  }\n  sendAnswer() {\n    var _this15 = this;\n    return _asyncToGenerator(function* () {\n      var answerContent = {\n        answer: {\n          sdp: _this15.peerConn.localDescription.sdp,\n          // type is now deprecated as of Matrix VoIP v1, but\n          // required to still be sent for backwards compat\n          type: _this15.peerConn.localDescription.type\n        },\n        [SDPStreamMetadataKey]: _this15.getLocalSDPStreamMetadata(true)\n      };\n      answerContent.capabilities = {\n        \"m.call.transferee\": _this15.client.supportsCallTransfer,\n        \"m.call.dtmf\": false\n      };\n\n      // We have just taken the local description from the peerConn which will\n      // contain all the local candidates added so far, so we can discard any candidates\n      // we had queued up because they'll be in the answer.\n      var discardCount = _this15.discardDuplicateCandidates();\n      logger.info(\"Call \".concat(_this15.callId, \" sendAnswer() discarding \").concat(discardCount, \" candidates that will be sent in answer\"));\n      try {\n        yield _this15.sendVoipEvent(EventType.CallAnswer, answerContent);\n        // If this isn't the first time we've tried to send the answer,\n        // we may have candidates queued up, so send them now.\n        _this15.inviteOrAnswerSent = true;\n      } catch (error) {\n        // We've failed to answer: back to the ringing state\n        _this15.state = CallState.Ringing;\n        if (error instanceof MatrixError && error.event) _this15.client.cancelPendingEvent(error.event);\n        var code = CallErrorCode.SendAnswer;\n        var message = \"Failed to send answer\";\n        if (error.name == \"UnknownDeviceError\") {\n          code = CallErrorCode.UnknownDevices;\n          message = \"Unknown devices present in the room\";\n        }\n        _this15.emit(CallEvent.Error, new CallError(code, message, error), _this15);\n        throw error;\n      }\n\n      // error handler re-throws so this won't happen on error, but\n      // we don't want the same error handling on the candidate queue\n      _this15.sendCandidateQueue();\n    })();\n  }\n  queueGotCallFeedsForAnswer(callFeeds) {\n    // Ensure only one negotiate/answer event is being processed at a time.\n    if (this.responsePromiseChain) {\n      this.responsePromiseChain = this.responsePromiseChain.then(() => this.gotCallFeedsForAnswer(callFeeds));\n    } else {\n      this.responsePromiseChain = this.gotCallFeedsForAnswer(callFeeds);\n    }\n  }\n\n  // Enables DTX (discontinuous transmission) on the given session to reduce\n  // bandwidth when transmitting silence\n  mungeSdp(description, mods) {\n    // The only way to enable DTX at this time is through SDP munging\n    var sdp = parseSdp(description.sdp);\n    sdp.media.forEach(media => {\n      var payloadTypeToCodecMap = new Map();\n      var codecToPayloadTypeMap = new Map();\n      for (var rtp of media.rtp) {\n        payloadTypeToCodecMap.set(rtp.payload, rtp.codec);\n        codecToPayloadTypeMap.set(rtp.codec, rtp.payload);\n      }\n      for (var mod of mods) {\n        if (mod.mediaType !== media.type) continue;\n        if (!codecToPayloadTypeMap.has(mod.codec)) {\n          logger.info(\"Call \".concat(this.callId, \" mungeSdp() ignoring SDP modifications for \").concat(mod.codec, \" as it's not present.\"));\n          continue;\n        }\n        var extraConfig = [];\n        if (mod.enableDtx !== undefined) {\n          extraConfig.push(\"usedtx=\".concat(mod.enableDtx ? \"1\" : \"0\"));\n        }\n        if (mod.maxAverageBitrate !== undefined) {\n          extraConfig.push(\"maxaveragebitrate=\".concat(mod.maxAverageBitrate));\n        }\n        var found = false;\n        for (var fmtp of media.fmtp) {\n          if (payloadTypeToCodecMap.get(fmtp.payload) === mod.codec) {\n            found = true;\n            fmtp.config += \";\" + extraConfig.join(\";\");\n          }\n        }\n        if (!found) {\n          media.fmtp.push({\n            payload: codecToPayloadTypeMap.get(mod.codec),\n            config: extraConfig.join(\";\")\n          });\n        }\n      }\n    });\n    description.sdp = writeSdp(sdp);\n  }\n  createOffer() {\n    var _this16 = this;\n    return _asyncToGenerator(function* () {\n      var offer = yield _this16.peerConn.createOffer();\n      _this16.mungeSdp(offer, getCodecParamMods(_this16.isPtt));\n      return offer;\n    })();\n  }\n  createAnswer() {\n    var _this17 = this;\n    return _asyncToGenerator(function* () {\n      var answer = yield _this17.peerConn.createAnswer();\n      _this17.mungeSdp(answer, getCodecParamMods(_this17.isPtt));\n      return answer;\n    })();\n  }\n  gotCallFeedsForAnswer(callFeeds) {\n    var _this18 = this;\n    return _asyncToGenerator(function* () {\n      if (_this18.callHasEnded()) return;\n      _this18.waitForLocalAVStream = false;\n      for (var feed of callFeeds) {\n        _this18.pushLocalFeed(feed);\n      }\n      _this18.state = CallState.CreateAnswer;\n      var answer;\n      try {\n        _this18.getRidOfRTXCodecs();\n        answer = yield _this18.createAnswer();\n      } catch (err) {\n        logger.debug(\"Call \".concat(_this18.callId, \" gotCallFeedsForAnswer() failed to create answer: \"), err);\n        _this18.terminate(CallParty.Local, CallErrorCode.CreateAnswer, true);\n        return;\n      }\n      try {\n        yield _this18.peerConn.setLocalDescription(answer);\n\n        // make sure we're still going\n        if (_this18.callHasEnded()) return;\n        _this18.state = CallState.Connecting;\n\n        // Allow a short time for initial candidates to be gathered\n        yield new Promise(resolve => {\n          setTimeout(resolve, 200);\n        });\n\n        // make sure the call hasn't ended before we continue\n        if (_this18.callHasEnded()) return;\n        _this18.sendAnswer();\n      } catch (err) {\n        logger.debug(\"Call \".concat(_this18.callId, \" gotCallFeedsForAnswer() error setting local description!\"), err);\n        _this18.terminate(CallParty.Local, CallErrorCode.SetLocalDescription, true);\n        return;\n      }\n    })();\n  }\n  onRemoteIceCandidatesReceived(ev) {\n    var _this19 = this;\n    return _asyncToGenerator(function* () {\n      if (_this19.callHasEnded()) {\n        //debuglog(\"Ignoring remote ICE candidate because call has ended\");\n        return;\n      }\n      var content = ev.getContent();\n      var candidates = content.candidates;\n      if (!candidates) {\n        logger.info(\"Call \".concat(_this19.callId, \" onRemoteIceCandidatesReceived() ignoring candidates event with no candidates!\"));\n        return;\n      }\n      var fromPartyId = content.version === 0 ? null : content.party_id || null;\n      if (_this19.opponentPartyId === undefined) {\n        // we haven't picked an opponent yet so save the candidates\n        if (fromPartyId) {\n          logger.info(\"Call \".concat(_this19.callId, \" onRemoteIceCandidatesReceived() buffering \").concat(candidates.length, \" candidates until we pick an opponent\"));\n          var bufferedCandidates = _this19.remoteCandidateBuffer.get(fromPartyId) || [];\n          bufferedCandidates.push(...candidates);\n          _this19.remoteCandidateBuffer.set(fromPartyId, bufferedCandidates);\n        }\n        return;\n      }\n      if (!_this19.partyIdMatches(content)) {\n        logger.info(\"Call \".concat(_this19.callId, \" onRemoteIceCandidatesReceived() ignoring candidates from party ID \").concat(content.party_id, \": we have chosen party ID \").concat(_this19.opponentPartyId));\n        return;\n      }\n      yield _this19.addIceCandidates(candidates);\n    })();\n  }\n\n  /**\n   * Used by MatrixClient.\n   */\n  onAnswerReceived(event) {\n    var _this20 = this;\n    return _asyncToGenerator(function* () {\n      var content = event.getContent();\n      logger.debug(\"Call \".concat(_this20.callId, \" onAnswerReceived() running (hangupParty=\").concat(content.party_id, \")\"));\n      if (_this20.callHasEnded()) {\n        logger.debug(\"Call \".concat(_this20.callId, \" onAnswerReceived() ignoring answer because call has ended\"));\n        return;\n      }\n      if (_this20.opponentPartyId !== undefined) {\n        logger.info(\"Call \".concat(_this20.callId, \" onAnswerReceived() ignoring answer from party ID \").concat(content.party_id, \": we already have an answer/reject from \").concat(_this20.opponentPartyId));\n        return;\n      }\n      _this20.chooseOpponent(event);\n      yield _this20.addBufferedIceCandidates();\n      _this20.state = CallState.Connecting;\n      var sdpStreamMetadata = content[SDPStreamMetadataKey];\n      if (sdpStreamMetadata) {\n        _this20.updateRemoteSDPStreamMetadata(sdpStreamMetadata);\n      } else {\n        logger.warn(\"Call \".concat(_this20.callId, \" onAnswerReceived() did not get any SDPStreamMetadata! Can not send/receive multiple streams\"));\n      }\n      try {\n        _this20.isSettingRemoteAnswerPending = true;\n        yield _this20.peerConn.setRemoteDescription(content.answer);\n        _this20.isSettingRemoteAnswerPending = false;\n        logger.debug(\"Call \".concat(_this20.callId, \" onAnswerReceived() set remote description: \").concat(content.answer.type));\n      } catch (e) {\n        _this20.isSettingRemoteAnswerPending = false;\n        logger.debug(\"Call \".concat(_this20.callId, \" onAnswerReceived() failed to set remote description\"), e);\n        _this20.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);\n        return;\n      }\n\n      // If the answer we selected has a party_id, send a select_answer event\n      // We do this after setting the remote description since otherwise we'd block\n      // call setup on it\n      if (_this20.opponentPartyId !== null) {\n        try {\n          yield _this20.sendVoipEvent(EventType.CallSelectAnswer, {\n            selected_party_id: _this20.opponentPartyId\n          });\n        } catch (err) {\n          // This isn't fatal, and will just mean that if another party has raced to answer\n          // the call, they won't know they got rejected, so we carry on & don't retry.\n          logger.warn(\"Call \".concat(_this20.callId, \" onAnswerReceived() failed to send select_answer event\"), err);\n        }\n      }\n    })();\n  }\n  onSelectAnswerReceived(event) {\n    var _this21 = this;\n    return _asyncToGenerator(function* () {\n      if (_this21.direction !== CallDirection.Inbound) {\n        logger.warn(\"Call \".concat(_this21.callId, \" onSelectAnswerReceived() got select_answer for an outbound call: ignoring\"));\n        return;\n      }\n      var selectedPartyId = event.getContent().selected_party_id;\n      if (selectedPartyId === undefined || selectedPartyId === null) {\n        logger.warn(\"Call \".concat(_this21.callId, \" onSelectAnswerReceived() got nonsensical select_answer with null/undefined selected_party_id: ignoring\"));\n        return;\n      }\n      if (selectedPartyId !== _this21.ourPartyId) {\n        logger.info(\"Call \".concat(_this21.callId, \" onSelectAnswerReceived() got select_answer for party ID \").concat(selectedPartyId, \": we are party ID \").concat(_this21.ourPartyId, \".\"));\n        // The other party has picked somebody else's answer\n        yield _this21.terminate(CallParty.Remote, CallErrorCode.AnsweredElsewhere, true);\n      }\n    })();\n  }\n  onNegotiateReceived(event) {\n    var _this22 = this;\n    return _asyncToGenerator(function* () {\n      var content = event.getContent();\n      var description = content.description;\n      if (!description || !description.sdp || !description.type) {\n        logger.info(\"Call \".concat(_this22.callId, \" onNegotiateReceived() ignoring invalid m.call.negotiate event\"));\n        return;\n      }\n      // Politeness always follows the direction of the call: in a glare situation,\n      // we pick either the inbound or outbound call, so one side will always be\n      // inbound and one outbound\n      var polite = _this22.direction === CallDirection.Inbound;\n\n      // Here we follow the perfect negotiation logic from\n      // https://w3c.github.io/webrtc-pc/#perfect-negotiation-example\n      var readyForOffer = !_this22.makingOffer && (_this22.peerConn.signalingState === \"stable\" || _this22.isSettingRemoteAnswerPending);\n      var offerCollision = description.type === \"offer\" && !readyForOffer;\n      _this22.ignoreOffer = !polite && offerCollision;\n      if (_this22.ignoreOffer) {\n        logger.info(\"Call \".concat(_this22.callId, \" onNegotiateReceived() ignoring colliding negotiate event because we're impolite\"));\n        return;\n      }\n      var prevLocalOnHold = _this22.isLocalOnHold();\n      var sdpStreamMetadata = content[SDPStreamMetadataKey];\n      if (sdpStreamMetadata) {\n        _this22.updateRemoteSDPStreamMetadata(sdpStreamMetadata);\n      } else {\n        logger.warn(\"Call \".concat(_this22.callId, \" onNegotiateReceived() received negotiation event without SDPStreamMetadata!\"));\n      }\n      try {\n        _this22.isSettingRemoteAnswerPending = description.type == \"answer\";\n        yield _this22.peerConn.setRemoteDescription(description); // SRD rolls back as needed\n        _this22.isSettingRemoteAnswerPending = false;\n        logger.debug(\"Call \".concat(_this22.callId, \" onNegotiateReceived() set remote description: \").concat(description.type));\n        if (description.type === \"offer\") {\n          var _localDescription;\n          var answer;\n          try {\n            _this22.getRidOfRTXCodecs();\n            answer = yield _this22.createAnswer();\n          } catch (err) {\n            logger.debug(\"Call \".concat(_this22.callId, \" onNegotiateReceived() failed to create answer: \"), err);\n            _this22.terminate(CallParty.Local, CallErrorCode.CreateAnswer, true);\n            return;\n          }\n          yield _this22.peerConn.setLocalDescription(answer);\n          logger.debug(\"Call \".concat(_this22.callId, \" onNegotiateReceived() create an answer\"));\n          _this22.sendVoipEvent(EventType.CallNegotiate, {\n            lifetime: CALL_TIMEOUT_MS,\n            description: (_localDescription = _this22.peerConn.localDescription) === null || _localDescription === void 0 ? void 0 : _localDescription.toJSON(),\n            [SDPStreamMetadataKey]: _this22.getLocalSDPStreamMetadata(true)\n          });\n        }\n      } catch (err) {\n        _this22.isSettingRemoteAnswerPending = false;\n        logger.warn(\"Call \".concat(_this22.callId, \" onNegotiateReceived() failed to complete negotiation\"), err);\n      }\n      var newLocalOnHold = _this22.isLocalOnHold();\n      if (prevLocalOnHold !== newLocalOnHold) {\n        _this22.emit(CallEvent.LocalHoldUnhold, newLocalOnHold, _this22);\n        // also this one for backwards compat\n        _this22.emit(CallEvent.HoldUnhold, newLocalOnHold);\n      }\n    })();\n  }\n  updateRemoteSDPStreamMetadata(metadata) {\n    this.remoteSDPStreamMetadata = recursivelyAssign(this.remoteSDPStreamMetadata || {}, metadata, true);\n    for (var feed of this.getRemoteFeeds()) {\n      var _streamId;\n      var streamId = feed.stream.id;\n      var _metadata = this.remoteSDPStreamMetadata[streamId];\n      feed.setAudioVideoMuted(_metadata === null || _metadata === void 0 ? void 0 : _metadata.audio_muted, _metadata === null || _metadata === void 0 ? void 0 : _metadata.video_muted);\n      feed.purpose = (_streamId = this.remoteSDPStreamMetadata[streamId]) === null || _streamId === void 0 ? void 0 : _streamId.purpose;\n    }\n  }\n  onSDPStreamMetadataChangedReceived(event) {\n    var content = event.getContent();\n    var metadata = content[SDPStreamMetadataKey];\n    this.updateRemoteSDPStreamMetadata(metadata);\n  }\n  onAssertedIdentityReceived(event) {\n    var _this23 = this;\n    return _asyncToGenerator(function* () {\n      var content = event.getContent();\n      if (!content.asserted_identity) return;\n      _this23.remoteAssertedIdentity = {\n        id: content.asserted_identity.id,\n        displayName: content.asserted_identity.display_name\n      };\n      _this23.emit(CallEvent.AssertedIdentityChanged, _this23);\n    })();\n  }\n  callHasEnded() {\n    // This exists as workaround to typescript trying to be clever and erroring\n    // when putting if (this.state === CallState.Ended) return; twice in the same\n    // function, even though that function is async.\n    return this.state === CallState.Ended;\n  }\n  queueGotLocalOffer() {\n    // Ensure only one negotiate/answer event is being processed at a time.\n    if (this.responsePromiseChain) {\n      this.responsePromiseChain = this.responsePromiseChain.then(() => this.wrappedGotLocalOffer());\n    } else {\n      this.responsePromiseChain = this.wrappedGotLocalOffer();\n    }\n  }\n  wrappedGotLocalOffer() {\n    var _this24 = this;\n    return _asyncToGenerator(function* () {\n      _this24.makingOffer = true;\n      try {\n        // XXX: in what situations do we believe gotLocalOffer actually throws? It appears\n        // to handle most of its exceptions itself and terminate the call. I'm not entirely\n        // sure it would ever throw, so I can't add a test for these lines.\n        // Also the tense is different between \"gotLocalOffer\" and \"getLocalOfferFailed\" so\n        // it's not entirely clear whether getLocalOfferFailed is just misnamed or whether\n        // they've been cross-polinated somehow at some point.\n        yield _this24.gotLocalOffer();\n      } catch (e) {\n        _this24.getLocalOfferFailed(e);\n        return;\n      } finally {\n        _this24.makingOffer = false;\n      }\n    })();\n  }\n  gotLocalOffer() {\n    var _this25 = this;\n    return _asyncToGenerator(function* () {\n      logger.debug(\"Call \".concat(_this25.callId, \" gotLocalOffer() running\"));\n      if (_this25.callHasEnded()) {\n        logger.debug(\"Call \".concat(_this25.callId, \" gotLocalOffer() ignoring newly created offer because the call has ended\\\"\"));\n        return;\n      }\n      var offer;\n      try {\n        _this25.getRidOfRTXCodecs();\n        offer = yield _this25.createOffer();\n      } catch (err) {\n        logger.debug(\"Call \".concat(_this25.callId, \" gotLocalOffer() failed to create offer: \"), err);\n        _this25.terminate(CallParty.Local, CallErrorCode.CreateOffer, true);\n        return;\n      }\n      try {\n        yield _this25.peerConn.setLocalDescription(offer);\n      } catch (err) {\n        logger.debug(\"Call \".concat(_this25.callId, \" gotLocalOffer() error setting local description!\"), err);\n        _this25.terminate(CallParty.Local, CallErrorCode.SetLocalDescription, true);\n        return;\n      }\n      if (_this25.peerConn.iceGatheringState === \"gathering\") {\n        // Allow a short time for initial candidates to be gathered\n        yield new Promise(resolve => {\n          setTimeout(resolve, 200);\n        });\n      }\n      if (_this25.callHasEnded()) return;\n      var eventType = _this25.state === CallState.CreateOffer ? EventType.CallInvite : EventType.CallNegotiate;\n      var content = {\n        lifetime: CALL_TIMEOUT_MS\n      };\n      if (eventType === EventType.CallInvite && _this25.invitee) {\n        content.invitee = _this25.invitee;\n      }\n\n      // clunky because TypeScript can't follow the types through if we use an expression as the key\n      if (_this25.state === CallState.CreateOffer) {\n        var _localDescription2;\n        content.offer = (_localDescription2 = _this25.peerConn.localDescription) === null || _localDescription2 === void 0 ? void 0 : _localDescription2.toJSON();\n      } else {\n        var _localDescription3;\n        content.description = (_localDescription3 = _this25.peerConn.localDescription) === null || _localDescription3 === void 0 ? void 0 : _localDescription3.toJSON();\n      }\n      content.capabilities = {\n        \"m.call.transferee\": _this25.client.supportsCallTransfer,\n        \"m.call.dtmf\": false\n      };\n      content[SDPStreamMetadataKey] = _this25.getLocalSDPStreamMetadata(true);\n\n      // Get rid of any candidates waiting to be sent: they'll be included in the local\n      // description we just got and will send in the offer.\n      var discardCount = _this25.discardDuplicateCandidates();\n      logger.info(\"Call \".concat(_this25.callId, \" gotLocalOffer() discarding \").concat(discardCount, \" candidates that will be sent in offer\"));\n      try {\n        yield _this25.sendVoipEvent(eventType, content);\n      } catch (error) {\n        logger.error(\"Call \".concat(_this25.callId, \" gotLocalOffer() failed to send invite\"), error);\n        if (error instanceof MatrixError && error.event) _this25.client.cancelPendingEvent(error.event);\n        var code = CallErrorCode.SignallingFailed;\n        var message = \"Signalling failed\";\n        if (_this25.state === CallState.CreateOffer) {\n          code = CallErrorCode.SendInvite;\n          message = \"Failed to send invite\";\n        }\n        if (error.name == \"UnknownDeviceError\") {\n          code = CallErrorCode.UnknownDevices;\n          message = \"Unknown devices present in the room\";\n        }\n        _this25.emit(CallEvent.Error, new CallError(code, message, error), _this25);\n        _this25.terminate(CallParty.Local, code, false);\n\n        // no need to carry on & send the candidate queue, but we also\n        // don't want to rethrow the error\n        return;\n      }\n      _this25.sendCandidateQueue();\n      if (_this25.state === CallState.CreateOffer) {\n        _this25.inviteOrAnswerSent = true;\n        _this25.state = CallState.InviteSent;\n        _this25.inviteTimeout = setTimeout(() => {\n          _this25.inviteTimeout = undefined;\n          if (_this25.state === CallState.InviteSent) {\n            _this25.hangup(CallErrorCode.InviteTimeout, false);\n          }\n        }, CALL_TIMEOUT_MS);\n      }\n    })();\n  }\n  /**\n   * This method removes all video/rtx codecs from screensharing video\n   * transceivers. This is necessary since they can cause problems. Without\n   * this the following steps should produce an error:\n   *   Chromium calls Firefox\n   *   Firefox answers\n   *   Firefox starts screen-sharing\n   *   Chromium starts screen-sharing\n   *   Call crashes for Chromium with:\n   *       [96685:23:0518/162603.933321:ERROR:webrtc_video_engine.cc(3296)] RTX codec (PT=97) mapped to PT=96 which is not in the codec list.\n   *       [96685:23:0518/162603.933377:ERROR:webrtc_video_engine.cc(1171)] GetChangedRecvParameters called without any video codecs.\n   *       [96685:23:0518/162603.933430:ERROR:sdp_offer_answer.cc(4302)] Failed to set local video description recv parameters for m-section with mid='2'. (INVALID_PARAMETER)\n   */\n  getRidOfRTXCodecs() {\n    // RTCRtpReceiver.getCapabilities and RTCRtpSender.getCapabilities don't seem to be supported on FF before v113\n    if (!RTCRtpReceiver.getCapabilities || !RTCRtpSender.getCapabilities) return;\n    var screenshareVideoTransceiver = this.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Screenshare, \"video\"));\n\n    // setCodecPreferences isn't supported on FF (as of v113)\n    if (!screenshareVideoTransceiver || !screenshareVideoTransceiver.setCodecPreferences) return;\n    var recvCodecs = RTCRtpReceiver.getCapabilities(\"video\").codecs;\n    var sendCodecs = RTCRtpSender.getCapabilities(\"video\").codecs;\n    var codecs = [];\n    for (var codec of [...recvCodecs, ...sendCodecs]) {\n      if (codec.mimeType !== \"video/rtx\") {\n        codecs.push(codec);\n        try {\n          screenshareVideoTransceiver.setCodecPreferences(codecs);\n        } catch (e) {\n          // Specifically, Chrome around version 125 and Electron 30 (which is Chromium 124) return an H.264 codec in\n          // the sender's capabilities but throw when you try to set it. Hence... this mess.\n          // Specifically, that codec is:\n          // {\n          //   clockRate: 90000,\n          //   mimeType: \"video/H264\",\n          //   sdpFmtpLine: \"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=640034\",\n          // }\n          logger.info(\"Working around buggy WebRTC impl: claimed to support codec but threw when setting codec preferences\", codec, e);\n          codecs.pop();\n        }\n      }\n    }\n  }\n  /**\n   * @internal\n   */\n  sendVoipEvent(eventType, content) {\n    var _this26 = this;\n    return _asyncToGenerator(function* () {\n      var realContent = _objectSpread(_objectSpread({}, content), {}, {\n        version: VOIP_PROTO_VERSION,\n        call_id: _this26.callId,\n        party_id: _this26.ourPartyId,\n        conf_id: _this26.groupCallId\n      });\n      if (_this26.opponentDeviceId) {\n        var _this26$getOpponentMe;\n        var toDeviceSeq = _this26.toDeviceSeq++;\n        var _content = _objectSpread(_objectSpread({}, realContent), {}, {\n          device_id: _this26.client.deviceId,\n          sender_session_id: _this26.client.getSessionId(),\n          dest_session_id: _this26.opponentSessionId,\n          seq: toDeviceSeq,\n          [ToDeviceMessageId]: uuidv4()\n        });\n        _this26.emit(CallEvent.SendVoipEvent, {\n          type: \"toDevice\",\n          eventType,\n          userId: _this26.invitee || ((_this26$getOpponentMe = _this26.getOpponentMember()) === null || _this26$getOpponentMe === void 0 ? void 0 : _this26$getOpponentMe.userId),\n          opponentDeviceId: _this26.opponentDeviceId,\n          content: _content\n        }, _this26);\n        var userId = _this26.invitee || _this26.getOpponentMember().userId;\n        if (_this26.client.getUseE2eForGroupCall()) {\n          if (!_this26.hasOpponentDeviceInfo) {\n            logger.warn(\"Call \".concat(_this26.callId, \" sendVoipEvent() failed: we do not have opponentDeviceInfo\"));\n            return;\n          }\n\n          // TODO: Here we were sending the event to the opponent's device as a to-device message with MatrixClient.encryptAndSendToDevice.\n          // However due to the switch to Rust cryptography we need to migrate to the new encryptToDeviceMessages API.\n          throw new Error(\"Unimplemented\");\n        } else {\n          yield _this26.client.sendToDevice(eventType, new Map([[userId, new Map([[_this26.opponentDeviceId, _content]])]]));\n        }\n      } else {\n        var _this26$getOpponentMe2;\n        _this26.emit(CallEvent.SendVoipEvent, {\n          type: \"sendEvent\",\n          eventType,\n          roomId: _this26.roomId,\n          content: realContent,\n          userId: _this26.invitee || ((_this26$getOpponentMe2 = _this26.getOpponentMember()) === null || _this26$getOpponentMe2 === void 0 ? void 0 : _this26$getOpponentMe2.userId)\n        }, _this26);\n        yield _this26.client.sendEvent(_this26.roomId, eventType, realContent);\n      }\n    })();\n  }\n\n  /**\n   * Queue a candidate to be sent\n   * @param content - The candidate to queue up, or null if candidates have finished being generated\n   *                and end-of-candidates should be signalled\n   */\n  queueCandidate(content) {\n    // We partially de-trickle candidates by waiting for `delay` before sending them\n    // amalgamated, in order to avoid sending too many m.call.candidates events and hitting\n    // rate limits in Matrix.\n    // In practice, it'd be better to remove rate limits for m.call.*\n\n    // N.B. this deliberately lets you queue and send blank candidates, which MSC2746\n    // currently proposes as the way to indicate that candidate gathering is complete.\n    // This will hopefully be changed to an explicit rather than implicit notification\n    // shortly.\n    if (content) {\n      this.candidateSendQueue.push(content);\n    } else {\n      this.candidatesEnded = true;\n    }\n\n    // Don't send the ICE candidates yet if the call is in the ringing state: this\n    // means we tried to pick (ie. started generating candidates) and then failed to\n    // send the answer and went back to the ringing state. Queue up the candidates\n    // to send if we successfully send the answer.\n    // Equally don't send if we haven't yet sent the answer because we can send the\n    // first batch of candidates along with the answer\n    if (this.state === CallState.Ringing || !this.inviteOrAnswerSent) return;\n\n    // MSC2746 recommends these values (can be quite long when calling because the\n    // callee will need a while to answer the call)\n    var delay = this.direction === CallDirection.Inbound ? 500 : 2000;\n    if (this.candidateSendTries === 0) {\n      setTimeout(() => {\n        this.sendCandidateQueue();\n      }, delay);\n    }\n  }\n\n  // Discard all non-end-of-candidates messages\n  // Return the number of candidate messages that were discarded.\n  // Call this method before sending an invite or answer message\n  discardDuplicateCandidates() {\n    var discardCount = 0;\n    var newQueue = [];\n    for (var i = 0; i < this.candidateSendQueue.length; i++) {\n      var candidate = this.candidateSendQueue[i];\n      if (candidate.candidate === \"\") {\n        newQueue.push(candidate);\n      } else {\n        discardCount++;\n      }\n    }\n    this.candidateSendQueue = newQueue;\n    return discardCount;\n  }\n\n  /*\n   * Transfers this call to another user\n   */\n  transfer(targetUserId) {\n    var _this27 = this;\n    return _asyncToGenerator(function* () {\n      // Fetch the target user's global profile info: their room avatar / displayname\n      // could be different in whatever room we share with them.\n      var profileInfo = yield _this27.client.getProfileInfo(targetUserId);\n      var replacementId = genCallID();\n      var body = {\n        replacement_id: genCallID(),\n        target_user: {\n          id: targetUserId,\n          display_name: profileInfo.displayname,\n          avatar_url: profileInfo.avatar_url\n        },\n        create_call: replacementId\n      };\n      yield _this27.sendVoipEvent(EventType.CallReplaces, body);\n      yield _this27.terminate(CallParty.Local, CallErrorCode.Transferred, true);\n    })();\n  }\n\n  /*\n   * Transfers this call to the target call, effectively 'joining' the\n   * two calls (so the remote parties on each call are connected together).\n   */\n  transferToCall(transferTargetCall) {\n    var _this28 = this;\n    return _asyncToGenerator(function* () {\n      var _transferTargetCall$g, _this28$getOpponentMe;\n      var targetUserId = (_transferTargetCall$g = transferTargetCall.getOpponentMember()) === null || _transferTargetCall$g === void 0 ? void 0 : _transferTargetCall$g.userId;\n      var targetProfileInfo = targetUserId ? yield _this28.client.getProfileInfo(targetUserId) : undefined;\n      var opponentUserId = (_this28$getOpponentMe = _this28.getOpponentMember()) === null || _this28$getOpponentMe === void 0 ? void 0 : _this28$getOpponentMe.userId;\n      var transfereeProfileInfo = opponentUserId ? yield _this28.client.getProfileInfo(opponentUserId) : undefined;\n      var newCallId = genCallID();\n      var bodyToTransferTarget = {\n        // the replacements on each side have their own ID, and it's distinct from the\n        // ID of the new call (but we can use the same function to generate it)\n        replacement_id: genCallID(),\n        target_user: {\n          id: opponentUserId,\n          display_name: transfereeProfileInfo === null || transfereeProfileInfo === void 0 ? void 0 : transfereeProfileInfo.displayname,\n          avatar_url: transfereeProfileInfo === null || transfereeProfileInfo === void 0 ? void 0 : transfereeProfileInfo.avatar_url\n        },\n        await_call: newCallId\n      };\n      yield transferTargetCall.sendVoipEvent(EventType.CallReplaces, bodyToTransferTarget);\n      var bodyToTransferee = {\n        replacement_id: genCallID(),\n        target_user: {\n          id: targetUserId,\n          display_name: targetProfileInfo === null || targetProfileInfo === void 0 ? void 0 : targetProfileInfo.displayname,\n          avatar_url: targetProfileInfo === null || targetProfileInfo === void 0 ? void 0 : targetProfileInfo.avatar_url\n        },\n        create_call: newCallId\n      };\n      yield _this28.sendVoipEvent(EventType.CallReplaces, bodyToTransferee);\n      yield _this28.terminate(CallParty.Local, CallErrorCode.Transferred, true);\n      yield transferTargetCall.terminate(CallParty.Local, CallErrorCode.Transferred, true);\n    })();\n  }\n  terminate(hangupParty, hangupReason, shouldEmit) {\n    var _this29 = this;\n    return _asyncToGenerator(function* () {\n      var _this29$stats;\n      if (_this29.callHasEnded()) return;\n      _this29.hangupParty = hangupParty;\n      _this29.hangupReason = hangupReason;\n      _this29.state = CallState.Ended;\n      if (_this29.inviteTimeout) {\n        clearTimeout(_this29.inviteTimeout);\n        _this29.inviteTimeout = undefined;\n      }\n      if (_this29.iceDisconnectedTimeout !== undefined) {\n        clearTimeout(_this29.iceDisconnectedTimeout);\n        _this29.iceDisconnectedTimeout = undefined;\n      }\n      if (_this29.callLengthInterval) {\n        clearInterval(_this29.callLengthInterval);\n        _this29.callLengthInterval = undefined;\n      }\n      if (_this29.stopVideoTrackTimer !== undefined) {\n        clearTimeout(_this29.stopVideoTrackTimer);\n        _this29.stopVideoTrackTimer = undefined;\n      }\n      for (var [stream, listener] of _this29.removeTrackListeners) {\n        stream.removeEventListener(\"removetrack\", listener);\n      }\n      _this29.removeTrackListeners.clear();\n      _this29.callStatsAtEnd = yield _this29.collectCallStats();\n\n      // Order is important here: first we stopAllMedia() and only then we can deleteAllFeeds()\n      _this29.stopAllMedia();\n      _this29.deleteAllFeeds();\n      if (_this29.peerConn && _this29.peerConn.signalingState !== \"closed\") {\n        _this29.peerConn.close();\n      }\n      (_this29$stats = _this29.stats) === null || _this29$stats === void 0 || _this29$stats.removeStatsReportGatherer(_this29.callId);\n      if (shouldEmit) {\n        _this29.emit(CallEvent.Hangup, _this29);\n      }\n      _this29.client.callEventHandler.calls.delete(_this29.callId);\n    })();\n  }\n  stopAllMedia() {\n    logger.debug(\"Call \".concat(this.callId, \" stopAllMedia() running\"));\n    for (var feed of this.feeds) {\n      // Slightly awkward as local feed need to go via the correct method on\n      // the MediaHandler so they get removed from MediaHandler (remote tracks\n      // don't)\n      // NB. We clone local streams when passing them to individual calls in a group\n      // call, so we can (and should) stop the clones once we no longer need them:\n      // the other clones will continue fine.\n      if (feed.isLocal() && feed.purpose === SDPStreamMetadataPurpose.Usermedia) {\n        this.client.getMediaHandler().stopUserMediaStream(feed.stream);\n      } else if (feed.isLocal() && feed.purpose === SDPStreamMetadataPurpose.Screenshare) {\n        this.client.getMediaHandler().stopScreensharingStream(feed.stream);\n      } else if (!feed.isLocal()) {\n        logger.debug(\"Call \".concat(this.callId, \" stopAllMedia() stopping stream (streamId=\").concat(feed.stream.id, \")\"));\n        for (var track of feed.stream.getTracks()) {\n          track.stop();\n        }\n      }\n    }\n  }\n  checkForErrorListener() {\n    if (this.listeners(EventEmitterEvents.Error).length === 0) {\n      throw new Error(\"You MUST attach an error listener using call.on('error', function() {})\");\n    }\n  }\n  sendCandidateQueue() {\n    var _this30 = this;\n    return _asyncToGenerator(function* () {\n      if (_this30.candidateSendQueue.length === 0 || _this30.callHasEnded()) {\n        return;\n      }\n      var candidates = _this30.candidateSendQueue;\n      _this30.candidateSendQueue = [];\n      ++_this30.candidateSendTries;\n      var content = {\n        candidates: candidates.map(candidate => candidate.toJSON())\n      };\n      if (_this30.candidatesEnded) {\n        // If there are no more candidates, signal this by adding an empty string candidate\n        content.candidates.push({\n          candidate: \"\"\n        });\n      }\n      logger.debug(\"Call \".concat(_this30.callId, \" sendCandidateQueue() attempting to send \").concat(candidates.length, \" candidates\"));\n      try {\n        yield _this30.sendVoipEvent(EventType.CallCandidates, content);\n        // reset our retry count if we have successfully sent our candidates\n        // otherwise queueCandidate() will refuse to try to flush the queue\n        _this30.candidateSendTries = 0;\n\n        // Try to send candidates again just in case we received more candidates while sending.\n        _this30.sendCandidateQueue();\n      } catch (error) {\n        // don't retry this event: we'll send another one later as we might\n        // have more candidates by then.\n        if (error instanceof MatrixError && error.event) _this30.client.cancelPendingEvent(error.event);\n\n        // put all the candidates we failed to send back in the queue\n        _this30.candidateSendQueue.push(...candidates);\n        if (_this30.candidateSendTries > 5) {\n          logger.debug(\"Call \".concat(_this30.callId, \" sendCandidateQueue() failed to send candidates on attempt \").concat(_this30.candidateSendTries, \". Giving up on this call.\"), error);\n          var code = CallErrorCode.SignallingFailed;\n          var message = \"Signalling failed\";\n          _this30.emit(CallEvent.Error, new CallError(code, message, error), _this30);\n          _this30.hangup(code, false);\n          return;\n        }\n        var delayMs = 500 * Math.pow(2, _this30.candidateSendTries);\n        ++_this30.candidateSendTries;\n        logger.debug(\"Call \".concat(_this30.callId, \" sendCandidateQueue() failed to send candidates. Retrying in \").concat(delayMs, \"ms\"), error);\n        setTimeout(() => {\n          _this30.sendCandidateQueue();\n        }, delayMs);\n      }\n    })();\n  }\n\n  /**\n   * Place a call to this room.\n   * @throws if you have not specified a listener for 'error' events.\n   * @throws if have passed audio=false.\n   */\n  placeCall(audio, video) {\n    var _this31 = this;\n    return _asyncToGenerator(function* () {\n      if (!audio) {\n        throw new Error(\"You CANNOT start a call without audio\");\n      }\n      _this31.state = CallState.WaitLocalMedia;\n      var callFeed;\n      try {\n        var _this31$client$getDev;\n        var stream = yield _this31.client.getMediaHandler().getUserMediaStream(audio, video);\n\n        // make sure all the tracks are enabled (same as pushNewLocalFeed -\n        // we probably ought to just have one code path for adding streams)\n        setTracksEnabled(stream.getAudioTracks(), true);\n        setTracksEnabled(stream.getVideoTracks(), true);\n        callFeed = new CallFeed({\n          client: _this31.client,\n          roomId: _this31.roomId,\n          userId: _this31.client.getUserId(),\n          deviceId: (_this31$client$getDev = _this31.client.getDeviceId()) !== null && _this31$client$getDev !== void 0 ? _this31$client$getDev : undefined,\n          stream,\n          purpose: SDPStreamMetadataPurpose.Usermedia,\n          audioMuted: false,\n          videoMuted: false\n        });\n      } catch (e) {\n        _this31.getUserMediaFailed(e);\n        return;\n      }\n      try {\n        yield _this31.placeCallWithCallFeeds([callFeed]);\n      } catch (e) {\n        _this31.placeCallFailed(e);\n        return;\n      }\n    })();\n  }\n\n  /**\n   * Place a call to this room with call feed.\n   * @param callFeeds - to use\n   * @throws if you have not specified a listener for 'error' events.\n   * @throws if have passed audio=false.\n   */\n  placeCallWithCallFeeds(callFeeds) {\n    var _arguments2 = arguments,\n      _this32 = this;\n    return _asyncToGenerator(function* () {\n      var requestScreenshareFeed = _arguments2.length > 1 && _arguments2[1] !== undefined ? _arguments2[1] : false;\n      _this32.checkForErrorListener();\n      _this32.direction = CallDirection.Outbound;\n      yield _this32.initOpponentCrypto();\n\n      // XXX Find a better way to do this\n      _this32.client.callEventHandler.calls.set(_this32.callId, _this32);\n\n      // make sure we have valid turn creds. Unless something's gone wrong, it should\n      // poll and keep the credentials valid so this should be instant.\n      var haveTurnCreds = yield _this32.client.checkTurnServers();\n      if (!haveTurnCreds) {\n        logger.warn(\"Call \".concat(_this32.callId, \" placeCallWithCallFeeds() failed to get TURN credentials! Proceeding with call anyway...\"));\n      }\n\n      // create the peer connection now so it can be gathering candidates while we get user\n      // media (assuming a candidate pool size is configured)\n      _this32.peerConn = _this32.createPeerConnection();\n      _this32.emit(CallEvent.PeerConnectionCreated, _this32.peerConn, _this32);\n      _this32.gotCallFeedsForInvite(callFeeds, requestScreenshareFeed);\n    })();\n  }\n  createPeerConnection() {\n    var _this$stats;\n    var pc = new window.RTCPeerConnection({\n      iceTransportPolicy: this.forceTURN ? \"relay\" : undefined,\n      iceServers: this.turnServers.length ? this.turnServers : undefined,\n      iceCandidatePoolSize: this.client.iceCandidatePoolSize,\n      bundlePolicy: \"max-bundle\"\n    });\n\n    // 'connectionstatechange' would be better, but firefox doesn't implement that.\n    pc.addEventListener(\"iceconnectionstatechange\", this.onIceConnectionStateChanged);\n    pc.addEventListener(\"signalingstatechange\", this.onSignallingStateChanged);\n    pc.addEventListener(\"icecandidate\", this.gotLocalIceCandidate);\n    pc.addEventListener(\"icegatheringstatechange\", this.onIceGatheringStateChange);\n    pc.addEventListener(\"track\", this.onTrack);\n    pc.addEventListener(\"negotiationneeded\", this.onNegotiationNeeded);\n    pc.addEventListener(\"datachannel\", this.onDataChannel);\n    var opponentMember = this.getOpponentMember();\n    var opponentMemberId = opponentMember ? opponentMember.userId : \"unknown\";\n    (_this$stats = this.stats) === null || _this$stats === void 0 || _this$stats.addStatsReportGatherer(this.callId, opponentMemberId, pc);\n    return pc;\n  }\n  partyIdMatches(msg) {\n    // They must either match or both be absent (in which case opponentPartyId will be null)\n    // Also we ignore party IDs on the invite/offer if the version is 0, so we must do the same\n    // here and use null if the version is 0 (woe betide any opponent sending messages in the\n    // same call with different versions)\n    var msgPartyId = msg.version === 0 ? null : msg.party_id || null;\n    return msgPartyId === this.opponentPartyId;\n  }\n\n  // Commits to an opponent for the call\n  // ev: An invite or answer event\n  chooseOpponent(ev) {\n    var _getMember;\n    // I choo-choo-choose you\n    var msg = ev.getContent();\n    logger.debug(\"Call \".concat(this.callId, \" chooseOpponent() running (partyId=\").concat(msg.party_id, \")\"));\n    this.opponentVersion = msg.version;\n    if (this.opponentVersion === 0) {\n      // set to null to indicate that we've chosen an opponent, but because\n      // they're v0 they have no party ID (even if they sent one, we're ignoring it)\n      this.opponentPartyId = null;\n    } else {\n      // set to their party ID, or if they're naughty and didn't send one despite\n      // not being v0, set it to null to indicate we picked an opponent with no\n      // party ID\n      this.opponentPartyId = msg.party_id || null;\n    }\n    this.opponentCaps = msg.capabilities || {};\n    this.opponentMember = (_getMember = this.client.getRoom(this.roomId).getMember(ev.getSender())) !== null && _getMember !== void 0 ? _getMember : undefined;\n    if (this.opponentMember) {\n      var _this$stats2;\n      (_this$stats2 = this.stats) === null || _this$stats2 === void 0 || _this$stats2.updateOpponentMember(this.callId, this.opponentMember.userId);\n    }\n  }\n  addBufferedIceCandidates() {\n    var _this33 = this;\n    return _asyncToGenerator(function* () {\n      var bufferedCandidates = _this33.remoteCandidateBuffer.get(_this33.opponentPartyId);\n      if (bufferedCandidates) {\n        logger.info(\"Call \".concat(_this33.callId, \" addBufferedIceCandidates() adding \").concat(bufferedCandidates.length, \" buffered candidates for opponent \").concat(_this33.opponentPartyId));\n        yield _this33.addIceCandidates(bufferedCandidates);\n      }\n      _this33.remoteCandidateBuffer.clear();\n    })();\n  }\n  addIceCandidates(candidates) {\n    var _this34 = this;\n    return _asyncToGenerator(function* () {\n      for (var candidate of candidates) {\n        if ((candidate.sdpMid === null || candidate.sdpMid === undefined) && (candidate.sdpMLineIndex === null || candidate.sdpMLineIndex === undefined)) {\n          logger.debug(\"Call \".concat(_this34.callId, \" addIceCandidates() got remote ICE end-of-candidates\"));\n        } else {\n          logger.debug(\"Call \".concat(_this34.callId, \" addIceCandidates() got remote ICE candidate (sdpMid=\").concat(candidate.sdpMid, \", candidate=\").concat(candidate.candidate, \")\"));\n        }\n        try {\n          yield _this34.peerConn.addIceCandidate(candidate);\n        } catch (err) {\n          if (!_this34.ignoreOffer) {\n            logger.info(\"Call \".concat(_this34.callId, \" addIceCandidates() failed to add remote ICE candidate\"), err);\n          } else {\n            logger.debug(\"Call \".concat(_this34.callId, \" addIceCandidates() failed to add remote ICE candidate because ignoring offer\"), err);\n          }\n        }\n      }\n    })();\n  }\n  get hasPeerConnection() {\n    return Boolean(this.peerConn);\n  }\n  initStats(stats) {\n    var peerId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : \"unknown\";\n    this.stats = stats;\n    this.stats.start();\n  }\n}\nexport function setTracksEnabled(tracks, enabled) {\n  for (var track of tracks) {\n    track.enabled = enabled;\n  }\n}\nexport function supportsMatrixCall() {\n  // typeof prevents Node from erroring on an undefined reference\n  if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n    // NB. We don't log here as apps try to create a call object as a test for\n    // whether calls are supported, so we shouldn't fill the logs up.\n    return false;\n  }\n\n  // Firefox throws on so little as accessing the RTCPeerConnection when operating in a secure mode.\n  // There's some information at https://bugzilla.mozilla.org/show_bug.cgi?id=1542616 though the concern\n  // is that the browser throwing a SecurityError will brick the client creation process.\n  try {\n    var _ref2, _ref3, _window$RTCPeerConnec;\n    var supported = Boolean((_ref2 = (_ref3 = (_window$RTCPeerConnec = window.RTCPeerConnection) !== null && _window$RTCPeerConnec !== void 0 ? _window$RTCPeerConnec : window.RTCSessionDescription) !== null && _ref3 !== void 0 ? _ref3 : window.RTCIceCandidate) !== null && _ref2 !== void 0 ? _ref2 : navigator.mediaDevices);\n    if (!supported) {\n      /* istanbul ignore if */ // Adds a lot of noise to test runs, so disable logging there.\n      if (process.env.NODE_ENV !== \"test\") {\n        logger.error(\"WebRTC is not supported in this browser / environment\");\n      }\n      return false;\n    }\n  } catch (e) {\n    logger.error(\"Exception thrown when trying to access WebRTC\", e);\n    return false;\n  }\n  return true;\n}\n\n/**\n * DEPRECATED\n * Use client.createCall()\n *\n * Create a new Matrix call for the browser.\n * @param client - The client instance to use.\n * @param roomId - The room the call is in.\n * @param options - DEPRECATED optional options map.\n * @returns the call or null if the browser doesn't support calling.\n */\nexport function createNewMatrixCall(client, roomId, options) {\n  if (!supportsMatrixCall()) return null;\n  var optionsForceTURN = options ? options.forceTURN : false;\n  var opts = {\n    client: client,\n    roomId: roomId,\n    invitee: options === null || options === void 0 ? void 0 : options.invitee,\n    turnServers: client.getTurnServers(),\n    // call level options\n    forceTURN: client.forceTURN || optionsForceTURN,\n    opponentDeviceId: options === null || options === void 0 ? void 0 : options.opponentDeviceId,\n    opponentSessionId: options === null || options === void 0 ? void 0 : options.opponentSessionId,\n    groupCallId: options === null || options === void 0 ? void 0 : options.groupCallId\n  };\n  var call = new MatrixCall(opts);\n  client.reEmitter.reEmit(call, Object.values(CallEvent));\n  return call;\n}\n//# sourceMappingURL=call.js.map","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// allow camelcase as these are things that go onto the wire\n/* eslint-disable camelcase */\n\nexport var PushRuleActionName = /*#__PURE__*/function (PushRuleActionName) {\n  PushRuleActionName[\"DontNotify\"] = \"dont_notify\";\n  PushRuleActionName[\"Notify\"] = \"notify\";\n  PushRuleActionName[\"Coalesce\"] = \"coalesce\";\n  return PushRuleActionName;\n}({});\nexport var TweakName = /*#__PURE__*/function (TweakName) {\n  TweakName[\"Highlight\"] = \"highlight\";\n  TweakName[\"Sound\"] = \"sound\";\n  return TweakName;\n}({});\nexport var ConditionOperator = /*#__PURE__*/function (ConditionOperator) {\n  ConditionOperator[\"ExactEquals\"] = \"==\";\n  ConditionOperator[\"LessThan\"] = \"<\";\n  ConditionOperator[\"GreaterThan\"] = \">\";\n  ConditionOperator[\"GreaterThanOrEqual\"] = \">=\";\n  ConditionOperator[\"LessThanOrEqual\"] = \"<=\";\n  return ConditionOperator;\n}({});\nexport var DMMemberCountCondition = \"2\";\nexport function isDmMemberCountCondition(condition) {\n  return condition === \"==2\" || condition === \"2\";\n}\nexport var ConditionKind = /*#__PURE__*/function (ConditionKind) {\n  ConditionKind[\"EventMatch\"] = \"event_match\";\n  ConditionKind[\"EventPropertyIs\"] = \"event_property_is\";\n  ConditionKind[\"EventPropertyContains\"] = \"event_property_contains\";\n  ConditionKind[\"ContainsDisplayName\"] = \"contains_display_name\";\n  ConditionKind[\"RoomMemberCount\"] = \"room_member_count\";\n  ConditionKind[\"SenderNotificationPermission\"] = \"sender_notification_permission\";\n  ConditionKind[\"CallStarted\"] = \"call_started\";\n  ConditionKind[\"CallStartedPrefix\"] = \"org.matrix.msc3914.call_started\";\n  return ConditionKind;\n}({});\n\n// XXX: custom conditions are possible but always fail, and break the typescript discriminated union so ignore them here\n// IPushRuleCondition<Exclude<string, ConditionKind>> unfortunately does not resolve this at the time of writing.\n\nexport var PushRuleKind = /*#__PURE__*/function (PushRuleKind) {\n  PushRuleKind[\"Override\"] = \"override\";\n  PushRuleKind[\"ContentSpecific\"] = \"content\";\n  PushRuleKind[\"RoomSpecific\"] = \"room\";\n  PushRuleKind[\"SenderSpecific\"] = \"sender\";\n  PushRuleKind[\"Underride\"] = \"underride\";\n  return PushRuleKind;\n}({});\nexport var RuleId = /*#__PURE__*/function (RuleId) {\n  RuleId[\"Master\"] = \".m.rule.master\";\n  RuleId[\"IsUserMention\"] = \".m.rule.is_user_mention\";\n  RuleId[\"IsRoomMention\"] = \".m.rule.is_room_mention\";\n  RuleId[\"ContainsDisplayName\"] = \".m.rule.contains_display_name\";\n  RuleId[\"ContainsUserName\"] = \".m.rule.contains_user_name\";\n  RuleId[\"AtRoomNotification\"] = \".m.rule.roomnotif\";\n  RuleId[\"DM\"] = \".m.rule.room_one_to_one\";\n  RuleId[\"EncryptedDM\"] = \".m.rule.encrypted_room_one_to_one\";\n  RuleId[\"Message\"] = \".m.rule.message\";\n  RuleId[\"EncryptedMessage\"] = \".m.rule.encrypted\";\n  RuleId[\"InviteToSelf\"] = \".m.rule.invite_for_me\";\n  RuleId[\"MemberEvent\"] = \".m.rule.member_event\";\n  RuleId[\"IncomingCall\"] = \".m.rule.call\";\n  RuleId[\"SuppressNotices\"] = \".m.rule.suppress_notices\";\n  RuleId[\"Tombstone\"] = \".m.rule.tombstone\";\n  RuleId[\"PollStart\"] = \".m.rule.poll_start\";\n  RuleId[\"PollStartUnstable\"] = \".org.matrix.msc3930.rule.poll_start\";\n  RuleId[\"PollEnd\"] = \".m.rule.poll_end\";\n  RuleId[\"PollEndUnstable\"] = \".org.matrix.msc3930.rule.poll_end\";\n  RuleId[\"PollStartOneToOne\"] = \".m.rule.poll_start_one_to_one\";\n  RuleId[\"PollStartOneToOneUnstable\"] = \".org.matrix.msc3930.rule.poll_start_one_to_one\";\n  RuleId[\"PollEndOneToOne\"] = \".m.rule.poll_end_one_to_one\";\n  RuleId[\"PollEndOneToOneUnstable\"] = \".org.matrix.msc3930.rule.poll_end_one_to_one\";\n  return RuleId;\n}({});\n\n/* eslint-enable camelcase */\n//# sourceMappingURL=PushRules.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { deepCompare, escapeRegExp, globToRegexp, isNullOrUndefined } from \"./utils.js\";\nimport { ConditionKind, PushRuleActionName, PushRuleKind, RuleId, TweakName } from \"./@types/PushRules.js\";\nimport { EventType } from \"./@types/event.js\";\nvar RULEKINDS_IN_ORDER = [PushRuleKind.Override, PushRuleKind.ContentSpecific, PushRuleKind.RoomSpecific, PushRuleKind.SenderSpecific, PushRuleKind.Underride];\n\n// The default override rules to apply to the push rules that arrive from the server.\n// We do this for two reasons:\n//   1. Synapse is unlikely to send us the push rule in an incremental sync - see\n//      https://github.com/matrix-org/synapse/pull/4867#issuecomment-481446072 for\n//      more details.\n//   2. We often want to start using push rules ahead of the server supporting them,\n//      and so we can put them here.\nvar DEFAULT_OVERRIDE_RULES = {\n  \".m.rule.is_room_mention\": {\n    // Matrix v1.7\n    rule_id: \".m.rule.is_room_mention\",\n    default: true,\n    enabled: true,\n    conditions: [{\n      kind: ConditionKind.EventPropertyIs,\n      key: \"content.m\\\\.mentions.room\",\n      value: true\n    }, {\n      kind: ConditionKind.SenderNotificationPermission,\n      key: \"room\"\n    }],\n    actions: [PushRuleActionName.Notify, {\n      set_tweak: TweakName.Highlight\n    }]\n  },\n  \".m.rule.reaction\": {\n    // For homeservers which don't support MSC2153 yet\n    rule_id: \".m.rule.reaction\",\n    default: true,\n    enabled: true,\n    conditions: [{\n      kind: ConditionKind.EventMatch,\n      key: \"type\",\n      pattern: \"m.reaction\"\n    }],\n    actions: [PushRuleActionName.DontNotify]\n  },\n  \".org.matrix.msc3786.rule.room.server_acl\": {\n    // For homeservers which don't support MSC3786 yet\n    rule_id: \".org.matrix.msc3786.rule.room.server_acl\",\n    default: true,\n    enabled: true,\n    conditions: [{\n      kind: ConditionKind.EventMatch,\n      key: \"type\",\n      pattern: EventType.RoomServerAcl\n    }, {\n      kind: ConditionKind.EventMatch,\n      key: \"state_key\",\n      pattern: \"\"\n    }],\n    actions: []\n  }\n};\n\n// A special rule id for `EXPECTED_DEFAULT_OVERRIDE_RULE_IDS` and friends which denotes where user-defined rules live in the order.\nvar UserDefinedRules = Symbol(\"UserDefinedRules\");\nvar EXPECTED_DEFAULT_OVERRIDE_RULE_IDS = [RuleId.Master, UserDefinedRules, RuleId.SuppressNotices, RuleId.InviteToSelf, RuleId.MemberEvent, RuleId.IsUserMention, RuleId.ContainsDisplayName, RuleId.IsRoomMention, RuleId.AtRoomNotification, RuleId.Tombstone, \".m.rule.reaction\", \".m.rule.room.server_acl\", \".org.matrix.msc3786.rule.room.server_acl\", \".m.rule.suppress_edits\"];\nvar DEFAULT_UNDERRIDE_RULES = {\n  \".org.matrix.msc3914.rule.room.call\": {\n    // For homeservers which don't support MSC3914 yet\n    rule_id: \".org.matrix.msc3914.rule.room.call\",\n    default: true,\n    enabled: true,\n    conditions: [{\n      kind: ConditionKind.EventMatch,\n      key: \"type\",\n      pattern: \"org.matrix.msc3401.call\"\n    }, {\n      kind: ConditionKind.CallStarted\n    }],\n    actions: [PushRuleActionName.Notify, {\n      set_tweak: TweakName.Sound,\n      value: \"default\"\n    }]\n  }\n};\nvar EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS = [UserDefinedRules, RuleId.IncomingCall, \".org.matrix.msc3914.rule.room.call\", RuleId.EncryptedDM, RuleId.DM, RuleId.Message, RuleId.EncryptedMessage];\n\n/**\n * Make sure that each of the rules listed in `defaultRuleIds` is listed in the given set of push rules.\n *\n * @param logger - A `Logger` to write log messages to.\n * @param kind - the kind of push rule set being merged.\n * @param incomingRules - the existing set of known push rules for the user.\n * @param defaultRules - a lookup table for the default definitions of push rules.\n * @param orderedRuleIds - the IDs of the expected push rules, in order.\n *\n * @returns A copy of `incomingRules`, with any missing default rules inserted in the right place.\n */\nfunction mergeRulesWithDefaults(logger, kind, incomingRules, defaultRules, orderedRuleIds) {\n  // Split the incomingRules into defaults and custom\n  var incomingDefaultRules = incomingRules.filter(rule => rule.default);\n  var incomingCustomRules = incomingRules.filter(rule => !rule.default);\n  function insertDefaultPushRule(ruleId) {\n    if (ruleId === UserDefinedRules) {\n      // Re-insert any user-defined rules that were in `incomingRules`\n      newRules.push(...incomingCustomRules);\n    } else if (ruleId in defaultRules) {\n      logger.warn(\"Adding default global \".concat(kind, \" push rule \").concat(ruleId));\n      newRules.push(defaultRules[ruleId]);\n    } else {\n      logger.warn(\"Missing default global \".concat(kind, \" push rule \").concat(ruleId));\n    }\n  }\n  var nextExpectedRuleIdIndex = 0;\n  var newRules = [];\n  // Merge our expected rules (including the incoming custom rules) into the incoming default rules.\n  for (var rule of incomingDefaultRules) {\n    var ruleIndex = orderedRuleIds.indexOf(rule.rule_id);\n    if (ruleIndex === -1) {\n      // an unrecognised rule; copy it over\n      newRules.push(rule);\n      continue;\n    }\n    while (ruleIndex > nextExpectedRuleIdIndex) {\n      // insert new rules\n      var defaultRuleId = orderedRuleIds[nextExpectedRuleIdIndex];\n      insertDefaultPushRule(defaultRuleId);\n      nextExpectedRuleIdIndex += 1;\n    }\n    // copy over the existing rule\n    newRules.push(rule);\n    nextExpectedRuleIdIndex += 1;\n  }\n\n  // Now copy over any remaining default rules\n  for (var ruleId of orderedRuleIds.slice(nextExpectedRuleIdIndex)) {\n    insertDefaultPushRule(ruleId);\n  }\n  return newRules;\n}\nexport class PushProcessor {\n  /**\n   * Construct a Push Processor.\n   * @param client - The Matrix client object to use\n   */\n  constructor(client) {\n    this.client = client;\n    /**\n     * Maps the original key from the push rules to a list of property names\n     * after unescaping.\n     */\n    _defineProperty(this, \"parsedKeys\", new Map());\n  }\n  /**\n   * Convert a list of actions into a object with the actions as keys and their values\n   * @example\n   * eg. `[ 'notify', { set_tweak: 'sound', value: 'default' } ]`\n   *     becomes `{ notify: true, tweaks: { sound: 'default' } }`\n   * @param actionList - The actions list\n   *\n   * @returns A object with key 'notify' (true or false) and an object of actions\n   */\n  static actionListToActionsObject(actionList) {\n    var actionObj = {\n      notify: false,\n      tweaks: {}\n    };\n    for (var action of actionList) {\n      if (action === PushRuleActionName.Notify) {\n        actionObj.notify = true;\n      } else if (typeof action === \"object\") {\n        if (action.value === undefined) {\n          action.value = true;\n        }\n        actionObj.tweaks[action.set_tweak] = action.value;\n      }\n    }\n    return actionObj;\n  }\n\n  /**\n   * Rewrites conditions on a client's push rules to match the defaults\n   * where applicable. Useful for upgrading push rules to more strict\n   * conditions when the server is falling behind on defaults.\n   *\n   * @param logger - A `Logger` to write log messages to.\n   * @param incomingRules - The client's existing push rules\n   * @param userId - The Matrix ID of the client.\n   * @returns The rewritten rules\n   */\n  static rewriteDefaultRules(logger, incomingRules) {\n    var userId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;\n    var newRules = JSON.parse(JSON.stringify(incomingRules)); // deep clone\n\n    // These lines are mostly to make the tests happy. We shouldn't run into these\n    // properties missing in practice.\n    if (!newRules) newRules = {};\n    if (!newRules.global) newRules.global = {};\n    if (!newRules.global.override) newRules.global.override = [];\n    if (!newRules.global.underride) newRules.global.underride = [];\n\n    // Merge the client-level defaults with the ones from the server\n    newRules.global.override = mergeRulesWithDefaults(logger, PushRuleKind.Override, newRules.global.override, DEFAULT_OVERRIDE_RULES, EXPECTED_DEFAULT_OVERRIDE_RULE_IDS);\n    newRules.global.underride = mergeRulesWithDefaults(logger, PushRuleKind.Underride, newRules.global.underride, DEFAULT_UNDERRIDE_RULES, EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS);\n    return newRules;\n  }\n\n  /**\n   * Create a RegExp object for the given glob pattern with a single capture group around the pattern itself, caching the result.\n   * No cache invalidation is present currently,\n   * as this will be inherently bounded to the size of the user's own push rules.\n   * @param pattern - the glob pattern to convert to a RegExp\n   * @param alignToWordBoundary - whether to align the pattern to word boundaries,\n   *     as specified for `content.body` matches, will use lookaround assertions to ensure the match only includes the pattern\n   * @param flags - the flags to pass to the RegExp constructor, defaults to case-insensitive\n   */\n  static getPushRuleGlobRegex(pattern) {\n    var alignToWordBoundary = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n    var flags = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : \"i\";\n    var [prefix, suffix] = alignToWordBoundary ? [\"(?<=^|\\\\W)\", \"(?=\\\\W|$)\"] : [\"^\", \"$\"];\n    var cacheKey = \"\".concat(alignToWordBoundary, \"-\").concat(flags, \"-\").concat(pattern);\n    if (!PushProcessor.cachedGlobToRegex[cacheKey]) {\n      PushProcessor.cachedGlobToRegex[cacheKey] = new RegExp(prefix + \"(\" + globToRegexp(pattern) + \")\" + suffix, flags);\n    }\n    return PushProcessor.cachedGlobToRegex[cacheKey];\n  }\n\n  /**\n   * Pre-caches the parsed keys for push rules and cleans out any obsolete cache\n   * entries. Should be called after push rules are updated.\n   * @param newRules - The new push rules.\n   */\n  updateCachedPushRuleKeys(newRules) {\n    // These lines are mostly to make the tests happy. We shouldn't run into these\n    // properties missing in practice.\n    if (!newRules) newRules = {};\n    if (!newRules.global) newRules.global = {};\n    if (!newRules.global.override) newRules.global.override = [];\n    if (!newRules.global.room) newRules.global.room = [];\n    if (!newRules.global.sender) newRules.global.sender = [];\n    if (!newRules.global.underride) newRules.global.underride = [];\n\n    // Process the 'key' property on event_match conditions pre-cache the\n    // values and clean-out any unused values.\n    var toRemoveKeys = new Set(this.parsedKeys.keys());\n    for (var ruleset of [newRules.global.override, newRules.global.room, newRules.global.sender, newRules.global.underride]) {\n      for (var rule of ruleset) {\n        if (!rule.conditions) {\n          continue;\n        }\n        for (var condition of rule.conditions) {\n          if (condition.kind !== ConditionKind.EventMatch) {\n            continue;\n          }\n\n          // Ensure we keep this key.\n          toRemoveKeys.delete(condition.key);\n\n          // Pre-process the key.\n          this.parsedKeys.set(condition.key, PushProcessor.partsForDottedKey(condition.key));\n        }\n      }\n    }\n    // Any keys that were previously cached, but are no longer needed should\n    // be removed.\n    toRemoveKeys.forEach(k => this.parsedKeys.delete(k));\n  }\n  // $glob: RegExp\n\n  matchingRuleFromKindSet(ev, kindset) {\n    for (var kind of RULEKINDS_IN_ORDER) {\n      var ruleset = kindset[kind];\n      if (!ruleset) {\n        continue;\n      }\n      for (var rule of ruleset) {\n        if (!rule.enabled) {\n          continue;\n        }\n        var rawrule = this.templateRuleToRaw(kind, rule);\n        if (!rawrule) {\n          continue;\n        }\n        if (this.ruleMatchesEvent(rawrule, ev)) {\n          return _objectSpread(_objectSpread({}, rule), {}, {\n            kind\n          });\n        }\n      }\n    }\n    return null;\n  }\n  templateRuleToRaw(kind, tprule) {\n    var rawrule = {\n      rule_id: tprule.rule_id,\n      actions: tprule.actions,\n      conditions: []\n    };\n    switch (kind) {\n      case PushRuleKind.Underride:\n      case PushRuleKind.Override:\n        rawrule.conditions = tprule.conditions;\n        break;\n      case PushRuleKind.RoomSpecific:\n        if (!tprule.rule_id) {\n          return null;\n        }\n        rawrule.conditions.push({\n          kind: ConditionKind.EventMatch,\n          key: \"room_id\",\n          value: tprule.rule_id\n        });\n        break;\n      case PushRuleKind.SenderSpecific:\n        if (!tprule.rule_id) {\n          return null;\n        }\n        rawrule.conditions.push({\n          kind: ConditionKind.EventMatch,\n          key: \"user_id\",\n          value: tprule.rule_id\n        });\n        break;\n      case PushRuleKind.ContentSpecific:\n        if (!tprule.pattern) {\n          return null;\n        }\n        rawrule.conditions.push({\n          kind: ConditionKind.EventMatch,\n          key: \"content.body\",\n          pattern: tprule.pattern\n        });\n        break;\n    }\n    return rawrule;\n  }\n  eventFulfillsCondition(cond, ev) {\n    switch (cond.kind) {\n      case ConditionKind.EventMatch:\n        return this.eventFulfillsEventMatchCondition(cond, ev);\n      case ConditionKind.EventPropertyIs:\n        return this.eventFulfillsEventPropertyIsCondition(cond, ev);\n      case ConditionKind.EventPropertyContains:\n        return this.eventFulfillsEventPropertyContains(cond, ev);\n      case ConditionKind.ContainsDisplayName:\n        return this.eventFulfillsDisplayNameCondition(cond, ev);\n      case ConditionKind.RoomMemberCount:\n        return this.eventFulfillsRoomMemberCountCondition(cond, ev);\n      case ConditionKind.SenderNotificationPermission:\n        return this.eventFulfillsSenderNotifPermCondition(cond, ev);\n      case ConditionKind.CallStarted:\n      case ConditionKind.CallStartedPrefix:\n        return this.eventFulfillsCallStartedCondition(cond, ev);\n    }\n\n    // unknown conditions: we previously matched all unknown conditions,\n    // but given that rules can be added to the base rules on a server,\n    // it's probably better to not match unknown conditions.\n    return false;\n  }\n  eventFulfillsSenderNotifPermCondition(cond, ev) {\n    var notifLevelKey = cond[\"key\"];\n    if (!notifLevelKey) {\n      return false;\n    }\n    var room = this.client.getRoom(ev.getRoomId());\n    if (!(room !== null && room !== void 0 && room.currentState)) {\n      return false;\n    }\n\n    // Note that this should not be the current state of the room but the state at\n    // the point the event is in the DAG. Unfortunately the js-sdk does not store\n    // this.\n    return room.currentState.mayTriggerNotifOfType(notifLevelKey, ev.getSender());\n  }\n  eventFulfillsRoomMemberCountCondition(cond, ev) {\n    if (!cond.is) {\n      return false;\n    }\n    var room = this.client.getRoom(ev.getRoomId());\n    if (!room || !room.currentState || !room.currentState.members) {\n      return false;\n    }\n    var memberCount = room.currentState.getJoinedMemberCount();\n    var m = cond.is.match(/^([=<>]*)(\\d*)$/);\n    if (!m) {\n      return false;\n    }\n    var ineq = m[1];\n    var rhs = parseInt(m[2]);\n    if (isNaN(rhs)) {\n      return false;\n    }\n    switch (ineq) {\n      case \"\":\n      case \"==\":\n        return memberCount == rhs;\n      case \"<\":\n        return memberCount < rhs;\n      case \">\":\n        return memberCount > rhs;\n      case \"<=\":\n        return memberCount <= rhs;\n      case \">=\":\n        return memberCount >= rhs;\n      default:\n        return false;\n    }\n  }\n  eventFulfillsDisplayNameCondition(cond, ev) {\n    var _room$currentState;\n    var content = ev.getContent();\n    if (ev.isEncrypted() && ev.getClearContent()) {\n      content = ev.getClearContent();\n    }\n    if (!content || !content.body || typeof content.body != \"string\") {\n      return false;\n    }\n    var room = this.client.getRoom(ev.getRoomId());\n    var member = room === null || room === void 0 || (_room$currentState = room.currentState) === null || _room$currentState === void 0 ? void 0 : _room$currentState.getMember(this.client.credentials.userId);\n    if (!member) {\n      return false;\n    }\n    var displayName = member.name;\n\n    // N.B. we can't use \\b as it chokes on unicode. however \\W seems to be okay\n    // as shorthand for [^0-9A-Za-z_].\n    var pat = new RegExp(\"(^|\\\\W)\" + escapeRegExp(displayName) + \"(\\\\W|$)\", \"i\");\n    return content.body.search(pat) > -1;\n  }\n\n  /**\n   * Check whether the given event matches the push rule condition by fetching\n   * the property from the event and comparing against the condition's glob-based\n   * pattern.\n   * @param cond - The push rule condition to check for a match.\n   * @param ev - The event to check for a match.\n   */\n  eventFulfillsEventMatchCondition(cond, ev) {\n    if (!cond.key) {\n      return false;\n    }\n    var val = this.valueForDottedKey(cond.key, ev);\n    if (typeof val !== \"string\") {\n      return false;\n    }\n\n    // XXX This does not match in a case-insensitive manner.\n    //\n    // See https://spec.matrix.org/v1.5/client-server-api/#conditions-1\n    if (cond.value) {\n      return cond.value === val;\n    }\n    if (typeof cond.pattern !== \"string\") {\n      return false;\n    }\n\n    // Align to word boundary on `content.body` matches, whole string otherwise\n    // https://spec.matrix.org/v1.13/client-server-api/#conditions-1\n    var regex = PushProcessor.getPushRuleGlobRegex(cond.pattern, cond.key === \"content.body\");\n    return !!val.match(regex);\n  }\n\n  /**\n   * Check whether the given event matches the push rule condition by fetching\n   * the property from the event and comparing exactly against the condition's\n   * value.\n   * @param cond - The push rule condition to check for a match.\n   * @param ev - The event to check for a match.\n   */\n  eventFulfillsEventPropertyIsCondition(cond, ev) {\n    if (!cond.key || cond.value === undefined) {\n      return false;\n    }\n    return cond.value === this.valueForDottedKey(cond.key, ev);\n  }\n\n  /**\n   * Check whether the given event matches the push rule condition by fetching\n   * the property from the event and comparing exactly against the condition's\n   * value.\n   * @param cond - The push rule condition to check for a match.\n   * @param ev - The event to check for a match.\n   */\n  eventFulfillsEventPropertyContains(cond, ev) {\n    if (!cond.key || cond.value === undefined) {\n      return false;\n    }\n    var val = this.valueForDottedKey(cond.key, ev);\n    if (!Array.isArray(val)) {\n      return false;\n    }\n    return val.includes(cond.value);\n  }\n  eventFulfillsCallStartedCondition(_cond, ev) {\n    // Since servers don't support properly sending push notification\n    // about MSC3401 call events, we do the handling ourselves\n    return [\"m.ring\", \"m.prompt\"].includes(ev.getContent()[\"m.intent\"]) && !(\"m.terminated\" in ev.getContent()) && (ev.getPrevContent()[\"m.terminated\"] !== ev.getContent()[\"m.terminated\"] || deepCompare(ev.getPrevContent(), {}));\n  }\n\n  /**\n   * Parse the key into the separate fields to search by splitting on\n   * unescaped \".\", and then removing any escape characters.\n   *\n   * @param str - The key of the push rule condition: a dotted field.\n   * @returns The unescaped parts to fetch.\n   * @internal\n   */\n  static partsForDottedKey(str) {\n    var result = [];\n\n    // The current field and whether the previous character was the escape\n    // character (a backslash).\n    var part = \"\";\n    var escaped = false;\n\n    // Iterate over each character, and decide whether to append to the current\n    // part (following the escape rules) or to start a new part (based on the\n    // field separator).\n    for (var c of str) {\n      // If the previous character was the escape character (a backslash)\n      // then decide what to append to the current part.\n      if (escaped) {\n        if (c === \"\\\\\" || c === \".\") {\n          // An escaped backslash or dot just gets added.\n          part += c;\n        } else {\n          // A character that shouldn't be escaped gets the backslash prepended.\n          part += \"\\\\\" + c;\n        }\n        // This always resets being escaped.\n        escaped = false;\n        continue;\n      }\n      if (c == \".\") {\n        // The field separator creates a new part.\n        result.push(part);\n        part = \"\";\n      } else if (c == \"\\\\\") {\n        // A backslash adds no characters, but starts an escape sequence.\n        escaped = true;\n      } else {\n        // Otherwise, just add the current character.\n        part += c;\n      }\n    }\n\n    // Ensure the final part is included. If there's an open escape sequence\n    // it should be included.\n    if (escaped) {\n      part += \"\\\\\";\n    }\n    result.push(part);\n    return result;\n  }\n\n  /**\n   * For a dotted field and event, fetch the value at that position, if one\n   * exists.\n   *\n   * @param key - The key of the push rule condition: a dotted field to fetch.\n   * @param ev - The matrix event to fetch the field from.\n   * @returns The value at the dotted path given by key.\n   */\n  valueForDottedKey(key, ev) {\n    // The key should already have been parsed via updateCachedPushRuleKeys,\n    // but if it hasn't (maybe via an old consumer of the SDK which hasn't\n    // been updated?) then lazily calculate it here.\n    var parts = this.parsedKeys.get(key);\n    if (parts === undefined) {\n      parts = PushProcessor.partsForDottedKey(key);\n      this.parsedKeys.set(key, parts);\n    }\n    var val;\n\n    // special-case the first component to deal with encrypted messages\n    var firstPart = parts[0];\n    var currentIndex = 0;\n    if (firstPart === \"content\") {\n      val = ev.getContent();\n      ++currentIndex;\n    } else if (firstPart === \"type\") {\n      val = ev.getType();\n      ++currentIndex;\n    } else {\n      // use the raw event for any other fields\n      val = ev.event;\n    }\n    for (; currentIndex < parts.length; ++currentIndex) {\n      // The previous iteration resulted in null or undefined, bail (and\n      // avoid the type error of attempting to retrieve a property).\n      if (isNullOrUndefined(val)) {\n        return undefined;\n      }\n      var thisPart = parts[currentIndex];\n      val = val[thisPart];\n    }\n    return val;\n  }\n  matchingRuleForEventWithRulesets(ev, rulesets) {\n    if (!rulesets) {\n      return null;\n    }\n    if (ev.getSender() === this.client.getSafeUserId()) {\n      return null;\n    }\n    return this.matchingRuleFromKindSet(ev, rulesets.global);\n  }\n  pushActionsForEventAndRulesets(ev, rulesets) {\n    var rule = this.matchingRuleForEventWithRulesets(ev, rulesets);\n    if (!rule) {\n      return {};\n    }\n    var actionObj = PushProcessor.actionListToActionsObject(rule.actions);\n\n    // Some actions are implicit in some situations: we add those here\n    if (actionObj.tweaks.highlight === undefined) {\n      // if it isn't specified, highlight if it's a content\n      // rule but otherwise not\n      actionObj.tweaks.highlight = rule.kind == PushRuleKind.ContentSpecific;\n    }\n    return {\n      actions: actionObj,\n      rule\n    };\n  }\n  ruleMatchesEvent(rule, ev) {\n    var _rule$conditions;\n    // Disable the deprecated mentions push rules if the new mentions property exists.\n    if (this.client.supportsIntentionalMentions() && ev.getContent()[\"m.mentions\"] !== undefined && (rule.rule_id === RuleId.ContainsUserName || rule.rule_id === RuleId.ContainsDisplayName || rule.rule_id === RuleId.AtRoomNotification)) {\n      return false;\n    }\n    return !((_rule$conditions = rule.conditions) !== null && _rule$conditions !== void 0 && _rule$conditions.some(cond => !this.eventFulfillsCondition(cond, ev)));\n  }\n\n  /**\n   * Get the user's push actions for the given event\n   */\n  actionsForEvent(ev) {\n    var {\n      actions\n    } = this.pushActionsForEventAndRulesets(ev, this.client.pushRules);\n    return actions || {};\n  }\n  actionsAndRuleForEvent(ev) {\n    return this.pushActionsForEventAndRulesets(ev, this.client.pushRules);\n  }\n\n  /**\n   * Get one of the users push rules by its ID\n   *\n   * @param ruleId - The ID of the rule to search for\n   * @returns The push rule, or null if no such rule was found\n   */\n  getPushRuleById(ruleId) {\n    var _result$rule;\n    var result = this.getPushRuleAndKindById(ruleId);\n    return (_result$rule = result === null || result === void 0 ? void 0 : result.rule) !== null && _result$rule !== void 0 ? _result$rule : null;\n  }\n\n  /**\n   * Get one of the users push rules by its ID\n   *\n   * @param ruleId - The ID of the rule to search for\n   * @returns rule The push rule, or null if no such rule was found\n   * @returns kind - The PushRuleKind of the rule to search for\n   */\n  getPushRuleAndKindById(ruleId) {\n    for (var scope of [\"global\"]) {\n      var _this$client$pushRule;\n      if (((_this$client$pushRule = this.client.pushRules) === null || _this$client$pushRule === void 0 ? void 0 : _this$client$pushRule[scope]) === undefined) continue;\n      for (var kind of RULEKINDS_IN_ORDER) {\n        if (this.client.pushRules[scope][kind] === undefined) continue;\n        for (var rule of this.client.pushRules[scope][kind]) {\n          if (rule.rule_id === ruleId) return {\n            rule,\n            kind\n          };\n        }\n      }\n    }\n    return null;\n  }\n}\n_defineProperty(PushProcessor, \"cachedGlobToRegex\", {});\n//# sourceMappingURL=pushprocessor.js.map","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * A list of the spec versions which the js-sdk is compatible with.\n *\n * In practice, this means: when we connect to a server, it must declare support for one of the versions in this list.\n *\n * Note that it does not *necessarily* mean that the js-sdk has good support for all the features in the listed spec\n * versions; only that we should be able to provide a base level of functionality with a server that offers support for\n * any of the listed versions.\n */\nexport var SUPPORTED_MATRIX_VERSIONS = [\"v1.1\", \"v1.2\", \"v1.3\", \"v1.4\", \"v1.5\", \"v1.6\", \"v1.7\", \"v1.8\", \"v1.9\"];\n\n/**\n * The oldest Matrix specification version the js-sdk supports.\n */\nexport var MINIMUM_MATRIX_VERSION = SUPPORTED_MATRIX_VERSIONS[0];\n\n/**\n * The most recent Matrix specification version the js-sdk supports.\n */\nexport var MAXIMUM_MATRIX_VERSION = SUPPORTED_MATRIX_VERSIONS[SUPPORTED_MATRIX_VERSIONS.length - 1];\n//# sourceMappingURL=version-support.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"./logger.js\";\nimport { Method, timeoutSignal } from \"./http-api/index.js\";\nimport { SUPPORTED_MATRIX_VERSIONS } from \"./version-support.js\";\n\n// Dev note: Auto discovery is part of the spec.\n// See: https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery\n\nexport var AutoDiscoveryAction = /*#__PURE__*/function (AutoDiscoveryAction) {\n  AutoDiscoveryAction[\"SUCCESS\"] = \"SUCCESS\";\n  AutoDiscoveryAction[\"IGNORE\"] = \"IGNORE\";\n  AutoDiscoveryAction[\"PROMPT\"] = \"PROMPT\";\n  AutoDiscoveryAction[\"FAIL_PROMPT\"] = \"FAIL_PROMPT\";\n  AutoDiscoveryAction[\"FAIL_ERROR\"] = \"FAIL_ERROR\";\n  return AutoDiscoveryAction;\n}({});\nexport var AutoDiscoveryError = /*#__PURE__*/function (AutoDiscoveryError) {\n  AutoDiscoveryError[\"Invalid\"] = \"Invalid homeserver discovery response\";\n  AutoDiscoveryError[\"GenericFailure\"] = \"Failed to get autodiscovery configuration from server\";\n  AutoDiscoveryError[\"InvalidHsBaseUrl\"] = \"Invalid base_url for m.homeserver\";\n  AutoDiscoveryError[\"InvalidHomeserver\"] = \"Homeserver URL does not appear to be a valid Matrix homeserver\";\n  AutoDiscoveryError[\"InvalidIsBaseUrl\"] = \"Invalid base_url for m.identity_server\";\n  AutoDiscoveryError[\"InvalidIdentityServer\"] = \"Identity server URL does not appear to be a valid identity server\";\n  AutoDiscoveryError[\"InvalidIs\"] = \"Invalid identity server discovery response\";\n  AutoDiscoveryError[\"MissingWellknown\"] = \"No .well-known JSON file found\";\n  AutoDiscoveryError[\"InvalidJson\"] = \"Invalid JSON\";\n  AutoDiscoveryError[\"UnsupportedHomeserverSpecVersion\"] = \"The homeserver does not meet the version requirements\"; // TODO: Implement when Sydent supports the `/versions` endpoint - https://github.com/matrix-org/sydent/issues/424\n  //IdentityServerTooOld = \"The identity server does not meet the minimum version requirements\",\n  return AutoDiscoveryError;\n}({});\n/**\n * Utilities for automatically discovery resources, such as homeservers\n * for users to log in to.\n */\nexport class AutoDiscovery {\n  /**\n   * Validates and verifies client configuration information for purposes\n   * of logging in. Such information includes the homeserver URL\n   * and identity server URL the client would want. Additional details\n   * may also be included, and will be transparently brought into the\n   * response object unaltered.\n   * @param wellknown - The configuration object itself, as returned\n   * by the .well-known auto-discovery endpoint.\n   * @returns Promise which resolves to the verified\n   * configuration, which may include error states. Rejects on unexpected\n   * failure, not when verification fails.\n   */\n  static fromDiscoveryConfig(wellknown) {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      var _hsVersions$raw;\n      // Step 1 is to get the config, which is provided to us here.\n\n      // We default to an error state to make the first few checks easier to\n      // write. We'll update the properties of this object over the duration\n      // of this function.\n      var clientConfig = {\n        \"m.homeserver\": {\n          state: AutoDiscovery.FAIL_ERROR,\n          error: AutoDiscovery.ERROR_INVALID,\n          base_url: null\n        },\n        \"m.identity_server\": {\n          // Technically, we don't have a problem with the identity server\n          // config at this point.\n          state: AutoDiscovery.PROMPT,\n          error: null,\n          base_url: null\n        }\n      };\n      if (!(wellknown !== null && wellknown !== void 0 && wellknown[\"m.homeserver\"])) {\n        logger.error(\"No m.homeserver key in config\");\n        clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n        clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID;\n        return Promise.resolve(clientConfig);\n      }\n      if (!wellknown[\"m.homeserver\"][\"base_url\"]) {\n        logger.error(\"No m.homeserver base_url in config\");\n        clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n        clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;\n        return Promise.resolve(clientConfig);\n      }\n\n      // Step 2: Make sure the homeserver URL is valid *looking*. We'll make\n      // sure it points to a homeserver in Step 3.\n      var hsUrl = _this.sanitizeWellKnownUrl(wellknown[\"m.homeserver\"][\"base_url\"]);\n      if (!hsUrl) {\n        logger.error(\"Invalid base_url for m.homeserver\");\n        clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;\n        return Promise.resolve(clientConfig);\n      }\n\n      // Step 3: Make sure the homeserver URL points to a homeserver.\n      var hsVersions = yield _this.fetchWellKnownObject(\"\".concat(hsUrl, \"/_matrix/client/versions\"));\n      if (!hsVersions || !Array.isArray((_hsVersions$raw = hsVersions.raw) === null || _hsVersions$raw === void 0 ? void 0 : _hsVersions$raw[\"versions\"])) {\n        logger.error(\"Invalid /versions response\");\n        clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HOMESERVER;\n\n        // Supply the base_url to the caller because they may be ignoring liveliness\n        // errors, like this one.\n        clientConfig[\"m.homeserver\"].base_url = hsUrl;\n        return Promise.resolve(clientConfig);\n      }\n\n      // Step 3.1: Non-spec check to ensure the server will actually work for us. We need to check if\n      // any of the versions in `SUPPORTED_MATRIX_VERSIONS` are listed in the /versions response.\n      var hsVersionSet = new Set(hsVersions.raw[\"versions\"]);\n      var supportedVersionFound = false;\n      for (var version of SUPPORTED_MATRIX_VERSIONS) {\n        if (hsVersionSet.has(version)) {\n          supportedVersionFound = true;\n          break;\n        }\n      }\n      if (!supportedVersionFound) {\n        logger.error(\"Homeserver does not meet version requirements\");\n        clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION;\n\n        // Supply the base_url to the caller because they may be ignoring liveliness\n        // errors, like this one.\n        clientConfig[\"m.homeserver\"].base_url = hsUrl;\n        return Promise.resolve(clientConfig);\n      }\n\n      // Step 4: Now that the homeserver looks valid, update our client config.\n      clientConfig[\"m.homeserver\"] = {\n        state: AutoDiscovery.SUCCESS,\n        error: null,\n        base_url: hsUrl\n      };\n\n      // Step 5: Try to pull out the identity server configuration\n      var isUrl = \"\";\n      if (wellknown[\"m.identity_server\"]) {\n        // We prepare a failing identity server response to save lines later\n        // in this branch.\n        var failingClientConfig = {\n          \"m.homeserver\": clientConfig[\"m.homeserver\"],\n          \"m.identity_server\": {\n            state: AutoDiscovery.FAIL_PROMPT,\n            error: AutoDiscovery.ERROR_INVALID_IS,\n            base_url: null\n          }\n        };\n\n        // Step 5a: Make sure the URL is valid *looking*. We'll make sure it\n        // points to an identity server in Step 5b.\n        isUrl = _this.sanitizeWellKnownUrl(wellknown[\"m.identity_server\"][\"base_url\"]);\n        if (!isUrl) {\n          logger.error(\"Invalid base_url for m.identity_server\");\n          failingClientConfig[\"m.identity_server\"].error = AutoDiscovery.ERROR_INVALID_IS_BASE_URL;\n          return Promise.resolve(failingClientConfig);\n        }\n\n        // Step 5b: Verify there is an identity server listening on the provided\n        // URL.\n        var isResponse = yield _this.fetchWellKnownObject(\"\".concat(isUrl, \"/_matrix/identity/v2\"));\n        if (!(isResponse !== null && isResponse !== void 0 && isResponse.raw) || isResponse.action !== AutoDiscoveryAction.SUCCESS) {\n          logger.error(\"Invalid /v2 response\");\n          failingClientConfig[\"m.identity_server\"].error = AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER;\n\n          // Supply the base_url to the caller because they may be ignoring\n          // liveliness errors, like this one.\n          failingClientConfig[\"m.identity_server\"].base_url = isUrl;\n          return Promise.resolve(failingClientConfig);\n        }\n      }\n\n      // Step 6: Now that the identity server is valid, or never existed,\n      // populate the IS section.\n      if (isUrl && isUrl.toString().length > 0) {\n        clientConfig[\"m.identity_server\"] = {\n          state: AutoDiscovery.SUCCESS,\n          error: null,\n          base_url: isUrl\n        };\n      }\n\n      // Step 7: Copy any other keys directly into the clientConfig. This is for\n      // things like custom configuration of services.\n      Object.keys(wellknown).forEach(k => {\n        if (k === \"m.homeserver\" || k === \"m.identity_server\") {\n          // Only copy selected parts of the config to avoid overwriting\n          // properties computed by the validation logic above.\n          var notProps = [\"error\", \"state\", \"base_url\"];\n          for (var prop of Object.keys(wellknown[k])) {\n            if (notProps.includes(prop)) continue;\n            // @ts-ignore - ts gets unhappy as we're mixing types here\n            clientConfig[k][prop] = wellknown[k][prop];\n          }\n        } else {\n          // Just copy the whole thing over otherwise\n          clientConfig[k] = wellknown[k];\n        }\n      });\n\n      // Step 8: Give the config to the caller (finally)\n      return Promise.resolve(clientConfig);\n    })();\n  }\n\n  /**\n   * Attempts to automatically discover client configuration information\n   * prior to logging in. Such information includes the homeserver URL\n   * and identity server URL the client would want. Additional details\n   * may also be discovered, and will be transparently included in the\n   * response object unaltered.\n   * @param domain - The homeserver domain to perform discovery\n   * on. For example, \"matrix.org\".\n   * @returns Promise which resolves to the discovered\n   * configuration, which may include error states. Rejects on unexpected\n   * failure, not when discovery fails.\n   */\n  static findClientConfig(domain) {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      if (!domain || typeof domain !== \"string\" || domain.length === 0) {\n        throw new Error(\"'domain' must be a string of non-zero length\");\n      }\n\n      // We use a .well-known lookup for all cases. According to the spec, we\n      // can do other discovery mechanisms if we want such as custom lookups\n      // however we won't bother with that here (mostly because the spec only\n      // supports .well-known right now).\n      //\n      // By using .well-known, we need to ensure we at least pull out a URL\n      // for the homeserver. We don't really need an identity server configuration\n      // but will return one anyways (with state PROMPT) to make development\n      // easier for clients. If we can't get a homeserver URL, all bets are\n      // off on the rest of the config and we'll assume it is invalid too.\n\n      // We default to an error state to make the first few checks easier to\n      // write. We'll update the properties of this object over the duration\n      // of this function.\n      var clientConfig = {\n        \"m.homeserver\": {\n          state: AutoDiscovery.FAIL_ERROR,\n          error: AutoDiscovery.ERROR_INVALID,\n          base_url: null\n        },\n        \"m.identity_server\": {\n          // Technically, we don't have a problem with the identity server\n          // config at this point.\n          state: AutoDiscovery.PROMPT,\n          error: null,\n          base_url: null\n        }\n      };\n\n      // Step 1: Actually request the .well-known JSON file and make sure it\n      // at least has a homeserver definition.\n      var domainWithProtocol = domain.includes(\"://\") ? domain : \"https://\".concat(domain);\n      var wellknown = yield _this2.fetchWellKnownObject(\"\".concat(domainWithProtocol, \"/.well-known/matrix/client\"));\n      if (!wellknown || wellknown.action !== AutoDiscoveryAction.SUCCESS) {\n        logger.error(\"No response or error when parsing .well-known\");\n        if (wellknown.reason) logger.error(wellknown.reason);\n        if (wellknown.action === AutoDiscoveryAction.IGNORE) {\n          clientConfig[\"m.homeserver\"] = {\n            state: AutoDiscovery.PROMPT,\n            error: null,\n            base_url: null\n          };\n        } else {\n          // this can only ever be FAIL_PROMPT at this point.\n          clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n          clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID;\n        }\n        return Promise.resolve(clientConfig);\n      }\n\n      // Step 2: Validate and parse the config\n      return AutoDiscovery.fromDiscoveryConfig(wellknown.raw);\n    })();\n  }\n\n  /**\n   * Gets the raw discovery client configuration for the given domain name.\n   * Should only be used if there's no validation to be done on the resulting\n   * object, otherwise use findClientConfig().\n   * @param domain - The domain to get the client config for.\n   * @returns Promise which resolves to the domain's client config. Can\n   * be an empty object.\n   */\n  static getRawClientConfig(domain) {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      var _response$raw;\n      if (!domain || typeof domain !== \"string\" || domain.length === 0) {\n        throw new Error(\"'domain' must be a string of non-zero length\");\n      }\n      var response = yield _this3.fetchWellKnownObject(\"https://\".concat(domain, \"/.well-known/matrix/client\"));\n      if (!response) return {};\n      return (_response$raw = response.raw) !== null && _response$raw !== void 0 ? _response$raw : {};\n    })();\n  }\n\n  /**\n   * Sanitizes a given URL to ensure it is either an HTTP or HTTP URL and\n   * is suitable for the requirements laid out by .well-known auto discovery.\n   * If valid, the URL will also be stripped of any trailing slashes.\n   * @param url - The potentially invalid URL to sanitize.\n   * @returns The sanitized URL or a falsey value if the URL is invalid.\n   * @internal\n   */\n  static sanitizeWellKnownUrl(url) {\n    if (!url) return false;\n    try {\n      var _parsed;\n      var parsed;\n      try {\n        parsed = new URL(url);\n      } catch (e) {\n        logger.error(\"Could not parse url\", e);\n      }\n      if (!((_parsed = parsed) !== null && _parsed !== void 0 && _parsed.hostname)) return false;\n      if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") return false;\n      var port = parsed.port ? \":\".concat(parsed.port) : \"\";\n      var path = parsed.pathname ? parsed.pathname : \"\";\n      var saferUrl = \"\".concat(parsed.protocol, \"//\").concat(parsed.hostname).concat(port).concat(path);\n      if (saferUrl.endsWith(\"/\")) {\n        saferUrl = saferUrl.substring(0, saferUrl.length - 1);\n      }\n      return saferUrl;\n    } catch (e) {\n      logger.error(e);\n      return false;\n    }\n  }\n  static fetch(resource, options) {\n    if (this.fetchFn) {\n      return this.fetchFn(resource, options);\n    }\n    return globalThis.fetch(resource, options);\n  }\n  static setFetchFn(fetchFn) {\n    AutoDiscovery.fetchFn = fetchFn;\n  }\n\n  /**\n   * Fetches a JSON object from a given URL, as expected by all .well-known\n   * related lookups. If the server gives a 404 then the `action` will be\n   * IGNORE. If the server returns something that isn't JSON, the `action`\n   * will be FAIL_PROMPT. For any other failure the `action` will be FAIL_PROMPT.\n   *\n   * The returned object will be a result of the call in object form with\n   * the following properties:\n   *   raw: The JSON object returned by the server.\n   *   action: One of SUCCESS, IGNORE, or FAIL_PROMPT.\n   *   reason: Relatively human-readable description of what went wrong.\n   *   error: The actual Error, if one exists.\n   * @param url - The URL to fetch a JSON object from.\n   * @returns Promise which resolves to the returned state.\n   * @internal\n   */\n  static fetchWellKnownObject(url) {\n    return _asyncToGenerator(function* () {\n      var response;\n      try {\n        response = yield AutoDiscovery.fetch(url, {\n          method: Method.Get,\n          signal: timeoutSignal(5000)\n        });\n        if (response.status === 404) {\n          return {\n            raw: {},\n            action: AutoDiscoveryAction.IGNORE,\n            reason: AutoDiscovery.ERROR_MISSING_WELLKNOWN\n          };\n        }\n        if (response.status !== 200) {\n          return {\n            raw: {},\n            action: AutoDiscoveryAction.FAIL_PROMPT,\n            reason: \"General failure\"\n          };\n        }\n      } catch (err) {\n        var error = err;\n        var reason = \"\";\n        if (typeof error === \"object\") {\n          reason = error === null || error === void 0 ? void 0 : error.message;\n        }\n        return {\n          error,\n          raw: {},\n          action: AutoDiscoveryAction.FAIL_PROMPT,\n          reason: reason || \"General failure\"\n        };\n      }\n      try {\n        return {\n          raw: yield response.json(),\n          action: AutoDiscoveryAction.SUCCESS\n        };\n      } catch (err) {\n        var _error = err;\n        return {\n          error: _error,\n          raw: {},\n          action: AutoDiscoveryAction.FAIL_PROMPT,\n          reason: (_error === null || _error === void 0 ? void 0 : _error.name) === \"SyntaxError\" ? AutoDiscovery.ERROR_INVALID_JSON : AutoDiscovery.ERROR_INVALID\n        };\n      }\n    })();\n  }\n}\n// Dev note: the constants defined here are related to but not\n// exactly the same as those in the spec. This is to hopefully\n// translate the meaning of the states in the spec, but also\n// support our own if needed.\n_defineProperty(AutoDiscovery, \"ERROR_INVALID\", AutoDiscoveryError.Invalid);\n_defineProperty(AutoDiscovery, \"ERROR_GENERIC_FAILURE\", AutoDiscoveryError.GenericFailure);\n_defineProperty(AutoDiscovery, \"ERROR_INVALID_HS_BASE_URL\", AutoDiscoveryError.InvalidHsBaseUrl);\n_defineProperty(AutoDiscovery, \"ERROR_INVALID_HOMESERVER\", AutoDiscoveryError.InvalidHomeserver);\n_defineProperty(AutoDiscovery, \"ERROR_INVALID_IS_BASE_URL\", AutoDiscoveryError.InvalidIsBaseUrl);\n_defineProperty(AutoDiscovery, \"ERROR_INVALID_IDENTITY_SERVER\", AutoDiscoveryError.InvalidIdentityServer);\n_defineProperty(AutoDiscovery, \"ERROR_INVALID_IS\", AutoDiscoveryError.InvalidIs);\n_defineProperty(AutoDiscovery, \"ERROR_MISSING_WELLKNOWN\", AutoDiscoveryError.MissingWellknown);\n_defineProperty(AutoDiscovery, \"ERROR_INVALID_JSON\", AutoDiscoveryError.InvalidJson);\n_defineProperty(AutoDiscovery, \"ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION\", AutoDiscoveryError.UnsupportedHomeserverSpecVersion);\n_defineProperty(AutoDiscovery, \"ALL_ERRORS\", Object.keys(AutoDiscoveryError));\n/**\n * The auto discovery failed. The client is expected to communicate\n * the error to the user and refuse logging in.\n */\n_defineProperty(AutoDiscovery, \"FAIL_ERROR\", AutoDiscoveryAction.FAIL_ERROR);\n/**\n * The auto discovery failed, however the client may still recover\n * from the problem. The client is recommended to that the same\n * action it would for PROMPT while also warning the user about\n * what went wrong. The client may also treat this the same as\n * a FAIL_ERROR state.\n */\n_defineProperty(AutoDiscovery, \"FAIL_PROMPT\", AutoDiscoveryAction.FAIL_PROMPT);\n/**\n * The auto discovery didn't fail but did not find anything of\n * interest. The client is expected to prompt the user for more\n * information, or fail if it prefers.\n */\n_defineProperty(AutoDiscovery, \"PROMPT\", AutoDiscoveryAction.PROMPT);\n/**\n * The auto discovery was successful.\n */\n_defineProperty(AutoDiscovery, \"SUCCESS\", AutoDiscoveryAction.SUCCESS);\n_defineProperty(AutoDiscovery, \"fetchFn\", void 0);\n//# sourceMappingURL=autodiscovery.js.map","/*\nCopyright 2019 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport var SERVICE_TYPES = /*#__PURE__*/function (SERVICE_TYPES) {\n  SERVICE_TYPES[\"IS\"] = \"SERVICE_TYPE_IS\";\n  // An identity server\n  SERVICE_TYPES[\"IM\"] = \"SERVICE_TYPE_IM\"; // An integration manager\n  return SERVICE_TYPES;\n}({});\n//# sourceMappingURL=service-types.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { Direction } from \"./event-timeline.js\";\nexport class EventContext {\n  /**\n   * Construct a new EventContext\n   *\n   * An eventcontext is used for circumstances such as search results, when we\n   * have a particular event of interest, and a bunch of events before and after\n   * it.\n   *\n   * It also stores pagination tokens for going backwards and forwards in the\n   * timeline.\n   *\n   * @param ourEvent - the event at the centre of this context\n   */\n  constructor(ourEvent) {\n    this.ourEvent = ourEvent;\n    _defineProperty(this, \"timeline\", void 0);\n    _defineProperty(this, \"ourEventIndex\", 0);\n    _defineProperty(this, \"paginateTokens\", {\n      [Direction.Backward]: null,\n      [Direction.Forward]: null\n    });\n    this.timeline = [ourEvent];\n  }\n\n  /**\n   * Get the main event of interest\n   *\n   * This is a convenience function for getTimeline()[getOurEventIndex()].\n   *\n   * @returns The event at the centre of this context.\n   */\n  getEvent() {\n    return this.timeline[this.ourEventIndex];\n  }\n\n  /**\n   * Get the list of events in this context\n   *\n   * @returns An array of MatrixEvents\n   */\n  getTimeline() {\n    return this.timeline;\n  }\n\n  /**\n   * Get the index in the timeline of our event\n   */\n  getOurEventIndex() {\n    return this.ourEventIndex;\n  }\n\n  /**\n   * Get a pagination token.\n   *\n   * @param backwards -   true to get the pagination token for going\n   */\n  getPaginateToken() {\n    var backwards = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n    return this.paginateTokens[backwards ? Direction.Backward : Direction.Forward];\n  }\n\n  /**\n   * Set a pagination token.\n   *\n   * Generally this will be used only by the matrix js sdk.\n   *\n   * @param token -        pagination token\n   * @param backwards -   true to set the pagination token for going\n   *                                   backwards in time\n   */\n  setPaginateToken(token) {\n    var backwards = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n    this.paginateTokens[backwards ? Direction.Backward : Direction.Forward] = token !== null && token !== void 0 ? token : null;\n  }\n\n  /**\n   * Add more events to the timeline\n   *\n   * @param events -      new events, in timeline order\n   * @param atStart -   true to insert new events at the start\n   */\n  addEvents(events) {\n    var atStart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n    // TODO: should we share logic with Room.addEventsToTimeline?\n    // Should Room even use EventContext?\n\n    if (atStart) {\n      this.timeline = events.concat(this.timeline);\n      this.ourEventIndex += events.length;\n    } else {\n      this.timeline = this.timeline.concat(events);\n    }\n  }\n}\n//# sourceMappingURL=event-context.js.map","/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventContext } from \"./event-context.js\";\nexport class SearchResult {\n  /**\n   * Create a SearchResponse from the response to /search\n   */\n\n  static fromJson(jsonObj, eventMapper) {\n    var jsonContext = jsonObj.context || {};\n    var eventsBefore = (jsonContext.events_before || []).map(eventMapper);\n    var eventsAfter = (jsonContext.events_after || []).map(eventMapper);\n    var context = new EventContext(eventMapper(jsonObj.result));\n\n    // Filter out any contextual events which do not correspond to the same timeline (thread or room)\n    var threadRootId = context.ourEvent.threadRootId;\n    eventsBefore = eventsBefore.filter(e => e.threadRootId === threadRootId);\n    eventsAfter = eventsAfter.filter(e => e.threadRootId === threadRootId);\n    context.setPaginateToken(jsonContext.start, true);\n    context.addEvents(eventsBefore, true);\n    context.addEvents(eventsAfter, false);\n    context.setPaginateToken(jsonContext.end, false);\n    return new SearchResult(jsonObj.rank, context);\n  }\n\n  /**\n   * Construct a new SearchResult\n   *\n   * @param rank -   where this SearchResult ranks in the results\n   * @param context -  the matching event and its\n   *    context\n   */\n  constructor(rank, context) {\n    this.rank = rank;\n    this.context = context;\n  }\n}\n//# sourceMappingURL=search-result.js.map","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// allow camelcase as these are things that go onto the wire\n/* eslint-disable camelcase */\n\n/** Options object for {@link MatrixClient.invite}. */\n\nexport function isSendDelayedEventRequestOpts(opts) {\n  if (\"parent_delay_id\" in opts && typeof opts.parent_delay_id !== \"string\") {\n    // Invalid type, reject\n    return false;\n  }\n  if (\"delay\" in opts && typeof opts.delay !== \"number\") {\n    // Invalid type, reject.\n    return true;\n  }\n  // At least one of these fields must be specified.\n  return \"delay\" in opts || \"parent_delay_id\" in opts;\n}\nexport var UpdateDelayedEventAction = /*#__PURE__*/function (UpdateDelayedEventAction) {\n  UpdateDelayedEventAction[\"Cancel\"] = \"cancel\";\n  UpdateDelayedEventAction[\"Restart\"] = \"restart\";\n  UpdateDelayedEventAction[\"Send\"] = \"send\";\n  return UpdateDelayedEventAction;\n}({});\n\n/* eslint-enable camelcase */\n//# sourceMappingURL=requests.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixEvent, MatrixEventEvent } from \"./models/event.js\";\nimport { RelationType } from \"./@types/event.js\";\nexport function eventMapperFor(client, options) {\n  var preventReEmit = Boolean(options.preventReEmit);\n  var decrypt = options.decrypt !== false;\n  function mapper(plainOldJsObject) {\n    var room = client.getRoom(plainOldJsObject.room_id);\n    var event;\n    // If the event is already known to the room, let's re-use the model rather than duplicating.\n    // We avoid doing this to state events as they may be forward or backwards looking which tweaks behaviour.\n    if (room && plainOldJsObject.state_key === undefined) {\n      event = room.findEventById(plainOldJsObject.event_id);\n    }\n    if (!event || event.status) {\n      event = new MatrixEvent(plainOldJsObject);\n    } else {\n      // merge the latest unsigned data from the server\n      event.setUnsigned(_objectSpread(_objectSpread({}, event.getUnsigned()), plainOldJsObject.unsigned));\n      // prevent doubling up re-emitters\n      preventReEmit = true;\n    }\n\n    // if there is a complete edit bundled alongside the event, perform the replacement.\n    // (prior to MSC3925, events were automatically replaced on the server-side. MSC3925 proposes that that doesn't\n    // happen automatically but the server does provide us with the whole content of the edit event.)\n    var bundledEdit = event.getServerAggregatedRelation(RelationType.Replace);\n    if (bundledEdit !== null && bundledEdit !== void 0 && bundledEdit.content) {\n      var replacement = mapper(bundledEdit);\n      // XXX: it's worth noting that the spec says we should only respect encrypted edits if, once decrypted, the\n      //   replacement has a `m.new_content` property. The problem is that we haven't yet decrypted the replacement\n      //   (it should be happening in the background), so we can't enforce this. Possibly we should for decryption\n      //   to complete, but that sounds a bit racy. For now, we just assume it's ok.\n      event.makeReplaced(replacement);\n    }\n    var thread = room === null || room === void 0 ? void 0 : room.findThreadForEvent(event);\n    if (thread) {\n      event.setThread(thread);\n    }\n    if (event.isEncrypted()) {\n      if (!preventReEmit) {\n        client.reEmitter.reEmit(event, [MatrixEventEvent.Decrypted]);\n      }\n      if (decrypt) {\n        client.decryptEventIfNeeded(event);\n      }\n    }\n    if (!preventReEmit) {\n      client.reEmitter.reEmit(event, [MatrixEventEvent.Replaced, MatrixEventEvent.VisibilityChange]);\n      room === null || room === void 0 || room.reEmitter.reEmit(event, [MatrixEventEvent.BeforeRedaction]);\n    }\n    return event;\n  }\n  return mapper;\n}\n//# sourceMappingURL=event-mapper.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nimport _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { RelationType, UNSTABLE_MSC3089_BRANCH } from \"../@types/event.js\";\nimport { EventTimeline } from \"./event-timeline.js\";\n/**\n * Represents a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) branch - a reference\n * to a file (leaf) in the tree. Note that this is UNSTABLE and subject to breaking changes\n * without notice.\n */\nexport class MSC3089Branch {\n  constructor(client, indexEvent, directory) {\n    this.client = client;\n    this.indexEvent = indexEvent;\n    this.directory = directory;\n  } // Nothing to do\n\n  /**\n   * The file ID.\n   */\n  get id() {\n    var stateKey = this.indexEvent.getStateKey();\n    if (!stateKey) {\n      throw new Error(\"State key not found for branch\");\n    }\n    return stateKey;\n  }\n\n  /**\n   * Whether this branch is active/valid.\n   */\n  get isActive() {\n    return this.indexEvent.getContent()[\"active\"] === true;\n  }\n\n  /**\n   * Version for the file, one-indexed.\n   */\n  get version() {\n    var _this$indexEvent$getC;\n    return (_this$indexEvent$getC = this.indexEvent.getContent()[\"version\"]) !== null && _this$indexEvent$getC !== void 0 ? _this$indexEvent$getC : 1;\n  }\n  get roomId() {\n    return this.indexEvent.getRoomId();\n  }\n\n  /**\n   * Deletes the file from the tree, including all prior edits/versions.\n   * @returns Promise which resolves when complete.\n   */\n  delete() {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      yield _this.client.sendStateEvent(_this.roomId, UNSTABLE_MSC3089_BRANCH.name, {}, _this.id);\n      yield _this.client.redactEvent(_this.roomId, _this.id);\n      var nextVersion = (yield _this.getVersionHistory())[1]; // [0] will be us\n      if (nextVersion) yield nextVersion.delete(); // implicit recursion\n    })();\n  }\n\n  /**\n   * Gets the name for this file.\n   * @returns The name, or \"Unnamed File\" if unknown.\n   */\n  getName() {\n    return this.indexEvent.getContent()[\"name\"] || \"Unnamed File\";\n  }\n\n  /**\n   * Sets the name for this file.\n   * @param name - The new name for this file.\n   * @returns Promise which resolves when complete.\n   */\n  setName(name) {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      yield _this2.client.sendStateEvent(_this2.roomId, UNSTABLE_MSC3089_BRANCH.name, _objectSpread(_objectSpread({}, _this2.indexEvent.getContent()), {}, {\n        name: name\n      }), _this2.id);\n    })();\n  }\n\n  /**\n   * Gets whether or not a file is locked.\n   * @returns True if locked, false otherwise.\n   */\n  isLocked() {\n    return this.indexEvent.getContent()[\"locked\"] || false;\n  }\n\n  /**\n   * Sets a file as locked or unlocked.\n   * @param locked - True to lock the file, false otherwise.\n   * @returns Promise which resolves when complete.\n   */\n  setLocked(locked) {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      yield _this3.client.sendStateEvent(_this3.roomId, UNSTABLE_MSC3089_BRANCH.name, _objectSpread(_objectSpread({}, _this3.indexEvent.getContent()), {}, {\n        locked: locked\n      }), _this3.id);\n    })();\n  }\n\n  /**\n   * Gets information about the file needed to download it.\n   * @returns Information about the file.\n   */\n  getFileInfo() {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      var event = yield _this4.getFileEvent();\n      var file = event.getOriginalContent()[\"file\"];\n      var httpUrl = _this4.client.mxcUrlToHttp(file[\"url\"]);\n      if (!httpUrl) {\n        throw new Error(\"No HTTP URL available for \".concat(file[\"url\"]));\n      }\n      return {\n        info: file,\n        httpUrl: httpUrl\n      };\n    })();\n  }\n\n  /**\n   * Gets the event the file points to.\n   * @returns Promise which resolves to the file's event.\n   */\n  getFileEvent() {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      var room = _this5.client.getRoom(_this5.roomId);\n      if (!room) throw new Error(\"Unknown room\");\n      var event = room.getUnfilteredTimelineSet().findEventById(_this5.id);\n\n      // keep scrolling back if needed until we find the event or reach the start of the room:\n      while (!event && room.getLiveTimeline().getState(EventTimeline.BACKWARDS).paginationToken) {\n        yield _this5.client.scrollback(room, 100);\n        event = room.getUnfilteredTimelineSet().findEventById(_this5.id);\n      }\n      if (!event) throw new Error(\"Failed to find event\");\n\n      // Sometimes the event isn't decrypted for us, so do that.\n      yield _this5.client.decryptEventIfNeeded(event);\n      return event;\n    })();\n  }\n\n  /**\n   * Creates a new version of this file with contents in a type that is compatible with MatrixClient.uploadContent().\n   * @param name - The name of the file.\n   * @param encryptedContents - The encrypted contents.\n   * @param info - The encrypted file information.\n   * @param additionalContent - Optional event content fields to include in the message.\n   * @returns Promise which resolves to the file event's sent response.\n   */\n  createNewVersion(name, encryptedContents, info, additionalContent) {\n    var _this6 = this;\n    return _asyncToGenerator(function* () {\n      var fileEventResponse = yield _this6.directory.createFile(name, encryptedContents, info, _objectSpread(_objectSpread({}, additionalContent !== null && additionalContent !== void 0 ? additionalContent : {}), {}, {\n        \"m.new_content\": true,\n        \"m.relates_to\": {\n          rel_type: RelationType.Replace,\n          event_id: _this6.id\n        }\n      }));\n\n      // Update the version of the new event\n      yield _this6.client.sendStateEvent(_this6.roomId, UNSTABLE_MSC3089_BRANCH.name, {\n        active: true,\n        name: name,\n        version: _this6.version + 1\n      }, fileEventResponse[\"event_id\"]);\n\n      // Deprecate ourselves\n      yield _this6.client.sendStateEvent(_this6.roomId, UNSTABLE_MSC3089_BRANCH.name, _objectSpread(_objectSpread({}, _this6.indexEvent.getContent()), {}, {\n        active: false\n      }), _this6.id);\n      return fileEventResponse;\n    })();\n  }\n\n  /**\n   * Gets the file's version history, starting at this file.\n   * @returns Promise which resolves to the file's version history, with the\n   * first element being the current version and the last element being the first version.\n   */\n  getVersionHistory() {\n    var _this7 = this;\n    return _asyncToGenerator(function* () {\n      var fileHistory = [];\n      fileHistory.push(_this7); // start with ourselves\n\n      var room = _this7.client.getRoom(_this7.roomId);\n      if (!room) throw new Error(\"Invalid or unknown room\");\n\n      // Clone the timeline to reverse it, getting most-recent-first ordering, hopefully\n      // shortening the awful loop below. Without the clone, we can unintentionally mutate\n      // the timeline.\n      var timelineEvents = [...room.getLiveTimeline().getEvents()].reverse();\n\n      // XXX: This is a very inefficient search, but it's the best we can do with the\n      // relations structure we have in the SDK. As of writing, it is not worth the\n      // investment in improving the structure.\n      var childEvent;\n      var parentEvent = yield _this7.getFileEvent();\n      do {\n        childEvent = timelineEvents.find(e => e.replacingEventId() === parentEvent.getId());\n        if (childEvent) {\n          var branch = _this7.directory.getFile(childEvent.getId());\n          if (branch) {\n            fileHistory.push(branch);\n            parentEvent = childEvent;\n          } else {\n            break; // prevent infinite loop\n          }\n        }\n      } while (childEvent);\n      return fileHistory;\n    })();\n  }\n}\n//# sourceMappingURL=MSC3089Branch.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventType, MsgType, UNSTABLE_MSC3089_BRANCH, UNSTABLE_MSC3089_LEAF } from \"../@types/event.js\";\nimport { logger } from \"../logger.js\";\nimport { averageBetweenStrings, DEFAULT_ALPHABET, lexicographicCompare, nextString, prevString, simpleRetryOperation } from \"../utils.js\";\nimport { MSC3089Branch } from \"./MSC3089Branch.js\";\nimport { MatrixError } from \"../http-api/index.js\";\nimport { KnownMembership } from \"../@types/membership.js\";\n/**\n * The recommended defaults for a tree space's power levels. Note that this\n * is UNSTABLE and subject to breaking changes without notice.\n */\nexport var DEFAULT_TREE_POWER_LEVELS_TEMPLATE = {\n  // Owner\n  invite: 100,\n  kick: 100,\n  ban: 100,\n  // Editor\n  redact: 50,\n  state_default: 50,\n  events_default: 50,\n  // Viewer\n  users_default: 0,\n  // Mixed\n  events: {\n    [EventType.RoomPowerLevels]: 100,\n    [EventType.RoomHistoryVisibility]: 100,\n    [EventType.RoomTombstone]: 100,\n    [EventType.RoomEncryption]: 100,\n    [EventType.RoomName]: 50,\n    [EventType.RoomMessage]: 50,\n    [EventType.RoomMessageEncrypted]: 50,\n    [EventType.Sticker]: 50\n  },\n  users: {} // defined by calling code\n};\n\n/**\n * Ease-of-use representation for power levels represented as simple roles.\n * Note that this is UNSTABLE and subject to breaking changes without notice.\n */\nexport var TreePermissions = /*#__PURE__*/function (TreePermissions) {\n  TreePermissions[\"Viewer\"] = \"viewer\";\n  // Default\n  TreePermissions[\"Editor\"] = \"editor\";\n  // \"Moderator\" or ~PL50\n  TreePermissions[\"Owner\"] = \"owner\"; // \"Admin\" or PL100\n  return TreePermissions;\n}({});\n/**\n * Represents a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089)\n * file tree Space. Note that this is UNSTABLE and subject to breaking changes\n * without notice.\n */\nexport class MSC3089TreeSpace {\n  constructor(client, roomId) {\n    this.client = client;\n    this.roomId = roomId;\n    _defineProperty(this, \"room\", void 0);\n    this.room = this.client.getRoom(this.roomId);\n    if (!this.room) throw new Error(\"Unknown room\");\n  }\n\n  /**\n   * Syntactic sugar for room ID of the Space.\n   */\n  get id() {\n    return this.roomId;\n  }\n\n  /**\n   * Whether or not this is a top level space.\n   */\n  get isTopLevel() {\n    // XXX: This is absolutely not how you find out if the space is top level\n    // but is safe for a managed usecase like we offer in the SDK.\n    var parentEvents = this.room.currentState.getStateEvents(EventType.SpaceParent);\n    if (!(parentEvents !== null && parentEvents !== void 0 && parentEvents.length)) return true;\n    return parentEvents.every(e => {\n      var _e$getContent;\n      return !((_e$getContent = e.getContent()) !== null && _e$getContent !== void 0 && _e$getContent[\"via\"]);\n    });\n  }\n\n  /**\n   * Sets the name of the tree space.\n   * @param name - The new name for the space.\n   * @returns Promise which resolves when complete.\n   */\n  setName(name) {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      yield _this.client.sendStateEvent(_this.roomId, EventType.RoomName, {\n        name\n      }, \"\");\n    })();\n  }\n\n  /**\n   * Invites a user to the tree space. They will be given the default Viewer\n   * permission level unless specified elsewhere.\n   * @param userId - The user ID to invite.\n   * @param andSubspaces - True (default) to invite the user to all\n   * directories/subspaces too, recursively.\n   * @returns Promise which resolves when complete.\n   */\n  invite(userId) {\n    var _arguments = arguments,\n      _this2 = this;\n    return _asyncToGenerator(function* () {\n      var andSubspaces = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : true;\n      var promises = [_this2.retryInvite(userId)];\n      if (andSubspaces) {\n        promises.push(..._this2.getDirectories().map(d => d.invite(userId, andSubspaces)));\n      }\n      yield Promise.all(promises);\n    })();\n  }\n  retryInvite(userId) {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      yield simpleRetryOperation(() => _this3.client.invite(_this3.roomId, userId), e => {\n        // We don't want to retry permission errors forever...\n        if (e instanceof MatrixError && e.errcode === \"M_FORBIDDEN\") {\n          return false;\n        }\n        return true;\n      });\n    })();\n  }\n\n  /**\n   * Sets the permissions of a user to the given role. Note that if setting a user\n   * to Owner then they will NOT be able to be demoted. If the user does not have\n   * permission to change the power level of the target, an error will be thrown.\n   * @param userId - The user ID to change the role of.\n   * @param role - The role to assign.\n   * @returns Promise which resolves when complete.\n   */\n  setPermissions(userId, role) {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      var _pls$events;\n      var currentPls = _this4.room.currentState.getStateEvents(EventType.RoomPowerLevels, \"\");\n      if (Array.isArray(currentPls)) throw new Error(\"Unexpected return type for power levels\");\n      var pls = (currentPls === null || currentPls === void 0 ? void 0 : currentPls.getContent()) || {};\n      var viewLevel = pls[\"users_default\"] || 0;\n      var editLevel = pls[\"events_default\"] || 50;\n      var adminLevel = ((_pls$events = pls[\"events\"]) === null || _pls$events === void 0 ? void 0 : _pls$events[EventType.RoomPowerLevels]) || 100;\n      var users = pls[\"users\"] || {};\n      switch (role) {\n        case TreePermissions.Viewer:\n          users[userId] = viewLevel;\n          break;\n        case TreePermissions.Editor:\n          users[userId] = editLevel;\n          break;\n        case TreePermissions.Owner:\n          users[userId] = adminLevel;\n          break;\n        default:\n          throw new Error(\"Invalid role: \" + role);\n      }\n      pls[\"users\"] = users;\n      yield _this4.client.sendStateEvent(_this4.roomId, EventType.RoomPowerLevels, pls, \"\");\n    })();\n  }\n\n  /**\n   * Gets the current permissions of a user. Note that any users missing explicit permissions (or not\n   * in the space) will be considered Viewers. Appropriate membership checks need to be performed\n   * elsewhere.\n   * @param userId - The user ID to check permissions of.\n   * @returns The permissions for the user, defaulting to Viewer.\n   */\n  getPermissions(userId) {\n    var _pls$events2, _pls$users;\n    var currentPls = this.room.currentState.getStateEvents(EventType.RoomPowerLevels, \"\");\n    if (Array.isArray(currentPls)) throw new Error(\"Unexpected return type for power levels\");\n    var pls = (currentPls === null || currentPls === void 0 ? void 0 : currentPls.getContent()) || {};\n    var viewLevel = pls[\"users_default\"] || 0;\n    var editLevel = pls[\"events_default\"] || 50;\n    var adminLevel = ((_pls$events2 = pls[\"events\"]) === null || _pls$events2 === void 0 ? void 0 : _pls$events2[EventType.RoomPowerLevels]) || 100;\n    var userLevel = ((_pls$users = pls[\"users\"]) === null || _pls$users === void 0 ? void 0 : _pls$users[userId]) || viewLevel;\n    if (userLevel >= adminLevel) return TreePermissions.Owner;\n    if (userLevel >= editLevel) return TreePermissions.Editor;\n    return TreePermissions.Viewer;\n  }\n\n  /**\n   * Creates a directory under this tree space, represented as another tree space.\n   * @param name - The name for the directory.\n   * @returns Promise which resolves to the created directory.\n   */\n  createDirectory(name) {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      var directory = yield _this5.client.unstableCreateFileTree(name);\n      yield _this5.client.sendStateEvent(_this5.roomId, EventType.SpaceChild, {\n        via: [_this5.client.getDomain()]\n      }, directory.roomId);\n      yield _this5.client.sendStateEvent(directory.roomId, EventType.SpaceParent, {\n        via: [_this5.client.getDomain()]\n      }, _this5.roomId);\n      return directory;\n    })();\n  }\n\n  /**\n   * Gets a list of all known immediate subdirectories to this tree space.\n   * @returns The tree spaces (directories). May be empty, but not null.\n   */\n  getDirectories() {\n    var trees = [];\n    var children = this.room.currentState.getStateEvents(EventType.SpaceChild);\n    for (var child of children) {\n      try {\n        var stateKey = child.getStateKey();\n        if (stateKey) {\n          var tree = this.client.unstableGetFileTreeSpace(stateKey);\n          if (tree) trees.push(tree);\n        }\n      } catch (e) {\n        logger.warn(\"Unable to create tree space instance for listing. Are we joined?\", e);\n      }\n    }\n    return trees;\n  }\n\n  /**\n   * Gets a subdirectory of a given ID under this tree space. Note that this will not recurse\n   * into children and instead only look one level deep.\n   * @param roomId - The room ID (directory ID) to find.\n   * @returns The directory, or undefined if not found.\n   */\n  getDirectory(roomId) {\n    return this.getDirectories().find(r => r.roomId === roomId);\n  }\n\n  /**\n   * Deletes the tree, kicking all members and deleting **all subdirectories**.\n   * @returns Promise which resolves when complete.\n   */\n  delete() {\n    var _this6 = this;\n    return _asyncToGenerator(function* () {\n      var subdirectories = _this6.getDirectories();\n      for (var dir of subdirectories) {\n        yield dir.delete();\n      }\n      var kickMemberships = [KnownMembership.Invite, KnownMembership.Knock, KnownMembership.Join];\n      var members = _this6.room.currentState.getStateEvents(EventType.RoomMember);\n      for (var member of members) {\n        var isNotUs = member.getStateKey() !== _this6.client.getUserId();\n        if (isNotUs && kickMemberships.includes(member.getContent().membership)) {\n          var stateKey = member.getStateKey();\n          if (!stateKey) {\n            throw new Error(\"State key not found for branch\");\n          }\n          yield _this6.client.kick(_this6.roomId, stateKey, \"Room deleted\");\n        }\n      }\n      yield _this6.client.leave(_this6.roomId);\n    })();\n  }\n  getOrderedChildren(children) {\n    var ordered = children.map(c => ({\n      roomId: c.getStateKey(),\n      order: c.getContent()[\"order\"]\n    })).filter(c => c.roomId);\n    ordered.sort((a, b) => {\n      if (a.order && !b.order) {\n        return -1;\n      } else if (!a.order && b.order) {\n        return 1;\n      } else if (!a.order && !b.order) {\n        var _roomA$currentState$g, _roomA$currentState$g2, _roomB$currentState$g, _roomB$currentState$g2;\n        var roomA = this.client.getRoom(a.roomId);\n        var roomB = this.client.getRoom(b.roomId);\n        if (!roomA || !roomB) {\n          // just don't bother trying to do more partial sorting\n          return lexicographicCompare(a.roomId, b.roomId);\n        }\n        var createTsA = (_roomA$currentState$g = (_roomA$currentState$g2 = roomA.currentState.getStateEvents(EventType.RoomCreate, \"\")) === null || _roomA$currentState$g2 === void 0 ? void 0 : _roomA$currentState$g2.getTs()) !== null && _roomA$currentState$g !== void 0 ? _roomA$currentState$g : 0;\n        var createTsB = (_roomB$currentState$g = (_roomB$currentState$g2 = roomB.currentState.getStateEvents(EventType.RoomCreate, \"\")) === null || _roomB$currentState$g2 === void 0 ? void 0 : _roomB$currentState$g2.getTs()) !== null && _roomB$currentState$g !== void 0 ? _roomB$currentState$g : 0;\n        if (createTsA === createTsB) {\n          return lexicographicCompare(a.roomId, b.roomId);\n        }\n        return createTsA - createTsB;\n      } else {\n        // both not-null orders\n        return lexicographicCompare(a.order, b.order);\n      }\n    });\n    return ordered;\n  }\n  getParentRoom() {\n    var parents = this.room.currentState.getStateEvents(EventType.SpaceParent);\n    var parent = parents[0]; // XXX: Wild assumption\n    if (!parent) throw new Error(\"Expected to have a parent in a non-top level space\");\n\n    // XXX: We are assuming the parent is a valid tree space.\n    // We probably don't need to validate the parent room state for this usecase though.\n    var stateKey = parent.getStateKey();\n    if (!stateKey) throw new Error(\"No state key found for parent\");\n    var parentRoom = this.client.getRoom(stateKey);\n    if (!parentRoom) throw new Error(\"Unable to locate room for parent\");\n    return parentRoom;\n  }\n\n  /**\n   * Gets the current order index for this directory. Note that if this is the top level space\n   * then -1 will be returned.\n   * @returns The order index of this space.\n   */\n  getOrder() {\n    if (this.isTopLevel) return -1;\n    var parentRoom = this.getParentRoom();\n    var children = parentRoom.currentState.getStateEvents(EventType.SpaceChild);\n    var ordered = this.getOrderedChildren(children);\n    return ordered.findIndex(c => c.roomId === this.roomId);\n  }\n\n  /**\n   * Sets the order index for this directory within its parent. Note that if this is a top level\n   * space then an error will be thrown. -1 can be used to move the child to the start, and numbers\n   * larger than the number of children can be used to move the child to the end.\n   * @param index - The new order index for this space.\n   * @returns Promise which resolves when complete.\n   * @throws Throws if this is a top level space.\n   */\n  setOrder(index) {\n    var _this7 = this;\n    return _asyncToGenerator(function* () {\n      var _currentChild$getCont2;\n      if (_this7.isTopLevel) throw new Error(\"Cannot set order of top level spaces currently\");\n      var parentRoom = _this7.getParentRoom();\n      var children = parentRoom.currentState.getStateEvents(EventType.SpaceChild);\n      var ordered = _this7.getOrderedChildren(children);\n      index = Math.max(Math.min(index, ordered.length - 1), 0);\n      var currentIndex = _this7.getOrder();\n      var movingUp = currentIndex < index;\n      if (movingUp && index === ordered.length - 1) {\n        index--;\n      } else if (!movingUp && index === 0) {\n        index++;\n      }\n      var prev = ordered[movingUp ? index : index - 1];\n      var next = ordered[movingUp ? index + 1 : index];\n      var newOrder = DEFAULT_ALPHABET[0];\n      var ensureBeforeIsSane = false;\n      if (!prev) {\n        // Move to front\n        if (next !== null && next !== void 0 && next.order) {\n          newOrder = prevString(next.order);\n        }\n      } else if (index === ordered.length - 1) {\n        // Move to back\n        if (next !== null && next !== void 0 && next.order) {\n          newOrder = nextString(next.order);\n        }\n      } else {\n        // Move somewhere in the middle\n        var startOrder = prev === null || prev === void 0 ? void 0 : prev.order;\n        var endOrder = next === null || next === void 0 ? void 0 : next.order;\n        if (startOrder && endOrder) {\n          if (startOrder === endOrder) {\n            // Error case: just move +1 to break out of awful math\n            newOrder = nextString(startOrder);\n          } else {\n            newOrder = averageBetweenStrings(startOrder, endOrder);\n          }\n        } else {\n          if (startOrder) {\n            // We're at the end (endOrder is null, so no explicit order)\n            newOrder = nextString(startOrder);\n          } else if (endOrder) {\n            // We're at the start (startOrder is null, so nothing before us)\n            newOrder = prevString(endOrder);\n          } else {\n            // Both points are unknown. We're likely in a range where all the children\n            // don't have particular order values, so we may need to update them too.\n            // The other possibility is there's only us as a child, but we should have\n            // shown up in the other states.\n            ensureBeforeIsSane = true;\n          }\n        }\n      }\n      if (ensureBeforeIsSane) {\n        // We were asked by the order algorithm to prepare the moving space for a landing\n        // in the undefined order part of the order array, which means we need to update the\n        // spaces that come before it with a stable order value.\n        var lastOrder;\n        for (var i = 0; i <= index; i++) {\n          var target = ordered[i];\n          if (i === 0) {\n            lastOrder = target.order;\n          }\n          if (!target.order) {\n            var _currentChild$getCont;\n            // XXX: We should be creating gaps to avoid conflicts\n            lastOrder = lastOrder ? nextString(lastOrder) : DEFAULT_ALPHABET[0];\n            var _currentChild = parentRoom.currentState.getStateEvents(EventType.SpaceChild, target.roomId);\n            var _content = (_currentChild$getCont = _currentChild === null || _currentChild === void 0 ? void 0 : _currentChild.getContent()) !== null && _currentChild$getCont !== void 0 ? _currentChild$getCont : {\n              via: [_this7.client.getDomain()]\n            };\n            yield _this7.client.sendStateEvent(parentRoom.roomId, EventType.SpaceChild, _objectSpread(_objectSpread({}, _content), {}, {\n              order: lastOrder\n            }), target.roomId);\n          } else {\n            lastOrder = target.order;\n          }\n        }\n        if (lastOrder) {\n          newOrder = nextString(lastOrder);\n        }\n      }\n\n      // TODO: Deal with order conflicts by reordering\n\n      // Now we can finally update our own order state\n      var currentChild = parentRoom.currentState.getStateEvents(EventType.SpaceChild, _this7.roomId);\n      var content = (_currentChild$getCont2 = currentChild === null || currentChild === void 0 ? void 0 : currentChild.getContent()) !== null && _currentChild$getCont2 !== void 0 ? _currentChild$getCont2 : {\n        via: [_this7.client.getDomain()]\n      };\n      yield _this7.client.sendStateEvent(parentRoom.roomId, EventType.SpaceChild, _objectSpread(_objectSpread({}, content), {}, {\n        // TODO: Safely constrain to 50 character limit required by spaces.\n        order: newOrder\n      }), _this7.roomId);\n    })();\n  }\n\n  /**\n   * Creates (uploads) a new file to this tree. The file must have already been encrypted for the room.\n   * The file contents are in a type that is compatible with MatrixClient.uploadContent().\n   * @param name - The name of the file.\n   * @param encryptedContents - The encrypted contents.\n   * @param info - The encrypted file information.\n   * @param additionalContent - Optional event content fields to include in the message.\n   * @returns Promise which resolves to the file event's sent response.\n   */\n  createFile(name, encryptedContents, info, additionalContent) {\n    var _this8 = this;\n    return _asyncToGenerator(function* () {\n      var {\n        content_uri: mxc\n      } = yield _this8.client.uploadContent(encryptedContents, {\n        includeFilename: false\n      });\n      info.url = mxc;\n      var fileContent = {\n        msgtype: MsgType.File,\n        body: name,\n        url: mxc,\n        file: info\n      };\n      additionalContent = additionalContent !== null && additionalContent !== void 0 ? additionalContent : {};\n      if (additionalContent[\"m.new_content\"]) {\n        // We do the right thing according to the spec, but due to how relations are\n        // handled we also end up duplicating this information to the regular `content`\n        // as well.\n        additionalContent[\"m.new_content\"] = fileContent;\n      }\n      var res = yield _this8.client.sendMessage(_this8.roomId, _objectSpread(_objectSpread(_objectSpread({}, additionalContent), fileContent), {}, {\n        [UNSTABLE_MSC3089_LEAF.name]: {}\n      }));\n      yield _this8.client.sendStateEvent(_this8.roomId, UNSTABLE_MSC3089_BRANCH.name, {\n        active: true,\n        name: name\n      }, res[\"event_id\"]);\n      return res;\n    })();\n  }\n\n  /**\n   * Retrieves a file from the tree.\n   * @param fileEventId - The event ID of the file.\n   * @returns The file, or null if not found.\n   */\n  getFile(fileEventId) {\n    var branch = this.room.currentState.getStateEvents(UNSTABLE_MSC3089_BRANCH.name, fileEventId);\n    return branch ? new MSC3089Branch(this.client, branch, this) : null;\n  }\n\n  /**\n   * Gets an array of all known files for the tree.\n   * @returns The known files. May be empty, but not null.\n   */\n  listFiles() {\n    return this.listAllFiles().filter(b => b.isActive);\n  }\n\n  /**\n   * Gets an array of all known files for the tree, including inactive/invalid ones.\n   * @returns The known files. May be empty, but not null.\n   */\n  listAllFiles() {\n    var _this$room$currentSta;\n    var branches = (_this$room$currentSta = this.room.currentState.getStateEvents(UNSTABLE_MSC3089_BRANCH.name)) !== null && _this$room$currentSta !== void 0 ? _this$room$currentSta : [];\n    return branches.map(e => new MSC3089Branch(this.client, e, this));\n  }\n}\n//# sourceMappingURL=MSC3089TreeSpace.js.map","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n// Types relating to the /search API\n/* eslint-disable camelcase */\nvar GroupKey = /*#__PURE__*/function (GroupKey) {\n  GroupKey[\"RoomId\"] = \"room_id\";\n  GroupKey[\"Sender\"] = \"sender\";\n  return GroupKey;\n}(GroupKey || {});\nexport var SearchOrderBy = /*#__PURE__*/function (SearchOrderBy) {\n  SearchOrderBy[\"Recent\"] = \"recent\";\n  SearchOrderBy[\"Rank\"] = \"rank\";\n  return SearchOrderBy;\n}({});\n\n/* eslint-enable camelcase */\n//# sourceMappingURL=search.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\nCopyright 2019, 2020 The Matrix.org Foundation C.I.C.\nCopyright 2021 - 2022 Šimon Brandner <simon.bra.ag@gmail.com>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.js\";\nimport { GroupCallType, GroupCallState } from \"../webrtc/groupCall.js\";\nimport { logger } from \"../logger.js\";\nexport var MediaHandlerEvent = /*#__PURE__*/function (MediaHandlerEvent) {\n  MediaHandlerEvent[\"LocalStreamsChanged\"] = \"local_streams_changed\";\n  return MediaHandlerEvent;\n}({});\nexport class MediaHandler extends TypedEventEmitter {\n  constructor(client) {\n    super();\n    this.client = client;\n    _defineProperty(this, \"audioInput\", void 0);\n    _defineProperty(this, \"audioSettings\", void 0);\n    _defineProperty(this, \"videoInput\", void 0);\n    _defineProperty(this, \"localUserMediaStream\", void 0);\n    _defineProperty(this, \"userMediaStreams\", []);\n    _defineProperty(this, \"screensharingStreams\", []);\n    // Promise chain to serialise calls to getMediaStream\n    _defineProperty(this, \"getMediaStreamPromise\", void 0);\n  }\n  restoreMediaSettings(audioInput, videoInput) {\n    this.audioInput = audioInput;\n    this.videoInput = videoInput;\n  }\n\n  /**\n   * Set an audio input device to use for MatrixCalls\n   * @param deviceId - the identifier for the device\n   * undefined treated as unset\n   */\n  setAudioInput(deviceId) {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      logger.info(\"MediaHandler setAudioInput() running (deviceId=\".concat(deviceId, \")\"));\n      if (_this.audioInput === deviceId) return;\n      _this.audioInput = deviceId;\n      yield _this.updateLocalUsermediaStreams();\n    })();\n  }\n\n  /**\n   * Set audio settings for MatrixCalls\n   * @param opts - audio options to set\n   */\n  setAudioSettings(opts) {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      logger.info(\"MediaHandler setAudioSettings() running (opts=\".concat(JSON.stringify(opts), \")\"));\n      _this2.audioSettings = Object.assign({}, opts);\n      yield _this2.updateLocalUsermediaStreams();\n    })();\n  }\n\n  /**\n   * Set a video input device to use for MatrixCalls\n   * @param deviceId - the identifier for the device\n   * undefined treated as unset\n   */\n  setVideoInput(deviceId) {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      logger.info(\"MediaHandler setVideoInput() running (deviceId=\".concat(deviceId, \")\"));\n      if (_this3.videoInput === deviceId) return;\n      _this3.videoInput = deviceId;\n      yield _this3.updateLocalUsermediaStreams();\n    })();\n  }\n\n  /**\n   * Set media input devices to use for MatrixCalls\n   * @param audioInput - the identifier for the audio device\n   * @param videoInput - the identifier for the video device\n   * undefined treated as unset\n   */\n  setMediaInputs(audioInput, videoInput) {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      logger.log(\"MediaHandler setMediaInputs() running (audioInput: \".concat(audioInput, \" videoInput: \").concat(videoInput, \")\"));\n      _this4.audioInput = audioInput;\n      _this4.videoInput = videoInput;\n      yield _this4.updateLocalUsermediaStreams();\n    })();\n  }\n\n  /*\n   * Requests new usermedia streams and replace the old ones\n   */\n  updateLocalUsermediaStreams() {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      if (_this5.userMediaStreams.length === 0) return;\n      var callMediaStreamParams = new Map();\n      for (var call of _this5.client.callEventHandler.calls.values()) {\n        callMediaStreamParams.set(call.callId, {\n          audio: call.hasLocalUserMediaAudioTrack,\n          video: call.hasLocalUserMediaVideoTrack\n        });\n      }\n      for (var stream of _this5.userMediaStreams) {\n        logger.log(\"MediaHandler updateLocalUsermediaStreams() stopping all tracks (streamId=\".concat(stream.id, \")\"));\n        for (var track of stream.getTracks()) {\n          track.stop();\n        }\n      }\n      _this5.userMediaStreams = [];\n      _this5.localUserMediaStream = undefined;\n      for (var _call of _this5.client.callEventHandler.calls.values()) {\n        if (_call.callHasEnded() || !callMediaStreamParams.has(_call.callId)) {\n          continue;\n        }\n        var {\n          audio,\n          video\n        } = callMediaStreamParams.get(_call.callId);\n        logger.log(\"MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (callId=\".concat(_call.callId, \")\"));\n        var _stream = yield _this5.getUserMediaStream(audio, video);\n        if (_call.callHasEnded()) {\n          continue;\n        }\n        yield _call.updateLocalUsermediaStream(_stream);\n      }\n      for (var groupCall of _this5.client.groupCallEventHandler.groupCalls.values()) {\n        if (!groupCall.localCallFeed) {\n          continue;\n        }\n        logger.log(\"MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (groupCallId=\".concat(groupCall.groupCallId, \")\"));\n        var _stream2 = yield _this5.getUserMediaStream(true, groupCall.type === GroupCallType.Video);\n        if (groupCall.state === GroupCallState.Ended) {\n          continue;\n        }\n        yield groupCall.updateLocalUsermediaStream(_stream2);\n      }\n      _this5.emit(MediaHandlerEvent.LocalStreamsChanged);\n    })();\n  }\n  hasAudioDevice() {\n    return _asyncToGenerator(function* () {\n      try {\n        var devices = yield navigator.mediaDevices.enumerateDevices();\n        return devices.filter(device => device.kind === \"audioinput\").length > 0;\n      } catch (err) {\n        logger.log(\"MediaHandler hasAudioDevice() calling navigator.mediaDevices.enumerateDevices with error\", err);\n        return false;\n      }\n    })();\n  }\n  hasVideoDevice() {\n    return _asyncToGenerator(function* () {\n      try {\n        var devices = yield navigator.mediaDevices.enumerateDevices();\n        return devices.filter(device => device.kind === \"videoinput\").length > 0;\n      } catch (err) {\n        logger.log(\"MediaHandler hasVideoDevice() calling navigator.mediaDevices.enumerateDevices with error\", err);\n        return false;\n      }\n    })();\n  }\n\n  /**\n   * @param audio - should have an audio track\n   * @param video - should have a video track\n   * @param reusable - is allowed to be reused by the MediaHandler\n   * @returns based on passed parameters\n   */\n  getUserMediaStream(audio, video) {\n    var _arguments = arguments,\n      _this6 = this;\n    return _asyncToGenerator(function* () {\n      var reusable = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : true;\n      // Serialise calls, othertwise we can't sensibly re-use the stream\n      if (_this6.getMediaStreamPromise) {\n        _this6.getMediaStreamPromise = _this6.getMediaStreamPromise.then(() => {\n          return _this6.getUserMediaStreamInternal(audio, video, reusable);\n        });\n      } else {\n        _this6.getMediaStreamPromise = _this6.getUserMediaStreamInternal(audio, video, reusable);\n      }\n      return _this6.getMediaStreamPromise;\n    })();\n  }\n  getUserMediaStreamInternal(audio, video, reusable) {\n    var _this7 = this;\n    return _asyncToGenerator(function* () {\n      var shouldRequestAudio = audio && (yield _this7.hasAudioDevice());\n      var shouldRequestVideo = video && (yield _this7.hasVideoDevice());\n      var stream;\n      var canReuseStream = true;\n      if (_this7.localUserMediaStream) {\n        var _this7$localUserMedia, _this7$localUserMedia2;\n        // This figures out if we can reuse the current localUsermediaStream\n        // based on whether or not the \"mute state\" (presence of tracks of a\n        // given kind) matches what is being requested\n        if (shouldRequestAudio !== _this7.localUserMediaStream.getAudioTracks().length > 0) {\n          canReuseStream = false;\n        }\n        if (shouldRequestVideo !== _this7.localUserMediaStream.getVideoTracks().length > 0) {\n          canReuseStream = false;\n        }\n\n        // This code checks that the device ID is the same as the localUserMediaStream stream, but we update\n        // the localUserMediaStream whenever the device ID changes (apart from when restoring) so it's not\n        // clear why this would ever be different, unless there's a race.\n        if (shouldRequestAudio && ((_this7$localUserMedia = _this7.localUserMediaStream.getAudioTracks()[0]) === null || _this7$localUserMedia === void 0 || (_this7$localUserMedia = _this7$localUserMedia.getSettings()) === null || _this7$localUserMedia === void 0 ? void 0 : _this7$localUserMedia.deviceId) !== _this7.audioInput) {\n          canReuseStream = false;\n        }\n        if (shouldRequestVideo && ((_this7$localUserMedia2 = _this7.localUserMediaStream.getVideoTracks()[0]) === null || _this7$localUserMedia2 === void 0 || (_this7$localUserMedia2 = _this7$localUserMedia2.getSettings()) === null || _this7$localUserMedia2 === void 0 ? void 0 : _this7$localUserMedia2.deviceId) !== _this7.videoInput) {\n          canReuseStream = false;\n        }\n      } else {\n        canReuseStream = false;\n      }\n      if (!canReuseStream) {\n        var constraints;\n        try {\n          // Not specifying exact for deviceId means switching devices does not always work,\n          // try with exact and fallback to ideal if it fails\n          constraints = _this7.getUserMediaContraints(shouldRequestAudio, shouldRequestVideo, true);\n          stream = yield navigator.mediaDevices.getUserMedia(constraints);\n        } catch (e) {\n          logger.warn(\"MediaHandler getUserMediaStreamInternal() error (e=\".concat(e, \"), retrying without exact deviceId\"));\n          constraints = _this7.getUserMediaContraints(shouldRequestAudio, shouldRequestVideo, false);\n          stream = yield navigator.mediaDevices.getUserMedia(constraints);\n        }\n        logger.log(\"MediaHandler getUserMediaStreamInternal() calling getUserMediaStream (streamId=\".concat(stream.id, \", shouldRequestAudio=\").concat(shouldRequestAudio, \", shouldRequestVideo=\").concat(shouldRequestVideo, \", constraints=\").concat(JSON.stringify(constraints), \")\"));\n        for (var track of stream.getTracks()) {\n          var settings = track.getSettings();\n          if (track.kind === \"audio\") {\n            _this7.audioInput = settings.deviceId;\n          } else if (track.kind === \"video\") {\n            _this7.videoInput = settings.deviceId;\n          }\n        }\n        if (reusable) {\n          _this7.localUserMediaStream = stream;\n        }\n      } else {\n        var _this7$localUserMedia3;\n        stream = _this7.localUserMediaStream.clone();\n        logger.log(\"MediaHandler getUserMediaStreamInternal() cloning (oldStreamId=\".concat((_this7$localUserMedia3 = _this7.localUserMediaStream) === null || _this7$localUserMedia3 === void 0 ? void 0 : _this7$localUserMedia3.id, \" newStreamId=\").concat(stream.id, \" shouldRequestAudio=\").concat(shouldRequestAudio, \" shouldRequestVideo=\").concat(shouldRequestVideo, \")\"));\n        if (!shouldRequestAudio) {\n          for (var _track of stream.getAudioTracks()) {\n            stream.removeTrack(_track);\n          }\n        }\n        if (!shouldRequestVideo) {\n          for (var _track2 of stream.getVideoTracks()) {\n            stream.removeTrack(_track2);\n          }\n        }\n      }\n      if (reusable) {\n        _this7.userMediaStreams.push(stream);\n      }\n      _this7.emit(MediaHandlerEvent.LocalStreamsChanged);\n      return stream;\n    })();\n  }\n\n  /**\n   * Stops all tracks on the provided usermedia stream\n   */\n  stopUserMediaStream(mediaStream) {\n    logger.log(\"MediaHandler stopUserMediaStream() stopping (streamId=\".concat(mediaStream.id, \")\"));\n    for (var track of mediaStream.getTracks()) {\n      track.stop();\n    }\n    var index = this.userMediaStreams.indexOf(mediaStream);\n    if (index !== -1) {\n      logger.debug(\"MediaHandler stopUserMediaStream() splicing usermedia stream out stream array (streamId=\".concat(mediaStream.id, \")\"), mediaStream.id);\n      this.userMediaStreams.splice(index, 1);\n    }\n    this.emit(MediaHandlerEvent.LocalStreamsChanged);\n    if (this.localUserMediaStream === mediaStream) {\n      // if we have this stream cahced, remove it, because we've stopped it\n      this.localUserMediaStream = undefined;\n    } else {\n      // If it's not the same stream. remove any tracks from the cached stream that\n      // we have just stopped, and if we do stop any, call the same method on the\n      // cached stream too in order to stop all its tracks (in case they are different)\n      // and un-cache it.\n      for (var _track3 of mediaStream.getTracks()) {\n        var _this$localUserMediaS;\n        if ((_this$localUserMediaS = this.localUserMediaStream) !== null && _this$localUserMediaS !== void 0 && _this$localUserMediaS.getTrackById(_track3.id)) {\n          this.stopUserMediaStream(this.localUserMediaStream);\n          break;\n        }\n      }\n    }\n  }\n\n  /**\n   * @param opts - screensharing stream options\n   * @param reusable - is allowed to be reused by the MediaHandler\n   * @returns based on passed parameters\n   */\n  getScreensharingStream() {\n    var _arguments2 = arguments,\n      _this8 = this;\n    return _asyncToGenerator(function* () {\n      var opts = _arguments2.length > 0 && _arguments2[0] !== undefined ? _arguments2[0] : {};\n      var reusable = _arguments2.length > 1 && _arguments2[1] !== undefined ? _arguments2[1] : true;\n      var stream;\n      if (_this8.screensharingStreams.length === 0) {\n        var screenshareConstraints = _this8.getScreenshareContraints(opts);\n        if (opts.desktopCapturerSourceId) {\n          // We are using Electron\n          logger.debug(\"MediaHandler getScreensharingStream() calling getUserMedia() (opts=\".concat(JSON.stringify(opts), \")\"));\n          stream = yield navigator.mediaDevices.getUserMedia(screenshareConstraints);\n        } else {\n          // We are not using Electron\n          logger.debug(\"MediaHandler getScreensharingStream() calling getDisplayMedia() (opts=\".concat(JSON.stringify(opts), \")\"));\n          stream = yield navigator.mediaDevices.getDisplayMedia(screenshareConstraints);\n        }\n      } else {\n        var matchingStream = _this8.screensharingStreams[_this8.screensharingStreams.length - 1];\n        logger.log(\"MediaHandler getScreensharingStream() cloning (streamId=\".concat(matchingStream.id, \")\"));\n        stream = matchingStream.clone();\n      }\n      if (reusable) {\n        _this8.screensharingStreams.push(stream);\n      }\n      _this8.emit(MediaHandlerEvent.LocalStreamsChanged);\n      return stream;\n    })();\n  }\n\n  /**\n   * Stops all tracks on the provided screensharing stream\n   */\n  stopScreensharingStream(mediaStream) {\n    logger.debug(\"MediaHandler stopScreensharingStream() stopping stream (streamId=\".concat(mediaStream.id, \")\"));\n    for (var track of mediaStream.getTracks()) {\n      track.stop();\n    }\n    var index = this.screensharingStreams.indexOf(mediaStream);\n    if (index !== -1) {\n      logger.debug(\"MediaHandler stopScreensharingStream() splicing stream out (streamId=\".concat(mediaStream.id, \")\"));\n      this.screensharingStreams.splice(index, 1);\n    }\n    this.emit(MediaHandlerEvent.LocalStreamsChanged);\n  }\n\n  /**\n   * Stops all local media tracks\n   */\n  stopAllStreams() {\n    for (var stream of this.userMediaStreams) {\n      logger.log(\"MediaHandler stopAllStreams() stopping (streamId=\".concat(stream.id, \")\"));\n      for (var track of stream.getTracks()) {\n        track.stop();\n      }\n    }\n    for (var _stream3 of this.screensharingStreams) {\n      for (var _track4 of _stream3.getTracks()) {\n        _track4.stop();\n      }\n    }\n    this.userMediaStreams = [];\n    this.screensharingStreams = [];\n    this.localUserMediaStream = undefined;\n    this.emit(MediaHandlerEvent.LocalStreamsChanged);\n  }\n  getUserMediaContraints(audio, video, exactDeviceId) {\n    var isWebkit = !!navigator.webkitGetUserMedia;\n    var deviceIdKey = exactDeviceId ? \"exact\" : \"ideal\";\n    var audioConstraints = {};\n    if (this.audioInput) {\n      audioConstraints.deviceId = {\n        [deviceIdKey]: this.audioInput\n      };\n    }\n    if (this.audioSettings) {\n      audioConstraints.autoGainControl = {\n        ideal: this.audioSettings.autoGainControl\n      };\n      audioConstraints.echoCancellation = {\n        ideal: this.audioSettings.echoCancellation\n      };\n      audioConstraints.noiseSuppression = {\n        ideal: this.audioSettings.noiseSuppression\n      };\n    }\n    var videoConstraints = {\n      /* We want 640x360.  Chrome will give it only if we ask exactly,\n         FF refuses entirely if we ask exactly, so have to ask for ideal\n         instead\n         XXX: Is this still true?\n       */\n      width: isWebkit ? {\n        exact: 640\n      } : {\n        ideal: 640\n      },\n      height: isWebkit ? {\n        exact: 360\n      } : {\n        ideal: 360\n      }\n    };\n    if (this.videoInput) {\n      videoConstraints.deviceId = {\n        [deviceIdKey]: this.videoInput\n      };\n    }\n    return {\n      audio: audio ? audioConstraints : false,\n      video: video ? videoConstraints : false\n    };\n  }\n  getScreenshareContraints(opts) {\n    var {\n      desktopCapturerSourceId,\n      audio\n    } = opts;\n    if (desktopCapturerSourceId) {\n      return {\n        audio: audio !== null && audio !== void 0 ? audio : false,\n        video: {\n          mandatory: {\n            chromeMediaSource: \"desktop\",\n            chromeMediaSourceId: desktopCapturerSourceId\n          }\n        }\n      };\n    } else {\n      return {\n        audio: audio !== null && audio !== void 0 ? audio : false,\n        video: true\n      };\n    }\n  }\n}\n//# sourceMappingURL=mediaHandler.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2022-2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"./logger.js\";\nimport { TypedEventEmitter } from \"./models/typed-event-emitter.js\";\nimport { sleep } from \"./utils.js\";\n// /sync requests allow you to set a timeout= but the request may continue\n// beyond that and wedge forever, so we need to track how long we are willing\n// to keep open the connection. This constant is *ADDED* to the timeout= value\n// to determine the max time we're willing to wait.\nvar BUFFER_PERIOD_MS = 10 * 1000;\nexport var MSC3575_WILDCARD = \"*\";\nexport var MSC3575_STATE_KEY_ME = \"$ME\";\nexport var MSC3575_STATE_KEY_LAZY = \"$LAZY\";\n\n/**\n * Represents a subscription to a room or set of rooms. Controls which events are returned.\n */\n\n/**\n * Controls which rooms are returned in a given list.\n */\n\n/**\n * Represents a list subscription.\n */\n\n/**\n * A complete Sliding Sync request.\n */\n\n/**\n * New format of hero introduced in MSC4186 with display name and avatar URL\n * in addition to just user_id (as it is on the wire, with underscores)\n * as opposed to Hero in room-summary.ts which has fields in camelCase\n * (and also a flag to note what format the hero came from).\n */\n\n/**\n * A complete Sliding Sync response\n */\n\nexport var SlidingSyncState = /*#__PURE__*/function (SlidingSyncState) {\n  /**\n   * Fired by SlidingSyncEvent.Lifecycle event immediately before processing the response.\n   */\n  SlidingSyncState[\"RequestFinished\"] = \"FINISHED\";\n  /**\n   * Fired by SlidingSyncEvent.Lifecycle event immediately after all room data listeners have been\n   * invoked, but before list listeners.\n   */\n  SlidingSyncState[\"Complete\"] = \"COMPLETE\";\n  return SlidingSyncState;\n}({});\n\n/**\n * Internal Class. SlidingList represents a single list in sliding sync. The list can have filters,\n * multiple sliding windows, and maintains the index-\\>room_id mapping.\n */\nclass SlidingList {\n  /**\n   * Construct a new sliding list.\n   * @param list - The range, sort and filter values to use for this list.\n   */\n  constructor(list) {\n    _defineProperty(this, \"list\", void 0);\n    _defineProperty(this, \"isModified\", void 0);\n    // returned data\n    _defineProperty(this, \"joinedCount\", 0);\n    this.replaceList(list);\n  }\n\n  /**\n   * Mark this list as modified or not. Modified lists will return sticky params with calls to getList.\n   * This is useful for the first time the list is sent, or if the list has changed in some way.\n   * @param modified - True to mark this list as modified so all sticky parameters will be re-sent.\n   */\n  setModified(modified) {\n    this.isModified = modified;\n  }\n\n  /**\n   * Update the list range for this list. Does not affect modified status as list ranges are non-sticky.\n   * @param newRanges - The new ranges for the list\n   */\n  updateListRange(newRanges) {\n    this.list.ranges = JSON.parse(JSON.stringify(newRanges));\n  }\n\n  /**\n   * Replace list parameters. All fields will be replaced with the new list parameters.\n   * @param list - The new list parameters\n   */\n  replaceList(list) {\n    var _list$filters, _list$ranges;\n    list.filters = (_list$filters = list.filters) !== null && _list$filters !== void 0 ? _list$filters : {};\n    list.ranges = (_list$ranges = list.ranges) !== null && _list$ranges !== void 0 ? _list$ranges : [];\n    this.list = JSON.parse(JSON.stringify(list));\n    this.isModified = true;\n\n    // reset values as the join count may be very different (if filters changed) including the rooms\n    // (e.g. sort orders or sliding window ranges changed)\n\n    // the total number of joined rooms according to the server, always >= len(roomIndexToRoomId)\n    this.joinedCount = 0;\n  }\n\n  /**\n   * Return a copy of the list suitable for a request body.\n   * @param forceIncludeAllParams - True to forcibly include all params even if the list\n   * hasn't been modified. Callers may want to do this if they are modifying the list prior to calling\n   * updateList.\n   */\n  getList(forceIncludeAllParams) {\n    var list = {\n      ranges: JSON.parse(JSON.stringify(this.list.ranges))\n    };\n    if (this.isModified || forceIncludeAllParams) {\n      list = JSON.parse(JSON.stringify(this.list));\n    }\n    return list;\n  }\n}\n\n/**\n * When onResponse extensions should be invoked: before or after processing the main response.\n */\nexport var ExtensionState = /*#__PURE__*/function (ExtensionState) {\n  // Call onResponse before processing the response body. This is useful when your extension is\n  // preparing the ground for the response body e.g. processing to-device messages before the\n  // encrypted event arrives.\n  ExtensionState[\"PreProcess\"] = \"ExtState.PreProcess\";\n  // Call onResponse after processing the response body. This is useful when your extension is\n  // decorating data from the client, and you rely on MatrixClient.getRoom returning the Room object\n  // e.g. room account data.\n  ExtensionState[\"PostProcess\"] = \"ExtState.PostProcess\";\n  return ExtensionState;\n}({});\n\n/**\n * An interface that must be satisfied to register extensions\n */\n\n/**\n * Events which can be fired by the SlidingSync class. These are designed to provide different levels\n * of information when processing sync responses.\n *  - RoomData: concerns rooms, useful for SlidingSyncSdk to update its knowledge of rooms.\n *  - Lifecycle: concerns callbacks at various well-defined points in the sync process.\n * Specifically, the order of event invocation is:\n *  - Lifecycle (state=RequestFinished)\n *  - RoomData (N times)\n *  - Lifecycle (state=Complete)\n */\nexport var SlidingSyncEvent = /*#__PURE__*/function (SlidingSyncEvent) {\n  /**\n   * This event fires when there are updates for a room. Fired as and when rooms are encountered\n   * in the response.\n   */\n  SlidingSyncEvent[\"RoomData\"] = \"SlidingSync.RoomData\";\n  /**\n   * This event fires at various points in the /sync loop lifecycle.\n   *  - SlidingSyncState.RequestFinished: Fires after we receive a valid response but before the\n   * response has been processed. Perform any pre-process steps here. If there was a problem syncing,\n   * `err` will be set (e.g network errors).\n   *  - SlidingSyncState.Complete: Fires after the response has been processed.\n   */\n  SlidingSyncEvent[\"Lifecycle\"] = \"SlidingSync.Lifecycle\";\n  return SlidingSyncEvent;\n}({});\n/**\n * SlidingSync is a high-level data structure which controls the majority of sliding sync.\n * It has no hooks into JS SDK except for needing a MatrixClient to perform the HTTP request.\n * This means this class (and everything it uses) can be used in isolation from JS SDK if needed.\n * To hook this up with the JS SDK, you need to use SlidingSyncSdk.\n */\nexport class SlidingSync extends TypedEventEmitter {\n  /**\n   * Create a new sliding sync instance\n   * @param proxyBaseUrl - The base URL of the sliding sync proxy\n   * @param lists - The lists to use for sliding sync.\n   * @param roomSubscriptionInfo - The params to use for room subscriptions.\n   * @param client - The client to use for /sync calls.\n   * @param timeoutMS - The number of milliseconds to wait for a response.\n   */\n  constructor(proxyBaseUrl, lists, roomSubscriptionInfo, client, timeoutMS) {\n    super();\n    this.proxyBaseUrl = proxyBaseUrl;\n    this.roomSubscriptionInfo = roomSubscriptionInfo;\n    this.client = client;\n    this.timeoutMS = timeoutMS;\n    _defineProperty(this, \"lists\", void 0);\n    _defineProperty(this, \"listModifiedCount\", 0);\n    _defineProperty(this, \"terminated\", false);\n    // flag set when resend() is called because we cannot rely on detecting AbortError in JS SDK :(\n    _defineProperty(this, \"needsResend\", false);\n    // map of extension name to req/resp handler\n    _defineProperty(this, \"extensions\", {});\n    _defineProperty(this, \"desiredRoomSubscriptions\", new Set());\n    // the *desired* room subscriptions\n    _defineProperty(this, \"confirmedRoomSubscriptions\", new Set());\n    // map of custom subscription name to the subscription\n    _defineProperty(this, \"customSubscriptions\", new Map());\n    // map of room ID to custom subscription name\n    _defineProperty(this, \"roomIdToCustomSubscription\", new Map());\n    _defineProperty(this, \"pendingReq\", void 0);\n    _defineProperty(this, \"abortController\", void 0);\n    this.lists = new Map();\n    lists.forEach((list, key) => {\n      this.lists.set(key, new SlidingList(list));\n    });\n  }\n\n  /**\n   * Add a custom room subscription, referred to by an arbitrary name. If a subscription with this\n   * name already exists, it is replaced. No requests are sent by calling this method.\n   * @param name - The name of the subscription. Only used to reference this subscription in\n   * useCustomSubscription.\n   * @param sub - The subscription information.\n   */\n  addCustomSubscription(name, sub) {\n    if (this.customSubscriptions.has(name)) {\n      logger.warn(\"addCustomSubscription: \".concat(name, \" already exists as a custom subscription, ignoring.\"));\n      return;\n    }\n    this.customSubscriptions.set(name, sub);\n  }\n\n  /**\n   * Use a custom subscription previously added via addCustomSubscription. No requests are sent\n   * by calling this method. Use modifyRoomSubscriptions to resend subscription information.\n   * @param roomId - The room to use the subscription in.\n   * @param name - The name of the subscription. If this name is unknown, the default subscription\n   * will be used.\n   */\n  useCustomSubscription(roomId, name) {\n    // We already know about this custom subscription, as it is immutable,\n    // we don't need to unconfirm the subscription.\n    if (this.roomIdToCustomSubscription.get(roomId) === name) {\n      return;\n    }\n    this.roomIdToCustomSubscription.set(roomId, name);\n    // unconfirm this subscription so a resend() will send it up afresh.\n    this.confirmedRoomSubscriptions.delete(roomId);\n  }\n\n  /**\n   * Get the room index data for a list.\n   * @param key - The list key\n   * @returns The list data which contains the rooms in this list\n   */\n  getListData(key) {\n    var data = this.lists.get(key);\n    if (!data) {\n      return null;\n    }\n    return {\n      joinedCount: data.joinedCount\n    };\n  }\n\n  /**\n   * Get the full request list parameters for a list index. This function is provided for callers to use\n   * in conjunction with setList to update fields on an existing list.\n   * @param key - The list key to get the params for.\n   * @returns A copy of the list params or undefined.\n   */\n  getListParams(key) {\n    var params = this.lists.get(key);\n    if (!params) {\n      return null;\n    }\n    return params.getList(true);\n  }\n\n  /**\n   * Set new ranges for an existing list. Calling this function when _only_ the ranges have changed\n   * is more efficient than calling setList(index,list) as this function won't resend sticky params,\n   * whereas setList always will.\n   * @param key - The list key to modify\n   * @param ranges - The new ranges to apply.\n   * @returns A promise which resolves to the transaction ID when it has been received down sync\n   * (or rejects with the transaction ID if the action was not applied e.g the request was cancelled\n   * immediately after sending, in which case the action will be applied in the subsequent request)\n   */\n  setListRanges(key, ranges) {\n    var list = this.lists.get(key);\n    if (!list) {\n      throw new Error(\"no list with key \" + key);\n    }\n    list.updateListRange(ranges);\n    this.resend();\n  }\n\n  /**\n   * Add or replace a list. Calling this function will interrupt the /sync request to resend new\n   * lists.\n   * @param key - The key to modify\n   * @param list - The new list parameters.\n   * @returns A promise which resolves to the transaction ID when it has been received down sync\n   * (or rejects with the transaction ID if the action was not applied e.g the request was cancelled\n   * immediately after sending, in which case the action will be applied in the subsequent request)\n   */\n  setList(key, list) {\n    var existingList = this.lists.get(key);\n    if (existingList) {\n      existingList.replaceList(list);\n      this.lists.set(key, existingList);\n    } else {\n      this.lists.set(key, new SlidingList(list));\n    }\n    this.listModifiedCount += 1;\n    this.resend();\n  }\n\n  /**\n   * Get the room subscriptions for the sync API.\n   * @returns A copy of the desired room subscriptions.\n   */\n  getRoomSubscriptions() {\n    return new Set(Array.from(this.desiredRoomSubscriptions));\n  }\n\n  /**\n   * Modify the room subscriptions for the sync API. Calling this function will interrupt the\n   * /sync request to resend new subscriptions. If the /sync stream has not started, this will\n   * prepare the room subscriptions for when start() is called.\n   * @param s - The new desired room subscriptions.\n   */\n  modifyRoomSubscriptions(s) {\n    this.desiredRoomSubscriptions = s;\n    this.resend();\n  }\n\n  /**\n   * Modify which events to retrieve for room subscriptions. Invalidates all room subscriptions\n   * such that they will be sent up afresh.\n   * @param rs - The new room subscription fields to fetch.\n   */\n  modifyRoomSubscriptionInfo(rs) {\n    this.roomSubscriptionInfo = rs;\n    this.confirmedRoomSubscriptions = new Set();\n    this.resend();\n  }\n\n  /**\n   * Register an extension to send with the /sync request.\n   * @param ext - The extension to register.\n   */\n  registerExtension(ext) {\n    if (this.extensions[ext.name()]) {\n      throw new Error(\"registerExtension: \".concat(ext.name(), \" already exists as an extension\"));\n    }\n    this.extensions[ext.name()] = ext;\n  }\n  getExtensionRequest(isInitial) {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      var ext = {};\n      for (var extName in _this.extensions) {\n        ext[extName] = yield _this.extensions[extName].onRequest(isInitial);\n      }\n      return ext;\n    })();\n  }\n  onPreExtensionsResponse(ext) {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      yield Promise.all(Object.keys(ext).map(/*#__PURE__*/function () {\n        var _ref = _asyncToGenerator(function* (extName) {\n          if (_this2.extensions[extName].when() == ExtensionState.PreProcess) {\n            yield _this2.extensions[extName].onResponse(ext[extName]);\n          }\n        });\n        return function (_x) {\n          return _ref.apply(this, arguments);\n        };\n      }()));\n    })();\n  }\n  onPostExtensionsResponse(ext) {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      yield Promise.all(Object.keys(ext).map(/*#__PURE__*/function () {\n        var _ref2 = _asyncToGenerator(function* (extName) {\n          if (_this3.extensions[extName].when() == ExtensionState.PostProcess) {\n            yield _this3.extensions[extName].onResponse(ext[extName]);\n          }\n        });\n        return function (_x2) {\n          return _ref2.apply(this, arguments);\n        };\n      }()));\n    })();\n  }\n\n  /**\n   * Invoke all attached room data listeners.\n   * @param roomId - The room which received some data.\n   * @param roomData - The raw sliding sync response JSON.\n   */\n  invokeRoomDataListeners(roomId, roomData) {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      if (!roomData.required_state) {\n        roomData.required_state = [];\n      }\n      if (!roomData.timeline) {\n        roomData.timeline = [];\n      }\n      yield _this4.emitPromised(SlidingSyncEvent.RoomData, roomId, roomData);\n    })();\n  }\n\n  /**\n   * Invoke all attached lifecycle listeners.\n   * @param state - The Lifecycle state\n   * @param resp - The raw sync response JSON\n   * @param err - Any error that occurred when making the request e.g. network errors.\n   */\n  invokeLifecycleListeners(state, resp, err) {\n    this.emit(SlidingSyncEvent.Lifecycle, state, resp, err);\n  }\n\n  /**\n   * Resend a Sliding Sync request. Used when something has changed in the request.\n   */\n  resend() {\n    var _this$abortController;\n    this.needsResend = true;\n    (_this$abortController = this.abortController) === null || _this$abortController === void 0 || _this$abortController.abort();\n    this.abortController = new AbortController();\n  }\n\n  /**\n   * Stop syncing with the server.\n   */\n  stop() {\n    var _this$abortController2;\n    this.terminated = true;\n    (_this$abortController2 = this.abortController) === null || _this$abortController2 === void 0 || _this$abortController2.abort();\n    // remove all listeners so things can be GC'd\n    this.removeAllListeners(SlidingSyncEvent.Lifecycle);\n    this.removeAllListeners(SlidingSyncEvent.RoomData);\n  }\n\n  /**\n   * Re-setup this connection e.g in the event of an expired session.\n   */\n  resetup() {\n    logger.warn(\"SlidingSync: resetting connection info\");\n    // resend sticky params and de-confirm all subscriptions\n    this.lists.forEach(l => {\n      l.setModified(true);\n    });\n    this.confirmedRoomSubscriptions = new Set(); // leave desired ones alone though!\n    // reset the connection as we might be wedged\n    this.resend();\n  }\n\n  /**\n   * Start syncing with the server. Blocks until stopped.\n   */\n  start() {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      _this5.abortController = new AbortController();\n      var currentPos;\n      var _loop = function* _loop() {\n          _this5.needsResend = false;\n          var resp;\n          try {\n            var _resp$lists, _resp$rooms, _resp$extensions;\n            var reqLists = {};\n            _this5.lists.forEach((l, key) => {\n              reqLists[key] = l.getList(true);\n            });\n            var reqBody = {\n              lists: reqLists,\n              pos: currentPos,\n              timeout: _this5.timeoutMS,\n              clientTimeout: _this5.timeoutMS + BUFFER_PERIOD_MS,\n              extensions: yield _this5.getExtensionRequest(currentPos === undefined)\n            };\n            // check if we are (un)subscribing to a room and modify request this one time for it\n            var newSubscriptions = difference(_this5.desiredRoomSubscriptions, _this5.confirmedRoomSubscriptions);\n            var unsubscriptions = difference(_this5.confirmedRoomSubscriptions, _this5.desiredRoomSubscriptions);\n            if (unsubscriptions.size > 0) {\n              reqBody.unsubscribe_rooms = Array.from(unsubscriptions);\n            }\n            if (newSubscriptions.size > 0) {\n              reqBody.room_subscriptions = {};\n              for (var roomId of newSubscriptions) {\n                var customSubName = _this5.roomIdToCustomSubscription.get(roomId);\n                var sub = _this5.roomSubscriptionInfo;\n                if (customSubName && _this5.customSubscriptions.has(customSubName)) {\n                  sub = _this5.customSubscriptions.get(customSubName);\n                }\n                reqBody.room_subscriptions[roomId] = sub;\n              }\n            }\n            _this5.pendingReq = _this5.client.slidingSync(reqBody, _this5.proxyBaseUrl, _this5.abortController.signal);\n            resp = yield _this5.pendingReq;\n            currentPos = resp.pos;\n            // update what we think we're subscribed to.\n            for (var _roomId of newSubscriptions) {\n              _this5.confirmedRoomSubscriptions.add(_roomId);\n            }\n            for (var _roomId2 of unsubscriptions) {\n              _this5.confirmedRoomSubscriptions.delete(_roomId2);\n            }\n            // mark all these lists as having been sent as sticky so we don't keep sending sticky params\n            _this5.lists.forEach(l => {\n              l.setModified(false);\n            });\n            // set default empty values so we don't need to null check\n            resp.lists = (_resp$lists = resp.lists) !== null && _resp$lists !== void 0 ? _resp$lists : {};\n            resp.rooms = (_resp$rooms = resp.rooms) !== null && _resp$rooms !== void 0 ? _resp$rooms : {};\n            resp.extensions = (_resp$extensions = resp.extensions) !== null && _resp$extensions !== void 0 ? _resp$extensions : {};\n            Object.keys(resp.lists).forEach(key => {\n              var list = _this5.lists.get(key);\n              if (!list || !resp) {\n                return;\n              }\n              list.joinedCount = resp.lists[key].count;\n            });\n            _this5.invokeLifecycleListeners(SlidingSyncState.RequestFinished, resp);\n          } catch (err) {\n            if (err.httpStatus) {\n              _this5.invokeLifecycleListeners(SlidingSyncState.RequestFinished, null, err);\n              if (err.httpStatus === 400) {\n                // session probably expired TODO: assign an errcode\n                // so drop state and re-request\n                _this5.resetup();\n                currentPos = undefined;\n                yield sleep(50); // in case the 400 was for something else; don't tightloop\n                return 0; // continue\n              } // else fallthrough to generic error handling\n            } else if (_this5.needsResend || err.name === \"AbortError\") {\n              return 0; // continue\n              // don't sleep as we caused this error by abort()ing the request.\n            }\n            logger.error(err);\n            yield sleep(5000);\n          }\n          if (!resp) {\n            return 0; // continue\n          }\n          yield _this5.onPreExtensionsResponse(resp.extensions);\n          for (var _roomId3 in resp.rooms) {\n            yield _this5.invokeRoomDataListeners(_roomId3, resp.rooms[_roomId3]);\n          }\n          _this5.invokeLifecycleListeners(SlidingSyncState.Complete, resp);\n          yield _this5.onPostExtensionsResponse(resp.extensions);\n        },\n        _ret;\n      while (!_this5.terminated) {\n        _ret = yield* _loop();\n        if (_ret === 0) continue;\n      }\n    })();\n  }\n}\nvar difference = (setA, setB) => {\n  var diff = new Set(setA);\n  for (var elem of setB) {\n    diff.delete(elem);\n  }\n  return diff;\n};\n//# sourceMappingURL=sliding-sync.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nimport _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { NotificationCountType, Room, RoomEvent } from \"./models/room.js\";\nimport { logger } from \"./logger.js\";\nimport { promiseMapSeries } from \"./utils.js\";\nimport { EventTimeline } from \"./models/event-timeline.js\";\nimport { ClientEvent } from \"./client.js\";\nimport { SyncState, _createAndReEmitRoom, defaultClientOpts, defaultSyncApiOpts, processToDeviceMessages } from \"./sync.js\";\nimport { MatrixError } from \"./http-api/index.js\";\nimport { ExtensionState, SlidingSyncEvent, SlidingSyncState } from \"./sliding-sync.js\";\nimport { EventType } from \"./@types/event.js\";\nimport { RoomStateEvent } from \"./models/room-state.js\";\nimport { RoomMemberEvent } from \"./models/room-member.js\";\nimport { KnownMembership } from \"./@types/membership.js\";\n\n// Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed\n// to RECONNECTING. This is needed to inform the client of server issues when the\n// keepAlive is successful but the server /sync fails.\nvar FAILED_SYNC_ERROR_THRESHOLD = 3;\nclass ExtensionE2EE {\n  constructor(crypto) {\n    this.crypto = crypto;\n  }\n  name() {\n    return \"e2ee\";\n  }\n  when() {\n    return ExtensionState.PreProcess;\n  }\n  onRequest(isInitial) {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      if (isInitial) {\n        // In SSS, the `?pos=` contains the stream position for device list updates.\n        // If we do not have a `?pos=` (e.g because we forgot it, or because the server\n        // invalidated our connection) then we MUST invlaidate all device lists because\n        // the server will not tell us the delta. This will then cause UTDs as we will fail\n        // to encrypt for new devices. This is an expensive call, so we should\n        // really really remember `?pos=` wherever possible.\n        logger.log(\"ExtensionE2EE: invalidating all device lists due to missing 'pos'\");\n        yield _this.crypto.markAllTrackedUsersAsDirty();\n      }\n      return {\n        enabled: true // this is sticky so only send it on the initial request\n      };\n    })();\n  }\n  onResponse(data) {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      // Handle device list updates\n      if (data.device_lists) {\n        yield _this2.crypto.processDeviceLists(data.device_lists);\n      }\n\n      // Handle one_time_keys_count and unused_fallback_key_types\n      yield _this2.crypto.processKeyCounts(data.device_one_time_keys_count, data[\"device_unused_fallback_key_types\"] || data[\"org.matrix.msc2732.device_unused_fallback_key_types\"]);\n      _this2.crypto.onSyncCompleted({});\n    })();\n  }\n}\nclass ExtensionToDevice {\n  constructor(client, cryptoCallbacks) {\n    this.client = client;\n    this.cryptoCallbacks = cryptoCallbacks;\n    _defineProperty(this, \"nextBatch\", null);\n  }\n  name() {\n    return \"to_device\";\n  }\n  when() {\n    return ExtensionState.PreProcess;\n  }\n  onRequest(isInitial) {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      return {\n        since: _this3.nextBatch !== null ? _this3.nextBatch : undefined,\n        limit: 100,\n        enabled: true\n      };\n    })();\n  }\n  onResponse(data) {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      var events = data[\"events\"] || [];\n      var receivedToDeviceMessages;\n      if (_this4.cryptoCallbacks) {\n        receivedToDeviceMessages = yield _this4.cryptoCallbacks.preprocessToDeviceMessages(events);\n      } else {\n        receivedToDeviceMessages = events.map(rawEvent => (\n        // Crypto is not enabled, so we just return the events.\n        {\n          message: rawEvent,\n          encryptionInfo: null\n        }));\n      }\n      processToDeviceMessages(receivedToDeviceMessages, _this4.client);\n      _this4.nextBatch = data.next_batch;\n    })();\n  }\n}\nclass ExtensionAccountData {\n  constructor(client) {\n    this.client = client;\n  }\n  name() {\n    return \"account_data\";\n  }\n  when() {\n    return ExtensionState.PostProcess;\n  }\n  onRequest(isInitial) {\n    return _asyncToGenerator(function* () {\n      return {\n        enabled: true\n      };\n    })();\n  }\n  onResponse(data) {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      if (data.global && data.global.length > 0) {\n        _this5.processGlobalAccountData(data.global);\n      }\n      for (var roomId in data.rooms) {\n        var accountDataEvents = mapEvents(_this5.client, roomId, data.rooms[roomId]);\n        var room = _this5.client.getRoom(roomId);\n        if (!room) {\n          logger.warn(\"got account data for room but room doesn't exist on client:\", roomId);\n          continue;\n        }\n        room.addAccountData(accountDataEvents);\n        accountDataEvents.forEach(e => {\n          _this5.client.emit(ClientEvent.Event, e);\n        });\n      }\n    })();\n  }\n  processGlobalAccountData(globalAccountData) {\n    var events = mapEvents(this.client, undefined, globalAccountData);\n    var prevEventsMap = events.reduce((m, c) => {\n      m[c.getType()] = this.client.store.getAccountData(c.getType());\n      return m;\n    }, {});\n    this.client.store.storeAccountDataEvents(events);\n    events.forEach(accountDataEvent => {\n      // Honour push rules that come down the sync stream but also\n      // honour push rules that were previously cached. Base rules\n      // will be updated when we receive push rules via getPushRules\n      // (see sync) before syncing over the network.\n      if (accountDataEvent.getType() === EventType.PushRules) {\n        var rules = accountDataEvent.getContent();\n        this.client.setPushRules(rules);\n      }\n      var prevEvent = prevEventsMap[accountDataEvent.getType()];\n      this.client.emit(ClientEvent.AccountData, accountDataEvent, prevEvent);\n      return accountDataEvent;\n    });\n  }\n}\nclass ExtensionTyping {\n  constructor(client) {\n    this.client = client;\n  }\n  name() {\n    return \"typing\";\n  }\n  when() {\n    return ExtensionState.PostProcess;\n  }\n  onRequest(isInitial) {\n    return _asyncToGenerator(function* () {\n      return {\n        enabled: true\n      };\n    })();\n  }\n  onResponse(data) {\n    var _this6 = this;\n    return _asyncToGenerator(function* () {\n      if (!(data !== null && data !== void 0 && data.rooms)) {\n        return;\n      }\n      for (var roomId in data.rooms) {\n        processEphemeralEvents(_this6.client, roomId, [data.rooms[roomId]]);\n      }\n    })();\n  }\n}\nclass ExtensionReceipts {\n  constructor(client) {\n    this.client = client;\n  }\n  name() {\n    return \"receipts\";\n  }\n  when() {\n    return ExtensionState.PostProcess;\n  }\n  onRequest(isInitial) {\n    return _asyncToGenerator(function* () {\n      return {\n        enabled: true\n      };\n    })();\n  }\n  onResponse(data) {\n    var _this7 = this;\n    return _asyncToGenerator(function* () {\n      if (!(data !== null && data !== void 0 && data.rooms)) {\n        return;\n      }\n      for (var roomId in data.rooms) {\n        processEphemeralEvents(_this7.client, roomId, [data.rooms[roomId]]);\n      }\n    })();\n  }\n}\n\n/**\n * A copy of SyncApi such that it can be used as a drop-in replacement for sync v2. For the actual\n * sliding sync API, see sliding-sync.ts or the class SlidingSync.\n */\nexport class SlidingSyncSdk {\n  // accumulator of sync events in the current sync response\n\n  constructor(slidingSync, client, opts, syncOpts) {\n    this.slidingSync = slidingSync;\n    this.client = client;\n    _defineProperty(this, \"opts\", void 0);\n    _defineProperty(this, \"syncOpts\", void 0);\n    _defineProperty(this, \"syncState\", null);\n    _defineProperty(this, \"syncStateData\", void 0);\n    _defineProperty(this, \"lastPos\", null);\n    _defineProperty(this, \"failCount\", 0);\n    _defineProperty(this, \"notifEvents\", []);\n    this.opts = defaultClientOpts(opts);\n    this.syncOpts = defaultSyncApiOpts(syncOpts);\n    if (client.getNotifTimelineSet()) {\n      client.reEmitter.reEmit(client.getNotifTimelineSet(), [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n    }\n    this.slidingSync.on(SlidingSyncEvent.Lifecycle, this.onLifecycle.bind(this));\n    this.slidingSync.on(SlidingSyncEvent.RoomData, this.onRoomData.bind(this));\n    var extensions = [new ExtensionToDevice(this.client, this.syncOpts.cryptoCallbacks), new ExtensionAccountData(this.client), new ExtensionTyping(this.client), new ExtensionReceipts(this.client)];\n    if (this.syncOpts.cryptoCallbacks) {\n      extensions.push(new ExtensionE2EE(this.syncOpts.cryptoCallbacks));\n    }\n    extensions.forEach(ext => {\n      this.slidingSync.registerExtension(ext);\n    });\n  }\n  onRoomData(roomId, roomData) {\n    var _this8 = this;\n    return _asyncToGenerator(function* () {\n      var room = _this8.client.store.getRoom(roomId);\n      if (!room) {\n        if (!roomData.initial) {\n          _this8.syncOpts.logger.debug(\"initial flag not set but no stored room exists for room \", roomId, roomData);\n          return;\n        }\n        room = _createAndReEmitRoom(_this8.client, roomId, _this8.opts);\n      }\n      yield _this8.processRoomData(_this8.client, room, roomData);\n    })();\n  }\n  onLifecycle(state, resp, err) {\n    if (err) {\n      this.syncOpts.logger.debug(\"onLifecycle\", state, err);\n    }\n    switch (state) {\n      case SlidingSyncState.Complete:\n        this.purgeNotifications();\n        if (!resp) {\n          break;\n        }\n        // Element won't stop showing the initial loading spinner unless we fire SyncState.Prepared\n        if (!this.lastPos) {\n          this.updateSyncState(SyncState.Prepared, {\n            oldSyncToken: undefined,\n            nextSyncToken: resp.pos,\n            catchingUp: false,\n            fromCache: false\n          });\n        }\n        // Conversely, Element won't show the room list unless there is at least 1x SyncState.Syncing\n        // so hence for the very first sync we will fire prepared then immediately syncing.\n        this.updateSyncState(SyncState.Syncing, {\n          oldSyncToken: this.lastPos,\n          nextSyncToken: resp.pos,\n          catchingUp: false,\n          fromCache: false\n        });\n        this.lastPos = resp.pos;\n        break;\n      case SlidingSyncState.RequestFinished:\n        if (err) {\n          this.failCount += 1;\n          this.updateSyncState(this.failCount > FAILED_SYNC_ERROR_THRESHOLD ? SyncState.Error : SyncState.Reconnecting, {\n            error: new MatrixError(err)\n          });\n          if (this.shouldAbortSync(new MatrixError(err))) {\n            return; // shouldAbortSync actually stops syncing too so we don't need to do anything.\n          }\n        } else {\n          this.failCount = 0;\n          this.syncOpts.logger.debug(\"SlidingSyncState.RequestFinished with \".concat(Object.keys((resp === null || resp === void 0 ? void 0 : resp.rooms) || []).length, \" rooms\"));\n        }\n        break;\n    }\n  }\n\n  /**\n   * Sync rooms the user has left.\n   * @returns Resolved when they've been added to the store.\n   */\n  syncLeftRooms() {\n    return _asyncToGenerator(function* () {\n      return []; // TODO\n    })();\n  }\n\n  /**\n   * Peek into a room. This will result in the room in question being synced so it\n   * is accessible via getRooms(). Live updates for the room will be provided.\n   * @param roomId - The room ID to peek into.\n   * @returns A promise which resolves once the room has been added to the\n   * store.\n   */\n  peek(roomId) {\n    return _asyncToGenerator(function* () {\n      return null; // TODO\n    })();\n  }\n\n  /**\n   * Stop polling for updates in the peeked room. NOPs if there is no room being\n   * peeked.\n   */\n  stopPeeking() {\n    // TODO\n  }\n\n  /**\n   * Specify the set_presence value to be used for subsequent calls to the Sync API.\n   * @param presence - the presence to specify to set_presence of sync calls\n   */\n  setPresence(presence) {\n    // TODO not possible in sliding sync yet\n  }\n\n  /**\n   * Returns the current state of this sync object\n   * @see MatrixClient#event:\"sync\"\n   */\n  getSyncState() {\n    return this.syncState;\n  }\n\n  /**\n   * Returns the additional data object associated with\n   * the current sync state, or null if there is no\n   * such data.\n   * Sync errors, if available, are put in the 'error' key of\n   * this object.\n   */\n  getSyncStateData() {\n    var _this$syncStateData;\n    return (_this$syncStateData = this.syncStateData) !== null && _this$syncStateData !== void 0 ? _this$syncStateData : null;\n  }\n\n  // Helper functions which set up JS SDK structs are below and are identical to the sync v2 counterparts\n\n  createRoom(roomId) {\n    // XXX cargoculted from sync.ts\n    var {\n      timelineSupport\n    } = this.client;\n    var room = new Room(roomId, this.client, this.client.getUserId(), {\n      lazyLoadMembers: this.opts.lazyLoadMembers,\n      pendingEventOrdering: this.opts.pendingEventOrdering,\n      timelineSupport\n    });\n    this.client.reEmitter.reEmit(room, [RoomEvent.Name, RoomEvent.Redaction, RoomEvent.RedactionCancelled, RoomEvent.Receipt, RoomEvent.Tags, RoomEvent.LocalEchoUpdated, RoomEvent.AccountData, RoomEvent.MyMembership, RoomEvent.Timeline, RoomEvent.TimelineReset]);\n    this.registerStateListeners(room);\n    return room;\n  }\n  registerStateListeners(room) {\n    // XXX cargoculted from sync.ts\n    // we need to also re-emit room state and room member events, so hook it up\n    // to the client now. We need to add a listener for RoomState.members in\n    // order to hook them correctly.\n    this.client.reEmitter.reEmit(room.currentState, [RoomStateEvent.Events, RoomStateEvent.Members, RoomStateEvent.NewMember, RoomStateEvent.Update]);\n    room.currentState.on(RoomStateEvent.NewMember, (event, state, member) => {\n      var _this$client$getUser;\n      member.user = (_this$client$getUser = this.client.getUser(member.userId)) !== null && _this$client$getUser !== void 0 ? _this$client$getUser : undefined;\n      this.client.reEmitter.reEmit(member, [RoomMemberEvent.Name, RoomMemberEvent.Typing, RoomMemberEvent.PowerLevel, RoomMemberEvent.Membership]);\n    });\n  }\n\n  /*\n  private deregisterStateListeners(room: Room): void { // XXX cargoculted from sync.ts\n      // could do with a better way of achieving this.\n      room.currentState.removeAllListeners(RoomStateEvent.Events);\n      room.currentState.removeAllListeners(RoomStateEvent.Members);\n      room.currentState.removeAllListeners(RoomStateEvent.NewMember);\n  } */\n\n  shouldAbortSync(error) {\n    if (error.errcode === \"M_UNKNOWN_TOKEN\") {\n      // The logout already happened, we just need to stop.\n      this.syncOpts.logger.warn(\"Token no longer valid - assuming logout\");\n      this.stop();\n      this.updateSyncState(SyncState.Error, {\n        error\n      });\n      return true;\n    }\n    return false;\n  }\n  processRoomData(client, room, roomData) {\n    var _this9 = this;\n    return _asyncToGenerator(function* () {\n      roomData = ensureNameEvent(client, room.roomId, roomData);\n      var stateEvents = mapEvents(_this9.client, room.roomId, roomData.required_state);\n      // Prevent events from being decrypted ahead of time\n      // this helps large account to speed up faster\n      // room::decryptCriticalEvent is in charge of decrypting all the events\n      // required for a client to function properly\n      var timelineEvents = mapEvents(_this9.client, room.roomId, roomData.timeline, false);\n      var ephemeralEvents = []; // TODO this.mapSyncEventsFormat(joinObj.ephemeral);\n\n      // TODO: handle threaded / beacon events\n\n      if (roomData.limited || roomData.initial) {\n        // we should not know about any of these timeline entries if this is a genuinely new room.\n        // If we do, then we've effectively done scrollback (e.g requesting timeline_limit: 1 for\n        // this room, then timeline_limit: 50).\n        var knownEvents = new Set();\n        room.getLiveTimeline().getEvents().forEach(e => {\n          knownEvents.add(e.getId());\n        });\n        // all unknown events BEFORE a known event must be scrollback e.g:\n        //       D E   <-- what we know\n        // A B C D E F <-- what we just received\n        // means:\n        // A B C       <-- scrollback\n        //       D E   <-- dupes\n        //           F <-- new event\n        // We bucket events based on if we have seen a known event yet.\n        var oldEvents = [];\n        var newEvents = [];\n        var seenKnownEvent = false;\n        for (var i = timelineEvents.length - 1; i >= 0; i--) {\n          var recvEvent = timelineEvents[i];\n          if (knownEvents.has(recvEvent.getId())) {\n            seenKnownEvent = true;\n            continue; // don't include this event, it's a dupe\n          }\n          if (seenKnownEvent) {\n            // old -> new\n            oldEvents.push(recvEvent);\n          } else {\n            // old -> new\n            newEvents.unshift(recvEvent);\n          }\n        }\n        timelineEvents = newEvents;\n        if (oldEvents.length > 0) {\n          // old events are scrollback, insert them now\n          room.addEventsToTimeline(oldEvents, true, false, room.getLiveTimeline(), roomData.prev_batch);\n        }\n      }\n      var encrypted = room.hasEncryptionStateEvent();\n      // we do this first so it's correct when any of the events fire\n      if (roomData.notification_count != null) {\n        room.setUnreadNotificationCount(NotificationCountType.Total, roomData.notification_count);\n      }\n      if (roomData.highlight_count != null) {\n        // We track unread notifications ourselves in encrypted rooms, so don't\n        // bother setting it here. We trust our calculations better than the\n        // server's for this case, and therefore will assume that our non-zero\n        // count is accurate.\n        if (!encrypted || encrypted && room.getUnreadNotificationCount(NotificationCountType.Highlight) <= 0) {\n          room.setUnreadNotificationCount(NotificationCountType.Highlight, roomData.highlight_count);\n        }\n      }\n      if (roomData.bump_stamp) {\n        room.setBumpStamp(roomData.bump_stamp);\n      }\n      if (Number.isInteger(roomData.invited_count)) {\n        room.currentState.setInvitedMemberCount(roomData.invited_count);\n      }\n      if (Number.isInteger(roomData.joined_count)) {\n        room.currentState.setJoinedMemberCount(roomData.joined_count);\n      }\n      if (roomData.invite_state) {\n        var inviteStateEvents = mapEvents(_this9.client, room.roomId, roomData.invite_state);\n        yield _this9.injectRoomEvents(room, inviteStateEvents);\n        if (roomData.initial) {\n          room.recalculate();\n          _this9.client.store.storeRoom(room);\n          _this9.client.emit(ClientEvent.Room, room);\n        }\n        inviteStateEvents.forEach(e => {\n          _this9.client.emit(ClientEvent.Event, e);\n        });\n        return;\n      }\n      if (roomData.limited) {\n        var _roomData$prev_batch;\n        // set the back-pagination token. Do this *before* adding any\n        // events so that clients can start back-paginating.\n        room.getLiveTimeline().setPaginationToken((_roomData$prev_batch = roomData.prev_batch) !== null && _roomData$prev_batch !== void 0 ? _roomData$prev_batch : null, EventTimeline.BACKWARDS);\n      }\n\n      /* TODO\n      else if (roomData.limited) {\n           let limited = true;\n           // we've got a limited sync, so we *probably* have a gap in the\n          // timeline, so should reset. But we might have been peeking or\n          // paginating and already have some of the events, in which\n          // case we just want to append any subsequent events to the end\n          // of the existing timeline.\n          //\n          // This is particularly important in the case that we already have\n          // *all* of the events in the timeline - in that case, if we reset\n          // the timeline, we'll end up with an entirely empty timeline,\n          // which we'll try to paginate but not get any new events (which\n          // will stop us linking the empty timeline into the chain).\n          //\n          for (let i = timelineEvents.length - 1; i >= 0; i--) {\n              const eventId = timelineEvents[i].getId();\n              if (room.getTimelineForEvent(eventId)) {\n                  this.syncOpts.logger.debug(\"Already have event \" + eventId + \" in limited \" +\n                      \"sync - not resetting\");\n                  limited = false;\n                   // we might still be missing some of the events before i;\n                  // we don't want to be adding them to the end of the\n                  // timeline because that would put them out of order.\n                  timelineEvents.splice(0, i);\n                   // XXX: there's a problem here if the skipped part of the\n                  // timeline modifies the state set in stateEvents, because\n                  // we'll end up using the state from stateEvents rather\n                  // than the later state from timelineEvents. We probably\n                  // need to wind stateEvents forward over the events we're\n                  // skipping.\n                  break;\n              }\n          }\n           if (limited) {\n              room.resetLiveTimeline(\n                  roomData.prev_batch,\n                  null, // TODO this.syncOpts.canResetEntireTimeline(room.roomId) ? null : syncEventData.oldSyncToken,\n              );\n               // We have to assume any gap in any timeline is\n              // reason to stop incrementally tracking notifications and\n              // reset the timeline.\n              this.client.resetNotifTimelineSet();\n              this.registerStateListeners(room);\n          }\n      } */\n\n      yield _this9.injectRoomEvents(room, stateEvents, timelineEvents, roomData.num_live);\n\n      // we deliberately don't add ephemeral events to the timeline\n      room.addEphemeralEvents(ephemeralEvents);\n\n      // local fields must be set before any async calls because call site assumes\n      // synchronous execution prior to emitting SlidingSyncState.Complete\n      room.updateMyMembership(KnownMembership.Join);\n      room.setMSC4186SummaryData(roomData.heroes, roomData.joined_count, roomData.invited_count);\n      room.recalculate();\n      if (roomData.initial) {\n        client.store.storeRoom(room);\n        client.emit(ClientEvent.Room, room);\n      }\n\n      // check if any timeline events should bing and add them to the notifEvents array:\n      // we'll purge this once we've fully processed the sync response\n      _this9.addNotifications(timelineEvents);\n      var processRoomEvent = /*#__PURE__*/function () {\n        var _ref = _asyncToGenerator(function* (e) {\n          client.emit(ClientEvent.Event, e);\n          if (e.isState() && e.getType() == EventType.RoomEncryption && _this9.syncOpts.cryptoCallbacks) {\n            yield _this9.syncOpts.cryptoCallbacks.onCryptoEvent(room, e);\n          }\n        });\n        return function processRoomEvent(_x) {\n          return _ref.apply(this, arguments);\n        };\n      }();\n      yield promiseMapSeries(stateEvents, processRoomEvent);\n      yield promiseMapSeries(timelineEvents, processRoomEvent);\n      ephemeralEvents.forEach(function (e) {\n        client.emit(ClientEvent.Event, e);\n      });\n\n      // Decrypt only the last message in all rooms to make sure we can generate a preview\n      // And decrypt all events after the recorded read receipt to ensure an accurate\n      // notification count\n      room.decryptCriticalEvents();\n    })();\n  }\n\n  /**\n   * Injects events into a room's model.\n   * @param stateEventList - A list of state events. This is the state\n   * at the *END* of the timeline list if it is supplied.\n   * @param timelineEventList - A list of timeline events. Lower index\n   * is earlier in time. Higher index is later.\n   * @param numLive - the number of events in timelineEventList which just happened,\n   * supplied from the server.\n   */\n  injectRoomEvents(room, stateEventList) {\n    var _arguments = arguments,\n      _this0 = this;\n    return _asyncToGenerator(function* () {\n      var timelineEventList = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : [];\n      var numLive = _arguments.length > 3 && _arguments[3] !== undefined ? _arguments[3] : 0;\n      // If there are no events in the timeline yet, initialise it with\n      // the given state events\n      var liveTimeline = room.getLiveTimeline();\n      var timelineWasEmpty = liveTimeline.getEvents().length == 0;\n      if (timelineWasEmpty) {\n        // Passing these events into initialiseState will freeze them, so we need\n        // to compute and cache the push actions for them now, otherwise sync dies\n        // with an attempt to assign to read only property.\n        // XXX: This is pretty horrible and is assuming all sorts of behaviour from\n        // these functions that it shouldn't be. We should probably either store the\n        // push actions cache elsewhere so we can freeze MatrixEvents, or otherwise\n        // find some solution where MatrixEvents are immutable but allow for a cache\n        // field.\n        for (var ev of stateEventList) {\n          _this0.client.getPushActionsForEvent(ev);\n        }\n        liveTimeline.initialiseState(stateEventList);\n      }\n\n      // If the timeline wasn't empty, we process the state events here: they're\n      // defined as updates to the state before the start of the timeline, so this\n      // starts to roll the state forward.\n      // XXX: That's what we *should* do, but this can happen if we were previously\n      // peeking in a room, in which case we obviously do *not* want to add the\n      // state events here onto the end of the timeline. Historically, the js-sdk\n      // has just set these new state events on the old and new state. This seems\n      // very wrong because there could be events in the timeline that diverge the\n      // state, in which case this is going to leave things out of sync. However,\n      // for now I think it;s best to behave the same as the code has done previously.\n      if (!timelineWasEmpty) {\n        // XXX: As above, don't do this...\n        //room.addLiveEvents(stateEventList || []);\n        // Do this instead...\n        room.oldState.setStateEvents(stateEventList);\n        room.currentState.setStateEvents(stateEventList);\n      }\n\n      // the timeline is broken into 'live' events which just happened and normal timeline events\n      // which are still to be appended to the end of the live timeline but happened a while ago.\n      // The live events are marked as fromCache=false to ensure that downstream components know\n      // this is a live event, not historical (from a remote server cache).\n\n      var liveTimelineEvents = [];\n      if (numLive > 0) {\n        // last numLive events are live\n        liveTimelineEvents = timelineEventList.slice(-1 * numLive);\n        // everything else is not live\n        timelineEventList = timelineEventList.slice(0, -1 * liveTimelineEvents.length);\n      }\n\n      // Execute the timeline events.\n      // This also needs to be done before running push rules on the events as they need\n      // to be decorated with sender etc.\n      yield room.addLiveEvents(timelineEventList, {\n        fromCache: true,\n        addToState: false\n      });\n      if (liveTimelineEvents.length > 0) {\n        yield room.addLiveEvents(liveTimelineEvents, {\n          fromCache: false,\n          addToState: false\n        });\n      }\n      room.recalculate();\n\n      // resolve invites now we have set the latest state\n      _this0.resolveInvites(room);\n    })();\n  }\n  resolveInvites(room) {\n    if (!room || !this.opts.resolveInvitesToProfiles) {\n      return;\n    }\n    var client = this.client;\n    // For each invited room member we want to give them a displayname/avatar url\n    // if they have one (the m.room.member invites don't contain this).\n    room.getMembersWithMembership(KnownMembership.Invite).forEach(function (member) {\n      if (member.requestedProfileInfo) return;\n      member.requestedProfileInfo = true;\n      // try to get a cached copy first.\n      var user = client.getUser(member.userId);\n      var promise;\n      if (user) {\n        promise = Promise.resolve({\n          avatar_url: user.avatarUrl,\n          displayname: user.displayName\n        });\n      } else {\n        promise = client.getProfileInfo(member.userId);\n      }\n      promise.then(function (info) {\n        // slightly naughty by doctoring the invite event but this means all\n        // the code paths remain the same between invite/join display name stuff\n        // which is a worthy trade-off for some minor pollution.\n        var inviteEvent = member.events.member;\n        if (inviteEvent.getContent().membership !== KnownMembership.Invite) {\n          // between resolving and now they have since joined, so don't clobber\n          return;\n        }\n        inviteEvent.getContent().avatar_url = info.avatar_url;\n        inviteEvent.getContent().displayname = info.displayname;\n        // fire listeners\n        member.setMembershipEvent(inviteEvent, room.currentState);\n      }, function (_err) {\n        // OH WELL.\n      });\n    });\n  }\n  retryImmediately() {\n    return true;\n  }\n\n  /**\n   * Main entry point. Blocks until stop() is called.\n   */\n  sync() {\n    var _this1 = this;\n    return _asyncToGenerator(function* () {\n      _this1.syncOpts.logger.debug(\"Sliding sync init loop\");\n\n      //   1) We need to get push rules so we can check if events should bing as we get\n      //      them from /sync.\n      while (!_this1.client.isGuest()) {\n        try {\n          _this1.syncOpts.logger.debug(\"Getting push rules...\");\n          var result = yield _this1.client.getPushRules();\n          _this1.syncOpts.logger.debug(\"Got push rules\");\n          _this1.client.pushRules = result;\n          break;\n        } catch (err) {\n          _this1.syncOpts.logger.error(\"Getting push rules failed\", err);\n          if (_this1.shouldAbortSync(err)) {\n            return;\n          }\n        }\n      }\n\n      // start syncing\n      yield _this1.slidingSync.start();\n    })();\n  }\n\n  /**\n   * Stops the sync object from syncing.\n   */\n  stop() {\n    this.syncOpts.logger.debug(\"SyncApi.stop\");\n    this.slidingSync.stop();\n  }\n\n  /**\n   * Sets the sync state and emits an event to say so\n   * @param newState - The new state string\n   * @param data - Object of additional data to emit in the event\n   */\n  updateSyncState(newState, data) {\n    var old = this.syncState;\n    this.syncState = newState;\n    this.syncStateData = data;\n    this.client.emit(ClientEvent.Sync, this.syncState, old, data);\n  }\n\n  /**\n   * Takes a list of timelineEvents and adds and adds to notifEvents\n   * as appropriate.\n   * This must be called after the room the events belong to has been stored.\n   *\n   * @param timelineEventList - A list of timeline events. Lower index\n   * is earlier in time. Higher index is later.\n   */\n  addNotifications(timelineEventList) {\n    // gather our notifications into this.notifEvents\n    if (!this.client.getNotifTimelineSet()) {\n      return;\n    }\n    for (var timelineEvent of timelineEventList) {\n      var pushActions = this.client.getPushActionsForEvent(timelineEvent);\n      if (pushActions && pushActions.notify && pushActions.tweaks && pushActions.tweaks.highlight) {\n        this.notifEvents.push(timelineEvent);\n      }\n    }\n  }\n\n  /**\n   * Purge any events in the notifEvents array. Used after a /sync has been complete.\n   * This should not be called at a per-room scope (e.g in onRoomData) because otherwise the ordering\n   * will be messed up e.g room A gets a bing, room B gets a newer bing, but both in the same /sync\n   * response. If we purge at a per-room scope then we could process room B before room A leading to\n   * room B appearing earlier in the notifications timeline, even though it has the higher origin_server_ts.\n   */\n  purgeNotifications() {\n    this.notifEvents.sort(function (a, b) {\n      return a.getTs() - b.getTs();\n    });\n    this.notifEvents.forEach(event => {\n      var _this$client$getNotif;\n      (_this$client$getNotif = this.client.getNotifTimelineSet()) === null || _this$client$getNotif === void 0 || _this$client$getNotif.addLiveEvent(event, {\n        addToState: false\n      });\n    });\n    this.notifEvents = [];\n  }\n}\nfunction ensureNameEvent(client, roomId, roomData) {\n  // make sure m.room.name is in required_state if there is a name, replacing anything previously\n  // there if need be. This ensures clients transparently 'calculate' the right room name. Native\n  // sliding sync clients should just read the \"name\" field.\n  if (!roomData.name) {\n    return roomData;\n  }\n  for (var stateEvent of roomData.required_state) {\n    if (stateEvent.type === EventType.RoomName && stateEvent.state_key === \"\") {\n      stateEvent.content = {\n        name: roomData.name\n      };\n      return roomData;\n    }\n  }\n  roomData.required_state.push({\n    event_id: \"$fake-sliding-sync-name-event-\" + roomId,\n    state_key: \"\",\n    type: EventType.RoomName,\n    content: {\n      name: roomData.name\n    },\n    sender: client.getUserId(),\n    origin_server_ts: new Date().getTime()\n  });\n  return roomData;\n}\n// Helper functions which set up JS SDK structs are below and are identical to the sync v2 counterparts,\n// just outside the class.\nfunction mapEvents(client, roomId, events) {\n  var decrypt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;\n  var mapper = client.getEventMapper({\n    decrypt\n  });\n  return events.map(function (e) {\n    e.room_id = roomId;\n    return mapper(e);\n  });\n}\nfunction processEphemeralEvents(client, roomId, ephEvents) {\n  var ephemeralEvents = mapEvents(client, roomId, ephEvents);\n  var room = client.getRoom(roomId);\n  if (!room) {\n    logger.warn(\"got ephemeral events for room but room doesn't exist on client:\", roomId);\n    return;\n  }\n  room.addEphemeralEvents(ephemeralEvents);\n  ephemeralEvents.forEach(e => {\n    client.emit(ClientEvent.Event, e);\n  });\n}\n//# sourceMappingURL=sliding-sync-sdk.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module which manages queuing, scheduling and retrying\n * of requests.\n */\nimport { logger } from \"./logger.js\";\nimport { EventType } from \"./@types/event.js\";\nimport { removeElement } from \"./utils.js\";\nimport { calculateRetryBackoff } from \"./http-api/index.js\";\nvar DEBUG = false; // set true to enable console logging.\n\n/**\n * The function to invoke to process (send) events in the queue.\n * @param event - The event to send.\n * @returns Resolved/rejected depending on the outcome of the request.\n */\n\n// eslint-disable-next-line camelcase\nexport class MatrixScheduler {\n  /**\n   * Default retry algorithm for the matrix scheduler. Retries events up to 4 times with exponential backoff.\n   * @param attempts - Number of attempts that have been made, including the one that just failed (ie. starting at 1)\n   * @see retryAlgorithm\n   */\n  // eslint-disable-next-line @typescript-eslint/naming-convention\n  static RETRY_BACKOFF_RATELIMIT(event, attempts, err) {\n    return calculateRetryBackoff(err, attempts, false);\n  }\n\n  /**\n   * Queues `m.room.message` events and lets other events continue\n   * concurrently.\n   * @see queueAlgorithm\n   */\n  // eslint-disable-next-line @typescript-eslint/naming-convention\n  static QUEUE_MESSAGES(event) {\n    // enqueue messages or events that associate with another event (redactions and relations)\n    if (event.getType() === EventType.RoomMessage || event.hasAssociation()) {\n      // put these events in the 'message' queue.\n      return \"message\";\n    }\n    // allow all other events continue concurrently.\n    return null;\n  }\n\n  // queueName: [{\n  //  event: MatrixEvent,  // event to send\n  //  defer: PromiseWithResolvers,  // defer to resolve/reject at the END of the retries\n  //  attempts: Number  // number of times we've called processFn\n  // }, ...]\n\n  /**\n   * Construct a scheduler for Matrix. Requires\n   * {@link MatrixScheduler#setProcessFunction} to be provided\n   * with a way of processing events.\n   * @param retryAlgorithm - Optional. The retry\n   * algorithm to apply when determining when to try to send an event again.\n   * Defaults to {@link MatrixScheduler.RETRY_BACKOFF_RATELIMIT}.\n   * @param queueAlgorithm - Optional. The queuing\n   * algorithm to apply when determining which events should be sent before the\n   * given event. Defaults to {@link MatrixScheduler.QUEUE_MESSAGES}.\n   */\n  constructor() {\n    var retryAlgorithm = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : MatrixScheduler.RETRY_BACKOFF_RATELIMIT;\n    var queueAlgorithm = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : MatrixScheduler.QUEUE_MESSAGES;\n    this.retryAlgorithm = retryAlgorithm;\n    this.queueAlgorithm = queueAlgorithm;\n    _defineProperty(this, \"queues\", {});\n    _defineProperty(this, \"activeQueues\", []);\n    _defineProperty(this, \"procFn\", null);\n    _defineProperty(this, \"processQueue\", queueName => {\n      // get head of queue\n      var obj = this.peekNextEvent(queueName);\n      if (!obj) {\n        this.disableQueue(queueName);\n        return;\n      }\n      debuglog(\"Queue '%s' has %s pending events\", queueName, this.queues[queueName].length);\n      // fire the process function and if it resolves, resolve the deferred. Else\n      // invoke the retry algorithm.\n\n      // First wait for a resolved promise, so the resolve handlers for\n      // the deferred of the previously sent event can run.\n      // This way enqueued relations/redactions to enqueued events can receive\n      // the remove id of their target before being sent.\n      Promise.resolve().then(() => {\n        return this.procFn(obj.event);\n      }).then(res => {\n        // remove this from the queue\n        this.removeNextEvent(queueName);\n        debuglog(\"Queue '%s' sent event %s\", queueName, obj.event.getId());\n        obj.resolvers.resolve(res);\n        // keep processing\n        this.processQueue(queueName);\n      }, err => {\n        obj.attempts += 1;\n        // ask the retry algorithm when/if we should try again\n        var waitTimeMs = this.retryAlgorithm(obj.event, obj.attempts, err);\n        debuglog(\"retry(%s) err=%s event_id=%s waitTime=%s\", obj.attempts, err, obj.event.getId(), waitTimeMs);\n        if (waitTimeMs === -1) {\n          // give up (you quitter!)\n          logger.info(\"Queue '%s' giving up on event %s\", queueName, obj.event.getId());\n          // remove this from the queue\n          this.clearQueue(queueName, err);\n        } else {\n          setTimeout(this.processQueue, waitTimeMs, queueName);\n        }\n      });\n    });\n  }\n\n  /**\n   * Retrieve a queue based on an event. The event provided does not need to be in\n   * the queue.\n   * @param event - An event to get the queue for.\n   * @returns A shallow copy of events in the queue or null.\n   * Modifying this array will not modify the list itself. Modifying events in\n   * this array <i>will</i> modify the underlying event in the queue.\n   * @see MatrixScheduler.removeEventFromQueue To remove an event from the queue.\n   */\n  getQueueForEvent(event) {\n    var name = this.queueAlgorithm(event);\n    if (!name || !this.queues[name]) {\n      return null;\n    }\n    return this.queues[name].map(function (obj) {\n      return obj.event;\n    });\n  }\n\n  /**\n   * Remove this event from the queue. The event is equal to another event if they\n   * have the same ID returned from event.getId().\n   * @param event - The event to remove.\n   * @returns True if this event was removed.\n   */\n  removeEventFromQueue(event) {\n    var name = this.queueAlgorithm(event);\n    if (!name || !this.queues[name]) {\n      return false;\n    }\n    var removed = false;\n    removeElement(this.queues[name], element => {\n      if (element.event.getId() === event.getId()) {\n        // XXX we should probably reject the promise?\n        // https://github.com/matrix-org/matrix-js-sdk/issues/496\n        removed = true;\n        return true;\n      }\n      return false;\n    });\n    return removed;\n  }\n\n  /**\n   * Set the process function. Required for events in the queue to be processed.\n   * If set after events have been added to the queue, this will immediately start\n   * processing them.\n   * @param fn - The function that can process events\n   * in the queue.\n   */\n  setProcessFunction(fn) {\n    this.procFn = fn;\n    this.startProcessingQueues();\n  }\n\n  /**\n   * Queue an event if it is required and start processing queues.\n   * @param event - The event that may be queued.\n   * @returns A promise if the event was queued, which will be\n   * resolved or rejected in due time, else null.\n   */\n  queueEvent(event) {\n    var queueName = this.queueAlgorithm(event);\n    if (!queueName) {\n      return null;\n    }\n    // add the event to the queue and make a deferred for it.\n    if (!this.queues[queueName]) {\n      this.queues[queueName] = [];\n    }\n    var eventResolvers = Promise.withResolvers();\n    this.queues[queueName].push({\n      event: event,\n      resolvers: eventResolvers,\n      attempts: 0\n    });\n    debuglog(\"Queue algorithm dumped event %s into queue '%s'\", event.getId(), queueName);\n    this.startProcessingQueues();\n    return eventResolvers.promise;\n  }\n  startProcessingQueues() {\n    if (!this.procFn) return;\n    // for each inactive queue with events in them\n    Object.keys(this.queues).filter(queueName => {\n      return this.activeQueues.indexOf(queueName) === -1 && this.queues[queueName].length > 0;\n    }).forEach(queueName => {\n      // mark the queue as active\n      this.activeQueues.push(queueName);\n      // begin processing the head of the queue\n      debuglog(\"Spinning up queue: '%s'\", queueName);\n      this.processQueue(queueName);\n    });\n  }\n  disableQueue(queueName) {\n    // queue is empty. Mark as inactive and stop recursing.\n    var index = this.activeQueues.indexOf(queueName);\n    if (index >= 0) {\n      this.activeQueues.splice(index, 1);\n    }\n    logger.info(\"Stopping queue '%s' as it is now empty\", queueName);\n  }\n  clearQueue(queueName, err) {\n    logger.info(\"clearing queue '%s'\", queueName);\n    var obj;\n    while (obj = this.removeNextEvent(queueName)) {\n      obj.resolvers.reject(err);\n    }\n    this.disableQueue(queueName);\n  }\n  peekNextEvent(queueName) {\n    var queue = this.queues[queueName];\n    if (!Array.isArray(queue)) {\n      return undefined;\n    }\n    return queue[0];\n  }\n  removeNextEvent(queueName) {\n    var queue = this.queues[queueName];\n    if (!Array.isArray(queue)) {\n      return undefined;\n    }\n    return queue.shift();\n  }\n}\n\n/* istanbul ignore next */\nfunction debuglog() {\n  if (DEBUG) {\n    logger.log(...arguments);\n  }\n}\n//# sourceMappingURL=scheduler.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { ToDeviceMessageId } from \"./@types/event.js\";\nimport { ClientEvent } from \"./client.js\";\nimport { MatrixScheduler } from \"./scheduler.js\";\nimport { SyncState } from \"./sync.js\";\nimport { MapWithDefault } from \"./utils.js\";\nvar MAX_BATCH_SIZE = 20;\n\n/**\n * Maintains a queue of outgoing to-device messages, sending them\n * as soon as the homeserver is reachable.\n */\nexport class ToDeviceMessageQueue {\n  constructor(client, logger) {\n    var _this = this;\n    this.client = client;\n    this.logger = logger;\n    _defineProperty(this, \"sending\", false);\n    _defineProperty(this, \"running\", true);\n    _defineProperty(this, \"retryTimeout\", null);\n    _defineProperty(this, \"retryAttempts\", 0);\n    _defineProperty(this, \"sendQueue\", /*#__PURE__*/_asyncToGenerator(function* () {\n      if (_this.retryTimeout !== null) clearTimeout(_this.retryTimeout);\n      _this.retryTimeout = null;\n      if (_this.sending || !_this.running) return;\n      _this.logger.debug(\"Attempting to send queued to-device messages\");\n      _this.sending = true;\n      var headBatch;\n      try {\n        while (_this.running) {\n          headBatch = yield _this.client.store.getOldestToDeviceBatch();\n          if (headBatch === null) break;\n          yield _this.sendBatch(headBatch);\n          yield _this.client.store.removeToDeviceBatch(headBatch.id);\n          _this.retryAttempts = 0;\n        }\n\n        // Make sure we're still running after the async tasks: if not, stop.\n        if (!_this.running) return;\n        _this.logger.debug(\"All queued to-device messages sent\");\n      } catch (e) {\n        ++_this.retryAttempts;\n        // eslint-disable-next-line @typescript-eslint/naming-convention\n        // eslint-disable-next-line new-cap\n        var retryDelay = MatrixScheduler.RETRY_BACKOFF_RATELIMIT(null, _this.retryAttempts, e);\n        if (retryDelay === -1) {\n          // the scheduler function doesn't differentiate between fatal errors and just getting\n          // bored and giving up for now\n          if (Math.floor(e.httpStatus / 100) === 4) {\n            _this.logger.error(\"Fatal error when sending to-device message - dropping to-device batch!\", e);\n            yield _this.client.store.removeToDeviceBatch(headBatch.id);\n          } else {\n            _this.logger.info(\"Automatic retry limit reached for to-device messages.\");\n          }\n          return;\n        }\n        _this.logger.info(\"Failed to send batch of to-device messages. Will retry in \".concat(retryDelay, \"ms\"), e);\n        _this.retryTimeout = setTimeout(_this.sendQueue, retryDelay);\n      } finally {\n        _this.sending = false;\n      }\n    }));\n    /**\n     * Listen to sync state changes and automatically resend any pending events\n     * once syncing is resumed\n     */\n    _defineProperty(this, \"onResumedSync\", (state, oldState) => {\n      if (state === SyncState.Syncing && oldState !== SyncState.Syncing) {\n        this.logger.info(\"Resuming queue after resumed sync\");\n        this.sendQueue();\n      }\n    });\n  }\n  start() {\n    this.running = true;\n    this.sendQueue();\n    this.client.on(ClientEvent.Sync, this.onResumedSync);\n  }\n  stop() {\n    this.running = false;\n    if (this.retryTimeout !== null) clearTimeout(this.retryTimeout);\n    this.retryTimeout = null;\n    this.client.removeListener(ClientEvent.Sync, this.onResumedSync);\n  }\n  queueBatch(batch) {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      var batches = [];\n      for (var i = 0; i < batch.batch.length; i += MAX_BATCH_SIZE) {\n        var batchWithTxnId = {\n          eventType: batch.eventType,\n          batch: batch.batch.slice(i, i + MAX_BATCH_SIZE),\n          txnId: _this2.client.makeTxnId()\n        };\n        batches.push(batchWithTxnId);\n        var msgmap = batchWithTxnId.batch.map(msg => \"\".concat(msg.userId, \"/\").concat(msg.deviceId, \" (msgid \").concat(msg.payload[ToDeviceMessageId], \")\"));\n        _this2.logger.info(\"Enqueuing batch of to-device messages. type=\".concat(batch.eventType, \" txnid=\").concat(batchWithTxnId.txnId), msgmap);\n      }\n      yield _this2.client.store.saveToDeviceBatches(batches);\n      _this2.sendQueue();\n    })();\n  }\n  /**\n   * Attempts to send a batch of to-device messages.\n   */\n  sendBatch(batch) {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      var contentMap = new MapWithDefault(() => new Map());\n      for (var item of batch.batch) {\n        contentMap.getOrCreate(item.userId).set(item.deviceId, item.payload);\n      }\n      _this3.logger.info(\"Sending batch of \".concat(batch.batch.length, \" to-device messages with ID \").concat(batch.id, \" and txnId \").concat(batch.txnId));\n      yield _this3.client.sendToDevice(batch.eventType, contentMap, batch.txnId);\n    })();\n  }\n}\n//# sourceMappingURL=ToDeviceMessageQueue.js.map","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { UnstableValue } from \"matrix-events-sdk\";\n\n/// The event type storing the user's individual policies.\n///\n/// Exported for testing purposes.\nexport var POLICIES_ACCOUNT_EVENT_TYPE = new UnstableValue(\"m.policies\", \"org.matrix.msc3847.policies\");\n\n/// The key within the user's individual policies storing the user's ignored invites.\n///\n/// Exported for testing purposes.\nexport var IGNORE_INVITES_ACCOUNT_EVENT_KEY = new UnstableValue(\"m.ignore.invites\", \"org.matrix.msc3847.ignore.invites\");\n\n/// The types of recommendations understood.\nexport var PolicyRecommendation = /*#__PURE__*/function (PolicyRecommendation) {\n  PolicyRecommendation[\"Ban\"] = \"m.ban\";\n  return PolicyRecommendation;\n}({});\n\n/**\n * The various scopes for policies.\n */\nexport var PolicyScope = /*#__PURE__*/function (PolicyScope) {\n  /**\n   * The policy deals with an individual user, e.g. reject invites\n   * from this user.\n   */\n  PolicyScope[\"User\"] = \"m.policy.user\";\n  /**\n   * The policy deals with a room, e.g. reject invites towards\n   * a specific room.\n   */\n  PolicyScope[\"Room\"] = \"m.policy.room\";\n  /**\n   * The policy deals with a server, e.g. reject invites from\n   * this server.\n   */\n  PolicyScope[\"Server\"] = \"m.policy.server\";\n  return PolicyScope;\n}({});\n//# sourceMappingURL=invites-ignorer-types.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventTimeline } from \"./event-timeline.js\";\nimport { Preset } from \"../@types/partials.js\";\nimport { globToRegexp } from \"../utils.js\";\nimport { EventType } from \"../@types/event.js\";\nimport { IGNORE_INVITES_ACCOUNT_EVENT_KEY, POLICIES_ACCOUNT_EVENT_TYPE, PolicyRecommendation, PolicyScope } from \"./invites-ignorer-types.js\";\nexport { IGNORE_INVITES_ACCOUNT_EVENT_KEY, POLICIES_ACCOUNT_EVENT_TYPE, PolicyRecommendation, PolicyScope };\nvar scopeToEventTypeMap = {\n  [PolicyScope.User]: EventType.PolicyRuleUser,\n  [PolicyScope.Room]: EventType.PolicyRuleRoom,\n  [PolicyScope.Server]: EventType.PolicyRuleServer\n};\n\n/**\n * A container for ignored invites.\n *\n * # Performance\n *\n * This implementation is extremely naive. It expects that we are dealing\n * with a very short list of sources (e.g. only one). If real-world\n * applications turn out to require longer lists, we may need to rework\n * our data structures.\n */\nexport class IgnoredInvites {\n  constructor(client) {\n    this.client = client;\n  }\n\n  /**\n   * Add a new rule.\n   *\n   * @param scope - The scope for this rule.\n   * @param entity - The entity covered by this rule. Globs are supported.\n   * @param reason - A human-readable reason for introducing this new rule.\n   * @returns The event id for the new rule.\n   */\n  addRule(scope, entity, reason) {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      var target = yield _this.getOrCreateTargetRoom();\n      var response = yield _this.client.sendStateEvent(target.roomId, scopeToEventTypeMap[scope], {\n        entity,\n        reason,\n        recommendation: PolicyRecommendation.Ban\n      });\n      return response.event_id;\n    })();\n  }\n\n  /**\n   * Remove a rule.\n   */\n  removeRule(event) {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      yield _this2.client.redactEvent(event.getRoomId(), event.getId());\n    })();\n  }\n\n  /**\n   * Add a new room to the list of sources. If the user isn't a member of the\n   * room, attempt to join it.\n   *\n   * @param roomId - A valid room id. If this room is already in the list\n   * of sources, it will not be duplicated.\n   * @returns `true` if the source was added, `false` if it was already present.\n   * @throws If `roomId` isn't the id of a room that the current user is already\n   * member of or can join.\n   *\n   * # Safety\n   *\n   * This method will rewrite the `Policies` object in the user's account data.\n   * This rewrite is inherently racy and could overwrite or be overwritten by\n   * other concurrent rewrites of the same object.\n   */\n  addSource(roomId) {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      // We attempt to join the room *before* calling\n      // `await this.getOrCreateSourceRooms()` to decrease the duration\n      // of the racy section.\n      yield _this3.client.joinRoom(roomId);\n      // Race starts.\n      var sources = (yield _this3.getOrCreateSourceRooms()).map(room => room.roomId);\n      if (sources.includes(roomId)) {\n        return false;\n      }\n      sources.push(roomId);\n      yield _this3.withIgnoreInvitesPolicies(ignoreInvitesPolicies => {\n        ignoreInvitesPolicies.sources = sources;\n      });\n\n      // Race ends.\n      return true;\n    })();\n  }\n\n  /**\n   * Find out whether an invite should be ignored.\n   *\n   * @param params\n   * @param params.sender - The user id for the user who issued the invite.\n   * @param params.roomId - The room to which the user is invited.\n   * @returns A rule matching the entity, if any was found, `null` otherwise.\n   */\n  getRuleForInvite(_ref) {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      var {\n        sender,\n        roomId\n      } = _ref;\n      // In this implementation, we perform a very naive lookup:\n      // - search in each policy room;\n      // - turn each (potentially glob) rule entity into a regexp.\n      //\n      // Real-world testing will tell us whether this is performant enough.\n      // In the (unfortunately likely) case it isn't, there are several manners\n      // in which we could optimize this:\n      // - match several entities per go;\n      // - pre-compile each rule entity into a regexp;\n      // - pre-compile entire rooms into a single regexp.\n      var policyRooms = yield _this4.getOrCreateSourceRooms();\n      var senderServer = sender.split(\":\")[1];\n      var roomServer = roomId.split(\":\")[1];\n      for (var room of policyRooms) {\n        var state = room.getUnfilteredTimelineSet().getLiveTimeline().getState(EventTimeline.FORWARDS);\n        for (var {\n          scope,\n          entities\n        } of [{\n          scope: PolicyScope.Room,\n          entities: [roomId]\n        }, {\n          scope: PolicyScope.User,\n          entities: [sender]\n        }, {\n          scope: PolicyScope.Server,\n          entities: [senderServer, roomServer]\n        }]) {\n          var events = state.getStateEvents(scopeToEventTypeMap[scope]);\n          for (var event of events) {\n            var content = event.getContent();\n            if ((content === null || content === void 0 ? void 0 : content.recommendation) != PolicyRecommendation.Ban) {\n              // Ignoring invites only looks at `m.ban` recommendations.\n              continue;\n            }\n            var glob = content === null || content === void 0 ? void 0 : content.entity;\n            if (!glob) {\n              // Invalid event.\n              continue;\n            }\n            var regexp = void 0;\n            try {\n              regexp = new RegExp(globToRegexp(glob));\n            } catch (_unused) {\n              // Assume invalid event.\n              continue;\n            }\n            for (var entity of entities) {\n              if (entity && regexp.test(entity)) {\n                return event;\n              }\n            }\n            // No match.\n          }\n        }\n      }\n      return null;\n    })();\n  }\n\n  /**\n   * Get the target room, i.e. the room in which any new rule should be written.\n   *\n   * If there is no target room setup, a target room is created.\n   *\n   * Note: This method is public for testing reasons. Most clients should not need\n   * to call it directly.\n   *\n   * # Safety\n   *\n   * This method will rewrite the `Policies` object in the user's account data.\n   * This rewrite is inherently racy and could overwrite or be overwritten by\n   * other concurrent rewrites of the same object.\n   */\n  getOrCreateTargetRoom() {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      var ignoreInvitesPolicies = _this5.getIgnoreInvitesPolicies();\n      var target = ignoreInvitesPolicies.target;\n      // Validate `target`. If it is invalid, trash out the current `target`\n      // and create a new room.\n      if (typeof target !== \"string\") {\n        target = null;\n      }\n      if (target) {\n        // Check that the room exists and is valid.\n        var room = _this5.client.getRoom(target);\n        if (room) {\n          return room;\n        } else {\n          target = null;\n        }\n      }\n      // We need to create our own policy room for ignoring invites.\n      target = (yield _this5.client.createRoom({\n        name: \"Individual Policy Room\",\n        preset: Preset.PrivateChat\n      })).room_id;\n      yield _this5.withIgnoreInvitesPolicies(ignoreInvitesPolicies => {\n        ignoreInvitesPolicies.target = target;\n      });\n\n      // Since we have just called `createRoom`, `getRoom` should not be `null`.\n      return _this5.client.getRoom(target);\n    })();\n  }\n\n  /**\n   * Get the list of source rooms, i.e. the rooms from which rules need to be read.\n   *\n   * If no source rooms are setup, the target room is used as sole source room.\n   *\n   * Note: This method is public for testing reasons. Most clients should not need\n   * to call it directly.\n   *\n   * # Safety\n   *\n   * This method will rewrite the `Policies` object in the user's account data.\n   * This rewrite is inherently racy and could overwrite or be overwritten by\n   * other concurrent rewrites of the same object.\n   */\n  getOrCreateSourceRooms() {\n    var _this6 = this;\n    return _asyncToGenerator(function* () {\n      var ignoreInvitesPolicies = _this6.getIgnoreInvitesPolicies();\n      var sources = ignoreInvitesPolicies.sources;\n\n      // Validate `sources`. If it is invalid, trash out the current `sources`\n      // and create a new list of sources from `target`.\n      var hasChanges = false;\n      if (!Array.isArray(sources)) {\n        // `sources` could not be an array.\n        hasChanges = true;\n        sources = [];\n      }\n      var sourceRooms = sources\n      // `sources` could contain non-string / invalid room ids\n      .filter(roomId => typeof roomId === \"string\").map(roomId => _this6.client.getRoom(roomId)).filter(room => !!room);\n      if (sourceRooms.length != sources.length) {\n        hasChanges = true;\n      }\n      if (sourceRooms.length == 0) {\n        // `sources` could be empty (possibly because we've removed\n        // invalid content)\n        var target = yield _this6.getOrCreateTargetRoom();\n        hasChanges = true;\n        sourceRooms = [target];\n      }\n      if (hasChanges) {\n        // Reload `policies`/`ignoreInvitesPolicies` in case it has been changed\n        // during or by our call to `this.getTargetRoom()`.\n        yield _this6.withIgnoreInvitesPolicies(ignoreInvitesPolicies => {\n          ignoreInvitesPolicies.sources = sources;\n        });\n      }\n      return sourceRooms;\n    })();\n  }\n\n  /**\n   * Fetch the `IGNORE_INVITES_POLICIES` object from account data.\n   *\n   * If both an unstable prefix version and a stable prefix version are available,\n   * it will return the stable prefix version preferentially.\n   *\n   * The result is *not* validated but is guaranteed to be a non-null object.\n   *\n   * @returns A non-null object.\n   */\n  getIgnoreInvitesPolicies() {\n    return this.getPoliciesAndIgnoreInvitesPolicies().ignoreInvitesPolicies;\n  }\n\n  /**\n   * Modify in place the `IGNORE_INVITES_POLICIES` object from account data.\n   */\n  withIgnoreInvitesPolicies(cb) {\n    var _this7 = this;\n    return _asyncToGenerator(function* () {\n      var {\n        policies,\n        ignoreInvitesPolicies\n      } = _this7.getPoliciesAndIgnoreInvitesPolicies();\n      cb(ignoreInvitesPolicies);\n      policies[IGNORE_INVITES_ACCOUNT_EVENT_KEY.name] = ignoreInvitesPolicies;\n      yield _this7.client.setAccountData(POLICIES_ACCOUNT_EVENT_TYPE.name, policies);\n    })();\n  }\n\n  /**\n   * As `getIgnoreInvitesPolicies` but also return the `POLICIES_ACCOUNT_EVENT_TYPE`\n   * object.\n   */\n  getPoliciesAndIgnoreInvitesPolicies() {\n    var policies = {};\n    for (var key of [POLICIES_ACCOUNT_EVENT_TYPE.name, POLICIES_ACCOUNT_EVENT_TYPE.altName]) {\n      var _this$client$getAccou;\n      if (!key) {\n        continue;\n      }\n      var value = (_this$client$getAccou = this.client.getAccountData(key)) === null || _this$client$getAccou === void 0 ? void 0 : _this$client$getAccou.getContent();\n      if (value) {\n        policies = value;\n        break;\n      }\n    }\n    var ignoreInvitesPolicies = {};\n    var hasIgnoreInvitesPolicies = false;\n    for (var _key of [IGNORE_INVITES_ACCOUNT_EVENT_KEY.name, IGNORE_INVITES_ACCOUNT_EVENT_KEY.altName]) {\n      if (!_key) {\n        continue;\n      }\n      var _value = policies[_key];\n      if (_value && typeof _value == \"object\") {\n        ignoreInvitesPolicies = _value;\n        hasIgnoreInvitesPolicies = true;\n        break;\n      }\n    }\n    if (!hasIgnoreInvitesPolicies) {\n      policies[IGNORE_INVITES_ACCOUNT_EVENT_KEY.name] = ignoreInvitesPolicies;\n    }\n    return {\n      policies,\n      ignoreInvitesPolicies\n    };\n  }\n}\n//# sourceMappingURL=invites-ignorer.js.map","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** The prefix used on indexeddbs created by rust-crypto */\nexport var RUST_SDK_STORE_PREFIX = \"matrix-js-sdk\";\n//# sourceMappingURL=constants.js.map","// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET) {\n  if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n  const BASE_MAP = new Uint8Array(256)\n  for (let j = 0; j < BASE_MAP.length; j++) {\n    BASE_MAP[j] = 255\n  }\n  for (let i = 0; i < ALPHABET.length; i++) {\n    const x = ALPHABET.charAt(i)\n    const xc = x.charCodeAt(0)\n    if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n    BASE_MAP[xc] = i\n  }\n  const BASE = ALPHABET.length\n  const LEADER = ALPHABET.charAt(0)\n  const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n  const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n  function encode (source) {\n    // eslint-disable-next-line no-empty\n    if (source instanceof Uint8Array) { } else if (ArrayBuffer.isView(source)) {\n      source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n    } else if (Array.isArray(source)) {\n      source = Uint8Array.from(source)\n    }\n    if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n    if (source.length === 0) { return '' }\n    // Skip & count leading zeroes.\n    let zeroes = 0\n    let length = 0\n    let pbegin = 0\n    const pend = source.length\n    while (pbegin !== pend && source[pbegin] === 0) {\n      pbegin++\n      zeroes++\n    }\n    // Allocate enough space in big-endian base58 representation.\n    const size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n    const b58 = new Uint8Array(size)\n    // Process the bytes.\n    while (pbegin !== pend) {\n      let carry = source[pbegin]\n      // Apply \"b58 = b58 * 256 + ch\".\n      let i = 0\n      for (let it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n        carry += (256 * b58[it1]) >>> 0\n        b58[it1] = (carry % BASE) >>> 0\n        carry = (carry / BASE) >>> 0\n      }\n      if (carry !== 0) { throw new Error('Non-zero carry') }\n      length = i\n      pbegin++\n    }\n    // Skip leading zeroes in base58 result.\n    let it2 = size - length\n    while (it2 !== size && b58[it2] === 0) {\n      it2++\n    }\n    // Translate the result into a string.\n    let str = LEADER.repeat(zeroes)\n    for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n    return str\n  }\n  function decodeUnsafe (source) {\n    if (typeof source !== 'string') { throw new TypeError('Expected String') }\n    if (source.length === 0) { return new Uint8Array() }\n    let psz = 0\n    // Skip and count leading '1's.\n    let zeroes = 0\n    let length = 0\n    while (source[psz] === LEADER) {\n      zeroes++\n      psz++\n    }\n    // Allocate enough space in big-endian base256 representation.\n    const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n    const b256 = new Uint8Array(size)\n    // Process the characters.\n    while (psz < source.length) {\n      // Find code of next character\n      const charCode = source.charCodeAt(psz)\n      // Base map can not be indexed using char code\n      if (charCode > 255) { return }\n      // Decode character\n      let carry = BASE_MAP[charCode]\n      // Invalid character\n      if (carry === 255) { return }\n      let i = 0\n      for (let it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n        carry += (BASE * b256[it3]) >>> 0\n        b256[it3] = (carry % 256) >>> 0\n        carry = (carry / 256) >>> 0\n      }\n      if (carry !== 0) { throw new Error('Non-zero carry') }\n      length = i\n      psz++\n    }\n    // Skip leading zeroes in b256.\n    let it4 = size - length\n    while (it4 !== size && b256[it4] === 0) {\n      it4++\n    }\n    const vch = new Uint8Array(zeroes + (size - it4))\n    let j = zeroes\n    while (it4 !== size) {\n      vch[j++] = b256[it4++]\n    }\n    return vch\n  }\n  function decode (string) {\n    const buffer = decodeUnsafe(string)\n    if (buffer) { return buffer }\n    throw new Error('Non-base' + BASE + ' character')\n  }\n  return {\n    encode,\n    decodeUnsafe,\n    decode\n  }\n}\nexport default base\n","import basex from 'base-x';\nvar ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nexport default basex(ALPHABET);\n","/*\n * Copyright 2024 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Cryptography-related events emitted by the {@link matrix.MatrixClient}.\n */\nexport var CryptoEvent = /*#__PURE__*/function (CryptoEvent) {\n  /**\n   * Fires when the trust status of a user changes.\n   * The payload is a pair (userId, userTrustLevel). The trust level is one of the values from UserVerificationStatus.\n   */\n  CryptoEvent[\"UserTrustStatusChanged\"] = \"userTrustStatusChanged\";\n  /**\n   * Fires when the key backup status changes.\n   * The payload is a boolean indicating whether the key backup is enabled.\n   */\n  CryptoEvent[\"KeyBackupStatus\"] = \"crypto.keyBackupStatus\";\n  /**\n   * Fires when we failed to back up the keys\n   * The payload is the error code of the error that occurred.\n   */\n  CryptoEvent[\"KeyBackupFailed\"] = \"crypto.keyBackupFailed\";\n  /**\n   * Fires when the number of sessions that can be backed up changes.\n   * The payload is the remaining number of sessions that can be backed up.\n   */\n  CryptoEvent[\"KeyBackupSessionsRemaining\"] = \"crypto.keyBackupSessionsRemaining\";\n  /**\n   * Fires when a new valid backup decryption key is in cache.\n   * This will happen when a secret is received from another session, from secret storage,\n   * or when a new backup is created from this session.\n   *\n   * The payload is the version of the backup for which we have the key for.\n   *\n   * This event is only fired by the rust crypto backend.\n   */\n  CryptoEvent[\"KeyBackupDecryptionKeyCached\"] = \"crypto.keyBackupDecryptionKeyCached\";\n  /**\n   * Fires when a key verification request is received.\n   * The payload is a VerificationRequest object representing the request.\n   */\n  CryptoEvent[\"VerificationRequestReceived\"] = \"crypto.verificationRequestReceived\";\n  /** @deprecated Use {@link DevicesUpdated} instead when using rust crypto */\n  CryptoEvent[\"WillUpdateDevices\"] = \"crypto.willUpdateDevices\";\n  /**\n   * Fires whenever the stored devices for a user have been updated\n   * The payload is a pair (userIds, initialFetch).\n   */\n  CryptoEvent[\"DevicesUpdated\"] = \"crypto.devicesUpdated\";\n  /**\n   * Fires when the user's cross-signing keys have changed or cross-signing\n   * has been enabled/disabled. The client can use getStoredCrossSigningForUser\n   * with the user ID of the logged in user to check if cross-signing is\n   * enabled on the account. If enabled, it can test whether the current key\n   * is trusted using with checkUserTrust with the user ID of the logged\n   * in user. The checkOwnCrossSigningTrust function may be used to reconcile\n   * the trust in the account key.\n   *\n   * The cross-signing API is currently UNSTABLE and may change without notice.\n   * @experimental\n   */\n  CryptoEvent[\"KeysChanged\"] = \"crossSigning.keysChanged\";\n  /**\n   * Fires when data is being migrated from legacy crypto to rust crypto.\n   *\n   * The payload is a pair `(progress, total)`, where `progress` is the number of steps completed so far, and\n   * `total` is the total number of steps. When migration is complete, a final instance of the event is emitted, with\n   * `progress === total === -1`.\n   */\n  CryptoEvent[\"LegacyCryptoStoreMigrationProgress\"] = \"crypto.legacyCryptoStoreMigrationProgress\";\n  /**\n   * Fires when a new dehydrated device is created locally.\n   *\n   * After the client calls {@link CryptoApi.startDehydration}, this event\n   * will be fired every time a new dehydrated device is created.  It may fire\n   * before `startDehydration` returns.\n   */\n  CryptoEvent[\"DehydratedDeviceCreated\"] = \"dehydration.DehydratedDeviceCreated\";\n  /**\n   * Fires when a new dehydrated device is successfully uploaded to the server.\n   *\n   * This should fire shortly after {@link DehydratedDeviceCreated} fires. If\n   * upload is unsuccessful, this will be reported either by an error thrown\n   * by {@link CryptoApi.startDehydration} (for errors that happen before\n   * `startDehydration` returns), or by firing {@link DehydratedDeviceRotationError}\n   * (for errors that happen during regular rotation of the dehydrated device)\n   */\n  CryptoEvent[\"DehydratedDeviceUploaded\"] = \"dehydration.DehydratedDeviceUploaded\";\n  /**\n   * Fires when rehydration has started.\n   *\n   * After the client calls {@link CryptoApi.startDehydration}, this event will\n   * fire if a dehydrated device is found and we attempt to rehydrate it.\n   */\n  CryptoEvent[\"RehydrationStarted\"] = \"dehydration.RehydrationStarted\";\n  /**\n   * Fires during rehydration, to inform the application of rehydration progress.\n   *\n   * The payload is a pair `[roomKeyCount: number, toDeviceCount: number]`,\n   * where `roomKeyCount` is the number of room keys that have been received\n   * so far, and `toDeviceCount` is the number of to-device messages received\n   * so far (including the messages containing room keys).\n   */\n  CryptoEvent[\"RehydrationProgress\"] = \"dehydration.RehydrationProgress\";\n  /** Fires when rehydration has completed successfully. */\n  CryptoEvent[\"RehydrationCompleted\"] = \"dehydration.RehydrationCompleted\";\n  /** Fires when there was an error in rehydration.\n   *\n   * The payload is an error message as a string.\n   */\n  CryptoEvent[\"RehydrationError\"] = \"dehydration.RehydrationError\";\n  /**\n   * Fires when a dehydrated device key has been cached in the local database.\n   */\n  CryptoEvent[\"DehydrationKeyCached\"] = \"dehydration.DehydrationKeyCached\";\n  /**\n   * Fires when an error occurs during periodic rotation of the dehydrated device.\n   *\n   * The payload is an error message as a string.\n   */\n  CryptoEvent[\"DehydratedDeviceRotationError\"] = \"dehydration.DehydratedDeviceRotationError\";\n  return CryptoEvent;\n}({});\n//# sourceMappingURL=CryptoEvent.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * `matrix-js-sdk/lib/crypto-api`: End-to-end encryption support.\n *\n * The most important type is {@link CryptoApi}, an instance of which can be retrieved via\n * {@link MatrixClient.getCrypto}.\n *\n * @packageDocumentation\n */\n\n/**\n * The options to start device dehydration.\n */\n\n/**\n * Public interface to the cryptography parts of the js-sdk\n *\n * @remarks Currently, this is a work-in-progress. In time, more methods will be added here.\n */\n\n/** A reason code for a failure to decrypt an event. */\nexport var DecryptionFailureCode = /*#__PURE__*/function (DecryptionFailureCode) {\n  /** Message was encrypted with a Megolm session whose keys have not been shared with us. */\n  DecryptionFailureCode[\"MEGOLM_UNKNOWN_INBOUND_SESSION_ID\"] = \"MEGOLM_UNKNOWN_INBOUND_SESSION_ID\";\n  /** A special case of {@link MEGOLM_UNKNOWN_INBOUND_SESSION_ID}: the sender has told us it is withholding the key. */\n  DecryptionFailureCode[\"MEGOLM_KEY_WITHHELD\"] = \"MEGOLM_KEY_WITHHELD\";\n  /** A special case of {@link MEGOLM_KEY_WITHHELD}: the sender has told us it is withholding the key, because the current device is unverified. */\n  DecryptionFailureCode[\"MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE\"] = \"MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE\";\n  /** Message was encrypted with a Megolm session which has been shared with us, but in a later ratchet state. */\n  DecryptionFailureCode[\"OLM_UNKNOWN_MESSAGE_INDEX\"] = \"OLM_UNKNOWN_MESSAGE_INDEX\";\n  /**\n   * Message was sent before the current device was created; there is no key backup on the server, so this\n   * decryption failure is expected.\n   */\n  DecryptionFailureCode[\"HISTORICAL_MESSAGE_NO_KEY_BACKUP\"] = \"HISTORICAL_MESSAGE_NO_KEY_BACKUP\";\n  /**\n   * Message was sent before the current device was created; there was a key backup on the server, but we don't\n   * seem to have access to the backup. (Probably we don't have the right key.)\n   */\n  DecryptionFailureCode[\"HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED\"] = \"HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED\";\n  /**\n   * Message was sent before the current device was created; there was a (usable) key backup on the server, but we\n   * still can't decrypt. (Either the session isn't in the backup, or we just haven't gotten around to checking yet.)\n   */\n  DecryptionFailureCode[\"HISTORICAL_MESSAGE_WORKING_BACKUP\"] = \"HISTORICAL_MESSAGE_WORKING_BACKUP\";\n  /**\n   * Message was sent when the user was not a member of the room.\n   */\n  DecryptionFailureCode[\"HISTORICAL_MESSAGE_USER_NOT_JOINED\"] = \"HISTORICAL_MESSAGE_USER_NOT_JOINED\";\n  /**\n   * The sender's identity is not verified, but was previously verified.\n   */\n  DecryptionFailureCode[\"SENDER_IDENTITY_PREVIOUSLY_VERIFIED\"] = \"SENDER_IDENTITY_PREVIOUSLY_VERIFIED\";\n  /**\n   * The sender device is not cross-signed.  This will only be used if the\n   * device isolation mode is set to `OnlySignedDevicesIsolationMode`.\n   */\n  DecryptionFailureCode[\"UNSIGNED_SENDER_DEVICE\"] = \"UNSIGNED_SENDER_DEVICE\";\n  /**\n   * We weren't able to link the message back to any known device.  This will\n   * only be used if the device isolation mode is set to `OnlySignedDevicesIsolationMode`.\n   */\n  DecryptionFailureCode[\"UNKNOWN_SENDER_DEVICE\"] = \"UNKNOWN_SENDER_DEVICE\";\n  /** Unknown or unclassified error. */\n  DecryptionFailureCode[\"UNKNOWN_ERROR\"] = \"UNKNOWN_ERROR\";\n  return DecryptionFailureCode;\n}({});\n\n/** Base {@link DeviceIsolationMode} kind. */\nexport var DeviceIsolationModeKind = /*#__PURE__*/function (DeviceIsolationModeKind) {\n  DeviceIsolationModeKind[DeviceIsolationModeKind[\"AllDevicesIsolationMode\"] = 0] = \"AllDevicesIsolationMode\";\n  DeviceIsolationModeKind[DeviceIsolationModeKind[\"OnlySignedDevicesIsolationMode\"] = 1] = \"OnlySignedDevicesIsolationMode\";\n  return DeviceIsolationModeKind;\n}({});\n\n/**\n * A type of {@link DeviceIsolationMode}.\n *\n * Message encryption keys are shared with all devices in the room, except in case of\n * verified user problems (see {@link errorOnVerifiedUserProblems}).\n *\n * Events from all senders are always decrypted (and should be decorated with message shields in case\n * of authenticity warnings, see {@link EventEncryptionInfo}).\n */\nexport class AllDevicesIsolationMode {\n  /**\n   *\n   * @param errorOnVerifiedUserProblems - Behavior when sharing keys to remote devices.\n   *\n   * If set to `true`, sharing keys will fail (i.e. message sending will fail) with an error if:\n   *   - The user was previously verified but is not anymore, or:\n   *   - A verified user has some unverified devices (not cross-signed).\n   *\n   * If `false`, the keys will be distributed as usual. In this case, the client UX should display\n   * warnings to inform the user about problematic devices/users, and stop them hitting this case.\n   */\n  constructor(errorOnVerifiedUserProblems) {\n    this.errorOnVerifiedUserProblems = errorOnVerifiedUserProblems;\n    _defineProperty(this, \"kind\", DeviceIsolationModeKind.AllDevicesIsolationMode);\n  }\n}\n\n/**\n * A type of {@link DeviceIsolationMode}.\n *\n * Message encryption keys are only shared with devices that have been cross-signed by their owner.\n * Encryption will throw an error if a verified user replaces their identity.\n *\n * Events are decrypted only if they come from a cross-signed device. Other events will result in a decryption\n * failure. (To access the failure reason, see {@link MatrixEvent.decryptionFailureReason}.)\n */\nexport class OnlySignedDevicesIsolationMode {\n  constructor() {\n    _defineProperty(this, \"kind\", DeviceIsolationModeKind.OnlySignedDevicesIsolationMode);\n  }\n}\n\n/**\n * DeviceIsolationMode represents the mode of device isolation used when encrypting or decrypting messages.\n * It can be one of two types: {@link AllDevicesIsolationMode} or {@link OnlySignedDevicesIsolationMode}.\n *\n * Only supported by rust Crypto.\n */\n\n/**\n * Options object for `CryptoApi.bootstrapCrossSigning`.\n */\n\n/**\n * Represents the ways in which we trust a user\n */\nexport class UserVerificationStatus {\n  constructor(crossSigningVerified, crossSigningVerifiedBefore, tofu) {\n    var needsUserApproval = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n    this.crossSigningVerified = crossSigningVerified;\n    this.crossSigningVerifiedBefore = crossSigningVerifiedBefore;\n    this.tofu = tofu;\n    /**\n     * Indicates if the identity has changed in a way that needs user approval.\n     *\n     * This happens if the identity has changed since we first saw it, *unless* the new identity has also been verified\n     * by our user (eg via an interactive verification).\n     *\n     * To rectify this, either:\n     *\n     *  * Conduct a verification of the new identity via {@link CryptoApi.requestVerificationDM}.\n     *  * Pin the new identity, via {@link CryptoApi.pinCurrentUserIdentity}.\n     *\n     * @returns true if the identity has changed in a way that needs user approval.\n     */\n    _defineProperty(this, \"needsUserApproval\", void 0);\n    this.needsUserApproval = needsUserApproval;\n  }\n\n  /**\n   * @returns true if this user is verified via any means\n   */\n  isVerified() {\n    return this.isCrossSigningVerified();\n  }\n\n  /**\n   * @returns true if this user is verified via cross signing\n   */\n  isCrossSigningVerified() {\n    return this.crossSigningVerified;\n  }\n\n  /**\n   * @returns true if we ever verified this user before (at least for\n   * the history of verifications observed by this device).\n   */\n  wasCrossSigningVerified() {\n    return this.crossSigningVerifiedBefore;\n  }\n\n  /**\n   * @returns true if this user's key is trusted on first use\n   *\n   * @deprecated No longer supported, with the Rust crypto stack.\n   */\n  isTofu() {\n    return this.tofu;\n  }\n}\nexport class DeviceVerificationStatus {\n  constructor(opts) {\n    var _opts$signedByOwner, _opts$crossSigningVer, _opts$tofu, _opts$localVerified, _opts$trustCrossSigne;\n    /**\n     * True if this device has been signed by its owner (and that signature verified).\n     *\n     * This doesn't necessarily mean that we have verified the device, since we may not have verified the\n     * owner's cross-signing key.\n     */\n    _defineProperty(this, \"signedByOwner\", void 0);\n    /**\n     * True if this device has been verified via cross signing.\n     *\n     * This does *not* take into account `trustCrossSignedDevices`.\n     */\n    _defineProperty(this, \"crossSigningVerified\", void 0);\n    /**\n     * TODO: tofu magic wtf does this do?\n     */\n    _defineProperty(this, \"tofu\", void 0);\n    /**\n     * True if the device has been marked as locally verified.\n     */\n    _defineProperty(this, \"localVerified\", void 0);\n    /**\n     * True if the client has been configured to trust cross-signed devices via {@link CryptoApi#setTrustCrossSignedDevices}.\n     */\n    _defineProperty(this, \"trustCrossSignedDevices\", void 0);\n    this.signedByOwner = (_opts$signedByOwner = opts.signedByOwner) !== null && _opts$signedByOwner !== void 0 ? _opts$signedByOwner : false;\n    this.crossSigningVerified = (_opts$crossSigningVer = opts.crossSigningVerified) !== null && _opts$crossSigningVer !== void 0 ? _opts$crossSigningVer : false;\n    this.tofu = (_opts$tofu = opts.tofu) !== null && _opts$tofu !== void 0 ? _opts$tofu : false;\n    this.localVerified = (_opts$localVerified = opts.localVerified) !== null && _opts$localVerified !== void 0 ? _opts$localVerified : false;\n    this.trustCrossSignedDevices = (_opts$trustCrossSigne = opts.trustCrossSignedDevices) !== null && _opts$trustCrossSigne !== void 0 ? _opts$trustCrossSigne : false;\n  }\n\n  /**\n   * Check if we should consider this device \"verified\".\n   *\n   * A device is \"verified\" if either:\n   *  * it has been manually marked as such via {@link CryptoApi.setDeviceVerified}.\n   *  * it has been cross-signed with a verified signing key, **and** the client has been configured to trust\n   *    cross-signed devices via {@link CryptoApi.setTrustCrossSignedDevices}.\n   *\n   * @returns true if this device is verified via any means.\n   */\n  isVerified() {\n    return this.localVerified || this.trustCrossSignedDevices && this.crossSigningVerified;\n  }\n}\n\n/**\n * Enum representing the different stages of importing room keys.\n *\n * This is the type of the `stage` property of {@link ImportRoomKeyProgressData}.\n */\nexport var ImportRoomKeyStage = /*#__PURE__*/function (ImportRoomKeyStage) {\n  /**\n   * The stage where room keys are being fetched.\n   *\n   * @see {@link ImportRoomKeyFetchProgress}.\n   */\n  ImportRoomKeyStage[\"Fetch\"] = \"fetch\";\n  /**\n   * The stage where room keys are being loaded.\n   *\n   * @see {@link ImportRoomKeyLoadProgress}.\n   */\n  ImportRoomKeyStage[\"LoadKeys\"] = \"load_keys\";\n  return ImportRoomKeyStage;\n}({});\n\n/**\n * Type representing the progress during the 'fetch' stage of the room key import process.\n *\n * @see {@link ImportRoomKeyProgressData}.\n */\n\n/**\n * Type representing the progress during the 'load_keys' stage of the room key import process.\n *\n * @see {@link ImportRoomKeyProgressData}.\n */\n\n/**\n * Room key import progress report.\n * Used when calling {@link CryptoApi#importRoomKeys},\n * {@link CryptoApi#importRoomKeysAsJson} or {@link CryptoApi#restoreKeyBackup} as the parameter of\n * the progressCallback. Used to display feedback.\n */\n\n/**\n * Options object for {@link CryptoApi#importRoomKeys} and\n * {@link CryptoApi#importRoomKeysAsJson}.\n */\n\n/**\n * The result of a call to {@link CryptoApi.getCrossSigningStatus}.\n */\n\n/**\n * Crypto callbacks provided by the application\n */\n\n/**\n * The result of a call to {@link CryptoApi.getSecretStorageStatus}.\n */\n\n/**\n * Parameter of {@link CryptoApi#bootstrapSecretStorage}\n */\n\n/** Types of cross-signing key */\nexport var CrossSigningKey = /*#__PURE__*/function (CrossSigningKey) {\n  CrossSigningKey[\"Master\"] = \"master\";\n  CrossSigningKey[\"SelfSigning\"] = \"self_signing\";\n  CrossSigningKey[\"UserSigning\"] = \"user_signing\";\n  return CrossSigningKey;\n}({});\n\n/**\n * Information on one of the cross-signing keys.\n * @see https://spec.matrix.org/v1.7/client-server-api/#post_matrixclientv3keysdevice_signingupload\n */\n\n/**\n * Recovery key created by {@link CryptoApi#createRecoveryKeyFromPassphrase} or {@link CreateSecretStorageOpts#createSecretStorageKey}.\n */\n\n/**\n *  Result type of {@link CryptoApi#getEncryptionInfoForEvent}.\n */\n\n/**\n * Types of shield to be shown for {@link EventEncryptionInfo#shieldColour}.\n */\nexport var EventShieldColour = /*#__PURE__*/function (EventShieldColour) {\n  EventShieldColour[EventShieldColour[\"NONE\"] = 0] = \"NONE\";\n  EventShieldColour[EventShieldColour[\"GREY\"] = 1] = \"GREY\";\n  EventShieldColour[EventShieldColour[\"RED\"] = 2] = \"RED\";\n  return EventShieldColour;\n}({});\n\n/**\n * Reason codes for {@link EventEncryptionInfo#shieldReason}.\n */\nexport var EventShieldReason = /*#__PURE__*/function (EventShieldReason) {\n  /** An unknown reason from the crypto library (if you see this, it is a bug in matrix-js-sdk). */\n  EventShieldReason[EventShieldReason[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n  /** \"Encrypted by an unverified user.\" */\n  EventShieldReason[EventShieldReason[\"UNVERIFIED_IDENTITY\"] = 1] = \"UNVERIFIED_IDENTITY\";\n  /** \"Encrypted by a device not verified by its owner.\" */\n  EventShieldReason[EventShieldReason[\"UNSIGNED_DEVICE\"] = 2] = \"UNSIGNED_DEVICE\";\n  /** \"Encrypted by an unknown or deleted device.\" */\n  EventShieldReason[EventShieldReason[\"UNKNOWN_DEVICE\"] = 3] = \"UNKNOWN_DEVICE\";\n  /**\n   * \"The authenticity of this encrypted message can't be guaranteed on this device.\"\n   *\n   * ie: the key has been forwarded, or retrieved from an insecure backup.\n   */\n  EventShieldReason[EventShieldReason[\"AUTHENTICITY_NOT_GUARANTEED\"] = 4] = \"AUTHENTICITY_NOT_GUARANTEED\";\n  /**\n   * The (deprecated) sender_key field in the event does not match the Ed25519 key of the device that sent us the\n   * decryption keys.\n   *\n   * @deprecated The sender_key field is not checked by matrix-sdk-crypto, and this value is therefore unused since\n   * the migration to matrix-sdk-crypto in v37.0.0.\n   */\n  EventShieldReason[EventShieldReason[\"MISMATCHED_SENDER_KEY\"] = 5] = \"MISMATCHED_SENDER_KEY\";\n  /**\n   * The event was sent unencrypted in an encrypted room.\n   *\n   * @deprecated This has never been used. The fact it is here was due to a misunderstanding of the behaviour of\n   * `matrix-sdk-crypto`.\n   */\n  EventShieldReason[EventShieldReason[\"SENT_IN_CLEAR\"] = 6] = \"SENT_IN_CLEAR\";\n  /**\n   * The sender was previously verified but changed their identity.\n   */\n  EventShieldReason[EventShieldReason[\"VERIFICATION_VIOLATION\"] = 7] = \"VERIFICATION_VIOLATION\";\n  /**\n   * The `sender` field on the event does not match the owner of the device\n   * that established the Megolm session.\n   */\n  EventShieldReason[EventShieldReason[\"MISMATCHED_SENDER\"] = 8] = \"MISMATCHED_SENDER\";\n  return EventShieldReason;\n}({});\n\n/** The result of a call to {@link CryptoApi.getOwnDeviceKeys} */\n\n/**\n * Information about the encryption of a successfully decrypted to-device message.\n */\n\nexport * from \"./verification.js\";\nexport * from \"./recovery-key.js\";\nexport * from \"./key-passphrase.js\";\nexport * from \"./CryptoEvent.js\";\n//# sourceMappingURL=index.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\n/*\n * Copyright 2024 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// salt for HKDF, with 8 bytes of zeros\nvar zeroSalt = new Uint8Array(8);\n\n/**\n * Derive AES and HMAC keys from a master key.\n *\n * This is used for deriving secret storage keys: see https://spec.matrix.org/v1.11/client-server-api/#msecret_storagev1aes-hmac-sha2 (step 1).\n *\n * @param key\n * @param name\n */\nexport function deriveKeys(_x, _x2) {\n  return _deriveKeys.apply(this, arguments);\n}\nfunction _deriveKeys() {\n  _deriveKeys = _asyncToGenerator(function* (key, name) {\n    var hkdfkey = yield globalThis.crypto.subtle.importKey(\"raw\", key, {\n      name: \"HKDF\"\n    }, false, [\"deriveBits\"]);\n    var keybits = yield globalThis.crypto.subtle.deriveBits({\n      name: \"HKDF\",\n      salt: zeroSalt,\n      // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n      // @ts-ignore: https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/879\n      info: new TextEncoder().encode(name),\n      hash: \"SHA-256\"\n    }, hkdfkey, 512);\n    var aesKey = keybits.slice(0, 32);\n    var hmacKey = keybits.slice(32);\n    var aesProm = globalThis.crypto.subtle.importKey(\"raw\", aesKey, {\n      name: \"AES-CTR\"\n    }, false, [\"encrypt\", \"decrypt\"]);\n    var hmacProm = globalThis.crypto.subtle.importKey(\"raw\", hmacKey, {\n      name: \"HMAC\",\n      hash: {\n        name: \"SHA-256\"\n      }\n    }, false, [\"sign\", \"verify\"]);\n    return Promise.all([aesProm, hmacProm]);\n  });\n  return _deriveKeys.apply(this, arguments);\n}\n//# sourceMappingURL=deriveKeys.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\n/*\n * Copyright 2024 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { decodeBase64, encodeBase64 } from \"../base64.js\";\nimport { deriveKeys } from \"./internal/deriveKeys.js\";\n/**\n * Encrypt a string as a secret storage item, using AES-CTR.\n *\n * @param data - the plaintext to encrypt\n * @param key - the encryption key to use as an input to the HKDF function which is used to derive the AES key for\n *    encryption. Obviously, the same key must be provided when decrypting.\n * @param name - the name of the secret. Used as an input to the HKDF operation which is used to derive the AES key,\n *    so again the same value must be provided when decrypting.\n * @param ivStr - the base64-encoded initialization vector to use. If not supplied, a random one will be generated.\n *\n * @returns The encrypted result, including the ciphertext itself, the initialization vector (as supplied in `ivStr`,\n *   or generated), and an HMAC on the ciphertext — all base64-encoded.\n */\nexport default function encryptAESSecretStorageItem(_x, _x2, _x3, _x4) {\n  return _encryptAESSecretStorageItem.apply(this, arguments);\n}\nfunction _encryptAESSecretStorageItem() {\n  _encryptAESSecretStorageItem = _asyncToGenerator(function* (data, key, name, ivStr) {\n    var iv;\n    if (ivStr) {\n      iv = decodeBase64(ivStr);\n    } else {\n      iv = new Uint8Array(16);\n      globalThis.crypto.getRandomValues(iv);\n\n      // clear bit 63 of the IV to stop us hitting the 64-bit counter boundary\n      // (which would mean we wouldn't be able to decrypt on Android). The loss\n      // of a single bit of iv is a price we have to pay.\n      iv[8] &= 0x7f;\n    }\n    var [aesKey, hmacKey] = yield deriveKeys(key, name);\n    var encodedData = new TextEncoder().encode(data);\n    var ciphertext = yield globalThis.crypto.subtle.encrypt({\n      name: \"AES-CTR\",\n      counter: iv,\n      length: 64\n    }, aesKey, encodedData);\n    var hmac = yield globalThis.crypto.subtle.sign({\n      name: \"HMAC\"\n    }, hmacKey, ciphertext);\n    return {\n      iv: encodeBase64(iv),\n      ciphertext: encodeBase64(new Uint8Array(ciphertext)),\n      mac: encodeBase64(new Uint8Array(hmac))\n    };\n  });\n  return _encryptAESSecretStorageItem.apply(this, arguments);\n}\n//# sourceMappingURL=encryptAESSecretStorageItem.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\n/*\n * Copyright 2024 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { decodeBase64 } from \"../base64.js\";\nimport { deriveKeys } from \"./internal/deriveKeys.js\";\n/**\n * Decrypt an AES-encrypted Secret Storage item.\n *\n * @param data - the encrypted data, returned by {@link utils/encryptAESSecretStorageItem.default | encryptAESSecretStorageItem}.\n * @param key - the encryption key to use as an input to the HKDF function which is used to derive the AES key. Must\n *    be the same as provided to {@link utils/encryptAESSecretStorageItem.default | encryptAESSecretStorageItem}.\n * @param name - the name of the secret. Also used as an input to the HKDF operation which is used to derive the AES\n *    key, so again must be the same as provided to {@link utils/encryptAESSecretStorageItem.default | encryptAESSecretStorageItem}.\n */\nexport default function decryptAESSecretStorageItem(_x, _x2, _x3) {\n  return _decryptAESSecretStorageItem.apply(this, arguments);\n}\nfunction _decryptAESSecretStorageItem() {\n  _decryptAESSecretStorageItem = _asyncToGenerator(function* (data, key, name) {\n    var [aesKey, hmacKey] = yield deriveKeys(key, name);\n    var ciphertext = decodeBase64(data.ciphertext);\n    if (!(yield globalThis.crypto.subtle.verify({\n      name: \"HMAC\"\n    }, hmacKey, decodeBase64(data.mac), ciphertext))) {\n      throw new Error(\"Error decrypting secret \".concat(name, \": bad MAC\"));\n    }\n    var plaintext = yield globalThis.crypto.subtle.decrypt({\n      name: \"AES-CTR\",\n      counter: decodeBase64(data.iv),\n      length: 64\n    }, aesKey, ciphertext);\n    return new TextDecoder().decode(new Uint8Array(plaintext));\n  });\n  return _decryptAESSecretStorageItem.apply(this, arguments);\n}\n//# sourceMappingURL=decryptAESSecretStorageItem.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\n/*\nCopyright 2021-2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Implementation of server-side secret storage\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#storage\n */\n\nimport { ClientEvent } from \"./client.js\";\nimport { secureRandomString } from \"./randomstring.js\";\nimport { logger } from \"./logger.js\";\nimport encryptAESSecretStorageItem from \"./utils/encryptAESSecretStorageItem.js\";\nimport decryptAESSecretStorageItem from \"./utils/decryptAESSecretStorageItem.js\";\nexport var SECRET_STORAGE_ALGORITHM_V1_AES = \"m.secret_storage.v1.aes-hmac-sha2\";\n\n/**\n * Common base interface for Secret Storage Keys.\n *\n * The common properties for all encryption keys used in server-side secret storage.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#key-storage\n */\n\n/**\n * Properties for a SSSS key using the `m.secret_storage.v1.aes-hmac-sha2` algorithm.\n *\n * Corresponds to `AesHmacSha2KeyDescription` in the specification.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#msecret_storagev1aes-hmac-sha2\n */\n\n/**\n * Union type for secret storage keys.\n *\n * For now, this is only {@link SecretStorageKeyDescriptionAesV1}, but other interfaces may be added in future.\n */\n\n/**\n * Information on how to generate the key from a passphrase.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#deriving-keys-from-passphrases\n */\n\n/**\n * Options for {@link ServerSideSecretStorageImpl#addKey}.\n */\n\n/**\n * Return type for {@link ServerSideSecretStorageImpl#getKey}.\n */\n\n/**\n * Return type for {@link ServerSideSecretStorageImpl#addKey}.\n */\n\n/** Interface for managing account data on the server.\n *\n * A subset of {@link MatrixClient}.\n */\n\n/**\n *  Application callbacks for use with {@link SecretStorage.ServerSideSecretStorageImpl}\n */\n\n/**\n * Account Data event types which can store secret-storage-encrypted information.\n */\n\n/**\n * Account Data event content type for storing secret-storage-encrypted information.\n *\n * See https://spec.matrix.org/v1.13/client-server-api/#msecret_storagev1aes-hmac-sha2-1\n */\n\n/**\n * Interface provided by SecretStorage implementations\n *\n * Normally this will just be an {@link ServerSideSecretStorageImpl}, but for backwards\n * compatibility some methods allow other implementations.\n */\n\n/**\n * Implementation of Server-side secret storage.\n *\n * Secret *sharing* is *not* implemented here: this class is strictly about the storage component of\n * SSSS.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#storage\n */\nexport class ServerSideSecretStorageImpl {\n  /**\n   * Construct a new `SecretStorage`.\n   *\n   * Normally, it is unnecessary to call this directly, since MatrixClient automatically constructs one.\n   * However, it may be useful to construct a new `SecretStorage`, if custom `callbacks` are required, for example.\n   *\n   * @param accountDataAdapter - interface for fetching and setting account data on the server. Normally an instance\n   *   of {@link MatrixClient}.\n   * @param callbacks - application level callbacks for retrieving secret keys\n   */\n  constructor(accountDataAdapter, callbacks) {\n    this.accountDataAdapter = accountDataAdapter;\n    this.callbacks = callbacks;\n  }\n\n  /**\n   * Get the current default key ID for encrypting secrets.\n   *\n   * @returns The default key ID or null if no default key ID is set\n   */\n  getDefaultKeyId() {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      var _defaultKey$key;\n      var defaultKey = yield _this.accountDataAdapter.getAccountDataFromServer(\"m.secret_storage.default_key\");\n      if (!defaultKey) return null;\n      return (_defaultKey$key = defaultKey.key) !== null && _defaultKey$key !== void 0 ? _defaultKey$key : null;\n    })();\n  }\n\n  /**\n   * Implementation of {@link ServerSideSecretStorage#setDefaultKeyId}.\n   */\n  setDefaultKeyId(keyId) {\n    return new Promise((resolve, reject) => {\n      var listener = ev => {\n        if (ev.getType() !== \"m.secret_storage.default_key\") {\n          //  Different account data item\n          return;\n        }\n\n        // If keyId === null, the content should be an empty object.\n        // Otherwise, the `key` in the content object should match keyId.\n        var content = ev.getContent();\n        var isSameKey = keyId === null ? Object.keys(content).length === 0 : content.key === keyId;\n        if (isSameKey) {\n          this.accountDataAdapter.removeListener(ClientEvent.AccountData, listener);\n          resolve();\n        }\n      };\n      this.accountDataAdapter.on(ClientEvent.AccountData, listener);\n\n      // The spec [1] says that the value of the account data entry should be an object with a `key` property.\n      // It doesn't specify how to delete the default key; we do it by setting the account data to an empty object.\n      //\n      // [1]: https://spec.matrix.org/v1.13/client-server-api/#key-storage\n      var newValue = keyId === null ? {} : {\n        key: keyId\n      };\n      this.accountDataAdapter.setAccountData(\"m.secret_storage.default_key\", newValue).catch(e => {\n        this.accountDataAdapter.removeListener(ClientEvent.AccountData, listener);\n        reject(e);\n      });\n    });\n  }\n\n  /**\n   * Add a key for encrypting secrets.\n   *\n   * @param algorithm - the algorithm used by the key.\n   * @param opts - the options for the algorithm.  The properties used\n   *     depend on the algorithm given.\n   * @param keyId - the ID of the key.  If not given, a random\n   *     ID will be generated.\n   *\n   * @returns An object with:\n   *     keyId: the ID of the key\n   *     keyInfo: details about the key (iv, mac, passphrase)\n   */\n  addKey(algorithm, opts, keyId) {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      if (algorithm !== SECRET_STORAGE_ALGORITHM_V1_AES) {\n        throw new Error(\"Unknown key algorithm \".concat(algorithm));\n      }\n      var keyInfo = {\n        algorithm\n      };\n      if (opts.name) {\n        keyInfo.name = opts.name;\n      }\n      if (opts.passphrase) {\n        keyInfo.passphrase = opts.passphrase;\n      }\n      var {\n        iv,\n        mac\n      } = yield calculateKeyCheck(opts.key);\n      keyInfo.iv = iv;\n      keyInfo.mac = mac;\n\n      // Create a unique key id. XXX: this is racey.\n      if (!keyId) {\n        do {\n          keyId = secureRandomString(32);\n        } while (yield _this2.accountDataAdapter.getAccountDataFromServer(\"m.secret_storage.key.\".concat(keyId)));\n      }\n      yield _this2.accountDataAdapter.setAccountData(\"m.secret_storage.key.\".concat(keyId), keyInfo);\n      return {\n        keyId,\n        keyInfo\n      };\n    })();\n  }\n\n  /**\n   * Get the key information for a given ID.\n   *\n   * @param keyId - The ID of the key to check\n   *     for. Defaults to the default key ID if not provided.\n   * @returns If the key was found, the return value is an array of\n   *     the form [keyId, keyInfo].  Otherwise, null is returned.\n   *     XXX: why is this an array when addKey returns an object?\n   */\n  getKey(keyId) {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      if (!keyId) {\n        keyId = yield _this3.getDefaultKeyId();\n      }\n      if (!keyId) {\n        return null;\n      }\n      var keyInfo = yield _this3.accountDataAdapter.getAccountDataFromServer(\"m.secret_storage.key.\".concat(keyId));\n      return keyInfo ? [keyId, keyInfo] : null;\n    })();\n  }\n\n  /**\n   * Check whether we have a key with a given ID.\n   *\n   * @param keyId - The ID of the key to check\n   *     for. Defaults to the default key ID if not provided.\n   * @returns Whether we have the key.\n   */\n  hasKey(keyId) {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      var key = yield _this4.getKey(keyId);\n      return Boolean(key);\n    })();\n  }\n\n  /**\n   * Check whether a key matches what we expect based on the key info\n   *\n   * @param key - the key to check\n   * @param info - the key info\n   *\n   * @returns whether or not the key matches\n   */\n  checkKey(key, info) {\n    return _asyncToGenerator(function* () {\n      if (info.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n        if (info.mac) {\n          var {\n            mac\n          } = yield calculateKeyCheck(key, info.iv);\n          return trimTrailingEquals(info.mac) === trimTrailingEquals(mac);\n        } else {\n          // if we have no information, we have to assume the key is right\n          return true;\n        }\n      } else {\n        throw new Error(\"Unknown algorithm\");\n      }\n    })();\n  }\n\n  /**\n   * Implementation of {@link ServerSideSecretStorage#store}.\n   */\n  store(name, secret, keys) {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      if (secret === null) {\n        // remove secret\n        yield _this5.accountDataAdapter.setAccountData(name, {});\n        return;\n      }\n      var encrypted = {};\n      if (!keys) {\n        var defaultKeyId = yield _this5.getDefaultKeyId();\n        if (!defaultKeyId) {\n          throw new Error(\"No keys specified and no default key present\");\n        }\n        keys = [defaultKeyId];\n      }\n      if (keys.length === 0) {\n        throw new Error(\"Zero keys given to encrypt with!\");\n      }\n      for (var _keyId of keys) {\n        // get key information from key storage\n        var _keyInfo = yield _this5.accountDataAdapter.getAccountDataFromServer(\"m.secret_storage.key.\".concat(_keyId));\n        if (!_keyInfo) {\n          throw new Error(\"Unknown key: \" + _keyId);\n        }\n\n        // encrypt secret, based on the algorithm\n        if (_keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n          var _keys = {\n            [_keyId]: _keyInfo\n          };\n          var [, encryption] = yield _this5.getSecretStorageKey(_keys, name);\n          encrypted[_keyId] = yield encryption.encrypt(secret);\n        } else {\n          logger.warn(\"unknown algorithm for secret storage key \" + _keyId + \": \" + _keyInfo.algorithm);\n          // do nothing if we don't understand the encryption algorithm\n        }\n      }\n\n      // save encrypted secret\n      yield _this5.accountDataAdapter.setAccountData(name, {\n        encrypted\n      });\n    })();\n  }\n\n  /**\n   * Get a secret from storage, and decrypt it.\n   *\n   * {@link SecretStorageCallbacks#getSecretStorageKey} will be called to obtain a secret storage\n   * key to decrypt the secret.\n   *\n   * @param name - the name of the secret - i.e., the \"event type\" stored in the account data\n   *\n   * @returns the decrypted contents of the secret, or \"undefined\" if `name` is not found in\n   *    the user's account data.\n   */\n  get(name) {\n    var _this6 = this;\n    return _asyncToGenerator(function* () {\n      var secretInfo = yield _this6.accountDataAdapter.getAccountDataFromServer(name);\n      if (!secretInfo) {\n        return;\n      }\n      if (!secretInfo.encrypted) {\n        throw new Error(\"Content is not encrypted!\");\n      }\n\n      // get possible keys to decrypt\n      var keys = {};\n      for (var _keyId2 of Object.keys(secretInfo.encrypted)) {\n        // get key information from key storage\n        var _keyInfo2 = yield _this6.accountDataAdapter.getAccountDataFromServer(\"m.secret_storage.key.\".concat(_keyId2));\n        var _encInfo = secretInfo.encrypted[_keyId2];\n        // only use keys we understand the encryption algorithm of\n        if ((_keyInfo2 === null || _keyInfo2 === void 0 ? void 0 : _keyInfo2.algorithm) === SECRET_STORAGE_ALGORITHM_V1_AES) {\n          if (_encInfo.iv && _encInfo.ciphertext && _encInfo.mac) {\n            keys[_keyId2] = _keyInfo2;\n          }\n        }\n      }\n      if (Object.keys(keys).length === 0) {\n        throw new Error(\"Could not decrypt \".concat(name, \" because none of \") + \"the keys it is encrypted with are for a supported algorithm\");\n      }\n\n      // fetch private key from app\n      var [keyId, decryption] = yield _this6.getSecretStorageKey(keys, name);\n      var encInfo = secretInfo.encrypted[keyId];\n      return decryption.decrypt(encInfo);\n    })();\n  }\n\n  /**\n   * Check if a secret is stored on the server.\n   *\n   * @param name - the name of the secret\n   *\n   * @returns map of key name to key info the secret is encrypted\n   *     with, or null if it is not present or not encrypted with a trusted\n   *     key\n   */\n  isStored(name) {\n    var _this7 = this;\n    return _asyncToGenerator(function* () {\n      // check if secret exists\n      var secretInfo = yield _this7.accountDataAdapter.getAccountDataFromServer(name);\n      if (!(secretInfo !== null && secretInfo !== void 0 && secretInfo.encrypted)) return null;\n      var ret = {};\n\n      // filter secret encryption keys with supported algorithm\n      for (var _keyId3 of Object.keys(secretInfo.encrypted)) {\n        // get key information from key storage\n        var _keyInfo3 = yield _this7.accountDataAdapter.getAccountDataFromServer(\"m.secret_storage.key.\".concat(_keyId3));\n        if (!_keyInfo3) continue;\n        var encInfo = secretInfo.encrypted[_keyId3];\n\n        // only use keys we understand the encryption algorithm of\n        if (_keyInfo3.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n          if (encInfo.iv && encInfo.ciphertext && encInfo.mac) {\n            ret[_keyId3] = _keyInfo3;\n          }\n        }\n      }\n      return Object.keys(ret).length ? ret : null;\n    })();\n  }\n  getSecretStorageKey(keys, name) {\n    var _this8 = this;\n    return _asyncToGenerator(function* () {\n      if (!_this8.callbacks.getSecretStorageKey) {\n        throw new Error(\"No getSecretStorageKey callback supplied\");\n      }\n      var returned = yield _this8.callbacks.getSecretStorageKey({\n        keys\n      }, name);\n      if (!returned) {\n        throw new Error(\"getSecretStorageKey callback returned falsey\");\n      }\n      if (returned.length < 2) {\n        throw new Error(\"getSecretStorageKey callback returned invalid data\");\n      }\n      var [keyId, privateKey] = returned;\n      if (!keys[keyId]) {\n        throw new Error(\"App returned unknown key from getSecretStorageKey!\");\n      }\n      if (keys[keyId].algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n        var decryption = {\n          encrypt: function encrypt(secret) {\n            return encryptAESSecretStorageItem(secret, privateKey, name);\n          },\n          decrypt: function decrypt(encInfo) {\n            return decryptAESSecretStorageItem(encInfo, privateKey, name);\n          }\n        };\n        return [keyId, decryption];\n      } else {\n        throw new Error(\"Unknown key type: \" + keys[keyId].algorithm);\n      }\n    })();\n  }\n}\n\n/** trim trailing instances of '=' from a string\n *\n * @internal\n *\n * @param input - input string\n */\nexport function trimTrailingEquals(input) {\n  // according to Sonar and CodeQL, a regex such as /=+$/ is superlinear.\n  // Not sure I believe it, but it's easy enough to work around.\n\n  // find the number of characters before the trailing =\n  var i = input.length;\n  while (i >= 1 && input.charCodeAt(i - 1) == 0x3d) i--;\n\n  // trim to the calculated length\n  if (i < input.length) {\n    return input.substring(0, i);\n  } else {\n    return input;\n  }\n}\n\n// string of zeroes, for calculating the key check\nvar ZERO_STR = \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Calculate the MAC for checking the key.\n * See https://spec.matrix.org/v1.11/client-server-api/#msecret_storagev1aes-hmac-sha2, steps 3 and 4.\n *\n * @param key - the key to use\n * @param iv - The initialization vector as a base64-encoded string.\n *     If omitted, a random initialization vector will be created.\n * @returns An object that contains, `mac` and `iv` properties.\n */\nexport function calculateKeyCheck(key, iv) {\n  return encryptAESSecretStorageItem(ZERO_STR, key, \"\", iv);\n}\n//# sourceMappingURL=secret-storage.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\n/*\nCopyright 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Computes a SHA-256 hash of a string (after utf-8 encoding) and returns it as an ArrayBuffer.\n *\n * @param plaintext The string to hash\n * @returns An Uint8Array containing the SHA-256 hash of the input string\n * @throws If the subtle crypto API is not available, for example if the code is running\n *         in a web page with an insecure context (eg. served over plain HTTP).\n */\nexport function sha256(_x) {\n  return _sha.apply(this, arguments);\n}\nfunction _sha() {\n  _sha = _asyncToGenerator(function* (plaintext) {\n    if (!globalThis.crypto.subtle) {\n      throw new Error(\"Crypto.subtle is not available: insecure context?\");\n    }\n    var utf8 = new TextEncoder().encode(plaintext);\n    var digest = yield globalThis.crypto.subtle.digest(\"SHA-256\", utf8);\n    return new Uint8Array(digest);\n  });\n  return _sha.apply(this, arguments);\n}\n//# sourceMappingURL=digest.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MXID_PATTERN } from \"../models/room-member.js\";\nimport { deepCompare } from \"../utils.js\";\nimport { slotDescriptionToId, slotIdToDescription } from \"./MatrixRTCSession.js\";\nimport { sha256 } from \"../digest.js\";\nimport { encodeUnpaddedBase64 } from \"../base64.js\";\n/**\n * The default duration in milliseconds that a membership is considered valid for.\n * Ordinarily the client responsible for the session will update the membership before it expires.\n * We use this duration as the fallback case where stale sessions are present for some reason.\n */\nexport var DEFAULT_EXPIRE_DURATION = 1000 * 60 * 60 * 4;\nvar checkRtcMembershipData = (data, errors, referenceUserId) => {\n  var _data$sticky_key;\n  var prefix = \" - \";\n\n  // required fields\n  if (typeof data.slot_id !== \"string\") {\n    errors.push(prefix + \"slot_id must be string\");\n  } else {\n    if (data.slot_id.split(\"#\").length !== 2) errors.push(prefix + 'slot_id must include exactly one \"#\"');\n  }\n  if (typeof data.member !== \"object\" || data.member === null) {\n    errors.push(prefix + \"member must be an object\");\n  } else {\n    if (typeof data.member.user_id !== \"string\") errors.push(prefix + \"member.user_id must be string\");else if (!MXID_PATTERN.test(data.member.user_id)) errors.push(prefix + \"member.user_id must be a valid mxid\");\n    // This is not what the spec enforces but there currently are no rules what power levels are required to\n    // send a m.rtc.member event for a other user. So we add this check for simplicity and to avoid possible attacks until there\n    // is a proper definition when this is allowed.\n    else if (data.member.user_id !== referenceUserId) errors.push(prefix + \"member.user_id must match the sender\");\n    if (typeof data.member.device_id !== \"string\") errors.push(prefix + \"member.device_id must be string\");\n    if (typeof data.member.id !== \"string\") errors.push(prefix + \"member.id must be string\");\n  }\n  if (typeof data.application !== \"object\" || data.application === null) {\n    errors.push(prefix + \"application must be an object\");\n  } else {\n    if (typeof data.application.type !== \"string\") {\n      errors.push(prefix + \"application.type must be a string\");\n    } else {\n      if (data.application.type.includes(\"#\")) errors.push(prefix + 'application.type must not include \"#\"');\n    }\n  }\n  if (data.rtc_transports === undefined || !Array.isArray(data.rtc_transports)) {\n    errors.push(prefix + \"rtc_transports must be an array\");\n  } else {\n    // validate that each transport has at least a string 'type'\n    for (var t of data.rtc_transports) {\n      if (typeof t !== \"object\" || t === null || typeof t.type !== \"string\") {\n        errors.push(prefix + \"rtc_transports entries must be objects with a string type\");\n        break;\n      }\n    }\n  }\n  if (data.versions === undefined || !Array.isArray(data.versions)) {\n    errors.push(prefix + \"versions must be an array\");\n  } else if (!data.versions.every(v => typeof v === \"string\")) {\n    errors.push(prefix + \"versions must be an array of strings\");\n  }\n\n  // optional fields\n  if (((_data$sticky_key = data.sticky_key) !== null && _data$sticky_key !== void 0 ? _data$sticky_key : data.msc4354_sticky_key) === undefined) {\n    errors.push(prefix + \"sticky_key or msc4354_sticky_key must be a defined\");\n  }\n  if (data.sticky_key !== undefined && typeof data.sticky_key !== \"string\") {\n    errors.push(prefix + \"sticky_key must be a string\");\n  }\n  if (data.msc4354_sticky_key !== undefined && typeof data.msc4354_sticky_key !== \"string\") {\n    errors.push(prefix + \"msc4354_sticky_key must be a string\");\n  }\n  if (data.sticky_key !== undefined && data.msc4354_sticky_key !== undefined && data.sticky_key !== data.msc4354_sticky_key) {\n    errors.push(prefix + \"sticky_key and msc4354_sticky_key must be equal if both are defined\");\n  }\n  if (data[\"m.relates_to\"] !== undefined) {\n    var rel = data[\"m.relates_to\"];\n    if (typeof rel !== \"object\" || rel === null) {\n      errors.push(prefix + \"m.relates_to must be an object if provided\");\n    } else {\n      if (typeof rel.event_id !== \"string\") errors.push(prefix + \"m.relates_to.event_id must be a string\");\n      if (rel.rel_type !== \"m.reference\") errors.push(prefix + \"m.relates_to.rel_type must be m.reference\");\n    }\n  }\n  return errors.length === 0;\n};\n\n/**\n * MSC4143 (MatrixRTC) session membership data.\n * Represents the `session` in the memberships section of an m.call.member event as it is on the wire.\n **/\n\nvar checkSessionsMembershipData = (data, errors) => {\n  var _data$focus_active;\n  var prefix = \" - \";\n  if (typeof data.device_id !== \"string\") errors.push(prefix + \"device_id must be string\");\n  if (typeof data.call_id !== \"string\") errors.push(prefix + \"call_id must be string\");\n  if (typeof data.application !== \"string\") errors.push(prefix + \"application must be a string\");\n  if (typeof ((_data$focus_active = data.focus_active) === null || _data$focus_active === void 0 ? void 0 : _data$focus_active.type) !== \"string\") errors.push(prefix + \"focus_active.type must be a string\");\n  if (data.focus_active === undefined) {\n    errors.push(prefix + \"focus_active has an invalid type\");\n  }\n  if (data.foci_preferred !== undefined && !(Array.isArray(data.foci_preferred) && data.foci_preferred.every(f => typeof f === \"object\" && f !== null && typeof f.type === \"string\"))) {\n    errors.push(prefix + \"foci_preferred must be an array of transport objects\");\n  }\n  // optional parameters\n  if (data.created_ts !== undefined && typeof data.created_ts !== \"number\") {\n    errors.push(prefix + \"created_ts must be number\");\n  }\n\n  // application specific data (we first need to check if they exist)\n  if (data.scope !== undefined && typeof data.scope !== \"string\") errors.push(prefix + \"scope must be string\");\n  if (data[\"m.call.intent\"] !== undefined && typeof data[\"m.call.intent\"] !== \"string\") {\n    errors.push(prefix + \"m.call.intent must be a string\");\n  }\n  return errors.length === 0;\n};\n// TODO: Rename to RtcMembership once we removed the legacy SessionMembership from this file.\nexport class CallMembership {\n  static equal(a, b) {\n    return deepCompare(a === null || a === void 0 ? void 0 : a.membershipData, b === null || b === void 0 ? void 0 : b.membershipData);\n  }\n  constructor(/** The required parts of the Matrix event that this membership is based on */\n  matrixEvent,\n  /**\n   * The type checked membership data {data: (content of the matrix event), kind: (type hint)}\n   *\n   */\n  membershipData,\n  /**\n   *\n   * Anonymized identity to use with the RTC backend.\n   *\n   * The rtcBackendIdentity is a hashed version of all the identity parts:\n   * `sha256(${this.userId}|${this.deviceId}|${this.memberId})`\n   *\n   * It is used to anonymize the identity of the user in the RTC backend.\n   */\n  rtcBackendIdentity,\n  /**\n   * The constructor will automatically create a properly tagged child logger instance.\n   */\n  logger) {\n    this.membershipData = membershipData;\n    this.rtcBackendIdentity = rtcBackendIdentity;\n    _defineProperty(this, \"logger\", void 0);\n    /** The parsed data from the Matrix event.\n     * To access checked eventId and sender from the matrixEvent.\n     * Class construction will fail if these values cannot get obtained. */\n    _defineProperty(this, \"matrixEventData\", void 0);\n    var [eventId, sender, ts] = [matrixEvent.getId(), matrixEvent.getSender(), matrixEvent.getTs()];\n    if (eventId === undefined) throw new Error(\"parentEvent is missing eventId field\");\n    if (sender === undefined) throw new Error(\"parentEvent is missing sender field\");\n    this.matrixEventData = {\n      eventId,\n      sender,\n      ts\n    };\n    this.logger = logger === null || logger === void 0 ? void 0 : logger.getChild(\"[CallMembership \".concat(sender, \":\").concat(this.deviceId, \"]\"));\n  }\n\n  /**\n   * sha256(`${this.userId}|${this.deviceId}|${this.memberId}`) for sticky events (kind = rtc)\n   * `${this.userId}:${this.deviceId}` for state events (kind = session)\n   */\n  static computeRtcBackendIdentity(matrixEvent, membershipData) {\n    return _asyncToGenerator(function* () {\n      var {\n        kind,\n        data\n      } = membershipData;\n      switch (kind) {\n        case \"rtc\":\n          {\n            return CallMembership.computeRtcIdentityRaw(data.member.user_id, data.member.device_id, data.member.id);\n          }\n        case \"session\":\n          return \"\".concat(matrixEvent.getSender(), \":\").concat(data.device_id);\n      }\n    })();\n  }\n  static computeRtcIdentityRaw(userId, deviceId, memberId) {\n    return _asyncToGenerator(function* () {\n      return encodeUnpaddedBase64(yield sha256(\"\".concat(userId, \"|\").concat(deviceId, \"|\").concat(memberId)));\n    })();\n  }\n  static membershipDataFromMatrixEvent(matrixEvent) {\n    var [eventId, sender, content] = [matrixEvent.getId(), matrixEvent.getSender(), matrixEvent.getContent()];\n    if (eventId === undefined) throw new Error(\"parentEvent is missing eventId field\");\n    if (sender === undefined) throw new Error(\"parentEvent is missing sender field\");\n    var sessionErrors = [];\n    var rtcErrors = [];\n    if (checkSessionsMembershipData(content, sessionErrors)) {\n      return {\n        kind: \"session\",\n        data: content\n      };\n    } else if (checkRtcMembershipData(content, rtcErrors, sender)) {\n      return {\n        kind: \"rtc\",\n        data: content\n      };\n    } else {\n      var details = sessionErrors.length < rtcErrors.length ? \"Does not match MSC4143 m.call.member:\\n\".concat(sessionErrors.join(\"\\n\"), \"\\n\\n\") : \"Does not match MSC4143 m.rtc.member:\\n\".concat(rtcErrors.join(\"\\n\"), \"\\n\\n\");\n      var json = \"\\nevent:\\n\" + JSON.stringify(content).replaceAll('\"', \"'\");\n      throw Error(\"unknown CallMembership data.\\n\" + details + json);\n    }\n  }\n\n  /** @deprecated use userId instead */\n  get sender() {\n    return this.userId;\n  }\n  get userId() {\n    var {\n      kind,\n      data\n    } = this.membershipData;\n    switch (kind) {\n      case \"rtc\":\n        return data.member.user_id;\n      case \"session\":\n      default:\n        return this.matrixEventData.sender;\n    }\n  }\n  get eventId() {\n    return this.matrixEventData.eventId;\n  }\n\n  /**\n   * The ID of the MatrixRTC slot that this membership belongs to (format `{application}#{id}`).\n   * This is computed in case SessionMembershipData is used.\n   */\n  get slotId() {\n    var _this$logger2;\n    var {\n      kind,\n      data\n    } = this.membershipData;\n    if (data.application === \"m.call\") {\n      switch (kind) {\n        case \"rtc\":\n          return data.slot_id;\n        case \"session\":\n        default:\n          {\n            var [application, id] = [this.application, data.call_id];\n\n            // INFO_SLOT_ID_LEGACY_CASE  (search for all occurances of this INFO to get the full picture)\n            // The spec got changed to use `\"ROOM\"` instead of `\"\"` empyt string for the implicit default call.\n            // State events still are sent with `\"\"` however. To find other events that should end up in the same call,\n            // we use the slotId.\n            // Since the CallMembership is the public representation of a rtc.member event, we just pretend it is a\n            // \"ROOM\" slotId/call_id.\n            // This makes all the remote members work with just this simple trick.\n            //\n            // We of course now need to be careful when sending legacy events (state events)\n            // They get a slotDescription containing \"ROOM\" since this is what we use starting at the time this comment\n            // is commited.\n            //\n            // See the Other INFO_SLOT_ID_LEGACY_CASE comments to see where we revert back to \"\" just before sending the event.\n            var compatibilityAdaptedId;\n            if (id === \"\") {\n              var _this$logger;\n              compatibilityAdaptedId = \"ROOM\";\n              (_this$logger = this.logger) === null || _this$logger === void 0 || _this$logger.info(\"use slotId compat hack emptyString -> ROOM\");\n            } else {\n              compatibilityAdaptedId = id;\n            }\n            return slotDescriptionToId({\n              application,\n              id: compatibilityAdaptedId\n            });\n          }\n      }\n    }\n    (_this$logger2 = this.logger) === null || _this$logger2 === void 0 || _this$logger2.info(\"NOT using slotId compat hack emptyString -> ROOM\");\n    // This is what the function should look like for any other application that did not\n    // go through a `\"\"`=> `\"ROOM\"` rename\n    switch (kind) {\n      case \"rtc\":\n        return data.slot_id;\n      case \"session\":\n      default:\n        {\n          var [_application, _id] = [this.application, data.call_id];\n          return slotDescriptionToId({\n            application: _application,\n            id: _id\n          });\n        }\n    }\n  }\n  get deviceId() {\n    var {\n      kind,\n      data\n    } = this.membershipData;\n    switch (kind) {\n      case \"rtc\":\n        return data.member.device_id;\n      case \"session\":\n      default:\n        return data.device_id;\n    }\n  }\n  get callIntent() {\n    var {\n      kind,\n      data\n    } = this.membershipData;\n    switch (kind) {\n      case \"rtc\":\n        {\n          var _this$logger3;\n          var intent = data.application[\"m.call.intent\"];\n          if (typeof intent === \"string\") {\n            return intent;\n          }\n          (_this$logger3 = this.logger) === null || _this$logger3 === void 0 || _this$logger3.warn(\"RTC membership has invalid m.call.intent\");\n          return undefined;\n        }\n      case \"session\":\n      default:\n        return data[\"m.call.intent\"];\n    }\n  }\n\n  /**\n   * Parsed `slot_id` (format `{application}#{id}`) into its components (application and id).\n   */\n  get slotDescription() {\n    return slotIdToDescription(this.slotId);\n  }\n  get application() {\n    var {\n      kind,\n      data\n    } = this.membershipData;\n    switch (kind) {\n      case \"rtc\":\n        return data.application.type;\n      case \"session\":\n      default:\n        return data.application;\n    }\n  }\n  get applicationData() {\n    var {\n      kind,\n      data\n    } = this.membershipData;\n    switch (kind) {\n      case \"rtc\":\n        return data.application;\n      case \"session\":\n      default:\n        return {\n          \"type\": data.application,\n          \"m.call.intent\": data[\"m.call.intent\"]\n        };\n    }\n  }\n\n  /** @deprecated scope is not used and will be removed in future versions. replaced by application specific types.*/\n  get scope() {\n    var {\n      kind,\n      data\n    } = this.membershipData;\n    switch (kind) {\n      case \"rtc\":\n        return undefined;\n      case \"session\":\n      default:\n        return data.scope;\n    }\n  }\n  /**\n   * @deprecated renamed to `memberId`\n   */\n  get membershipID() {\n    return this.memberId;\n  }\n\n  /**\n   * This computes the membership ID for the membership.\n   * For the sticky event based rtcSessionData this is trivial it is `member.id`.\n   * This is not supposed to be used to identity on an rtc backend. This is just a nouance for\n   * a generated (sha256) anonymised identity. Only send `rtcBackendIdentity` to any rtc backend service.\n   *\n   * For the legacy sessionMemberEvents it is a bit more complex. Here we sometimes do not have this data\n   * in the event content and we expected the SFU and the client to use `${this.matrixEventData.sender}:${data.device_id}`.\n   *\n   * So if there is no membershipID we use the hard coded jwt id default (`${this.matrixEventData.sender}:${data.device_id}`)\n   * value (used until version 0.16.0)\n   *\n   * It is also possible for a session event to set a custom membershipID. in that case this will be used.\n   */\n  get memberId() {\n    var _data$membershipID;\n    // the createdTs behaves equivalent to the membershipID.\n    // we only need the field for the legacy member events where we needed to update them\n    // synapse ignores sending state events if they have the same content.\n    var {\n      kind,\n      data\n    } = this.membershipData;\n    switch (kind) {\n      case \"rtc\":\n        return data.member.id;\n      case \"session\":\n      default:\n        return (// best case we have a client already publishing the right custom membershipId\n          (_data$membershipID = data.membershipID) !== null && _data$membershipID !== void 0 ? _data$membershipID : // alternativly we use the hard coded jwt id defuatl value (used until version 0.16.0)\n          \"\".concat(this.matrixEventData.sender, \":\").concat(data.device_id)\n        );\n    }\n  }\n  createdTs() {\n    var _data$created_ts;\n    var {\n      kind,\n      data\n    } = this.membershipData;\n    switch (kind) {\n      case \"rtc\":\n        // TODO we need to read the referenced (relation) event if available to get the real created_ts\n        return this.matrixEventData.ts;\n      case \"session\":\n      default:\n        return (_data$created_ts = data.created_ts) !== null && _data$created_ts !== void 0 ? _data$created_ts : this.matrixEventData.ts;\n    }\n  }\n\n  /**\n   * Gets the absolute expiry timestamp of the membership.\n   * @returns The absolute expiry time of the membership as a unix timestamp in milliseconds or undefined if not applicable\n   */\n  getAbsoluteExpiry() {\n    var _data$expires;\n    var {\n      kind,\n      data\n    } = this.membershipData;\n    switch (kind) {\n      case \"rtc\":\n        return undefined;\n      case \"session\":\n      default:\n        // TODO: calculate this from the MatrixRTCSession join configuration directly\n        return this.createdTs() + ((_data$expires = data.expires) !== null && _data$expires !== void 0 ? _data$expires : DEFAULT_EXPIRE_DURATION);\n    }\n  }\n\n  /**\n   * @returns The number of milliseconds until the membership expires or undefined if applicable\n   */\n  getMsUntilExpiry() {\n    var {\n      kind\n    } = this.membershipData;\n    switch (kind) {\n      case \"rtc\":\n        return undefined;\n      case \"session\":\n      default:\n        // Assume that local clock is sufficiently in sync with other clocks in the distributed system.\n        // We used to try and adjust for the local clock being skewed, but there are cases where this is not accurate.\n        // The current implementation allows for the local clock to be -infinity to +MatrixRTCSession.MEMBERSHIP_EXPIRY_TIME/2\n        return this.getAbsoluteExpiry() - Date.now();\n    }\n  }\n\n  /**\n   * @returns true if the membership has expired, otherwise false\n   */\n  isExpired() {\n    var {\n      kind\n    } = this.membershipData;\n    switch (kind) {\n      case \"rtc\":\n        return false;\n      case \"session\":\n      default:\n        return this.getMsUntilExpiry() <= 0;\n    }\n  }\n\n  /**\n   * ## RTC Membership\n   * Gets the primary transport to use for this RTC membership (m.rtc.member).\n   * This will return the primary transport that is used by this call membership to publish their media.\n   * Directly relates to the `rtc_transports` field.\n   *\n   * ## Legacy session membership\n   * In case of a legacy session membership (m.call.member) this will return the selected transport where\n   * media is published. How this selection happens depends on the `focus_active` field of the session membership.\n   * If the `focus_selection` is `oldest_membership` this will return the transport of the oldest membership\n   * in the room (based on the `created_ts` field of the session membership).\n   * If the `focus_selection` is `multi_sfu` it will return the first transport of the `foci_preferred` list.\n   * (`multi_sfu` is equivalent to how `m.rtc.member` `rtc_transports` work).\n   * @param oldestMembership For backwards compatibility with session membership (legacy). Unused in case of RTC membership.\n   * Always required to make the consumer not care if it deals with RTC or session memberships.\n   * @returns The transport this membership uses to publish media or undefined if no transport is available.\n   */\n  getTransport(oldestMembership) {\n    var {\n      kind,\n      data\n    } = this.membershipData;\n    switch (kind) {\n      case \"rtc\":\n        return data.rtc_transports[0];\n      case \"session\":\n        switch (data.focus_active.focus_selection) {\n          case \"multi_sfu\":\n            return data.foci_preferred[0];\n          case \"oldest_membership\":\n            if (CallMembership.equal(this, oldestMembership)) return data.foci_preferred[0];\n            if (oldestMembership !== undefined) return oldestMembership.getTransport(oldestMembership);\n            break;\n        }\n    }\n    return undefined;\n  }\n\n  /**\n   * The focus_active filed of the session membership (m.call.member).\n   * @deprecated focus_active is not used and will be removed in future versions.\n   */\n  getFocusActive() {\n    var {\n      kind,\n      data\n    } = this.membershipData;\n    if (kind === \"session\") return data.focus_active;\n    return undefined;\n  }\n  /**\n   * The value of the `rtc_transports` field for RTC memberships (m.rtc.member).\n   * Or the value of the `foci_preferred` field for legacy session memberships (m.call.member).\n   */\n  get transports() {\n    var {\n      kind,\n      data\n    } = this.membershipData;\n    switch (kind) {\n      case \"rtc\":\n        return data.rtc_transports;\n      case \"session\":\n      default:\n        return data.foci_preferred;\n    }\n  }\n  get kind() {\n    return this.membershipData.kind;\n  }\n}\n//# sourceMappingURL=CallMembership.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * The mxID, deviceId and membership timestamp of a RTC session participant.\n */\n\n/**\n * A type representing the information needed to decrypt video streams.\n */\n\n/**\n * The information about the key used to encrypt video streams.\n */\n\n/**\n * THe content of a to-device event that contains encryption keys.\n */\n\n/**\n * @deprecated Use `RTCNotificationType` instead.\n */\n\n/**\n * @deprecated Use `IRTCNotificationContent` instead.\n */\n\n/**\n * Represents the intention of the call from the perspective of the sending user.\n * May be any string, although `\"audio\"` and `\"video\"` are commonly accepted values.\n */\n\n/**\n * This will check if the content has all the expected fields to be a valid IRTCNotificationContent.\n * It will also cap the lifetime to 90000ms (1.5 min) if a higher value is provided.\n * @param content\n * @throws if the content is invalid\n * @returns a parsed IRTCNotificationContent\n */\nexport function parseCallNotificationContent(content) {\n  if (content[\"m.mentions\"] && typeof content[\"m.mentions\"] !== \"object\") {\n    throw new Error(\"malformed m.mentions\");\n  }\n  if (typeof content[\"notification_type\"] !== \"string\") {\n    throw new Error(\"Missing or invalid notification_type\");\n  }\n  if (typeof content[\"sender_ts\"] !== \"number\") {\n    throw new Error(\"Missing or invalid sender_ts\");\n  }\n  if (typeof content[\"lifetime\"] !== \"number\") {\n    throw new Error(\"Missing or invalid lifetime\");\n  }\n  if (content[\"relation\"] && content[\"relation\"][\"rel_type\"] !== \"m.reference\") {\n    throw new Error(\"Invalid relation\");\n  }\n  if (content[\"m.call.intent\"] && typeof content[\"m.call.intent\"] !== \"string\") {\n    throw new Error(\"Invalid m.call.intent\");\n  }\n  var cappedLifetime = content[\"lifetime\"] >= 90000 ? 90000 : content[\"lifetime\"];\n  return _objectSpread(_objectSpread({}, content), {}, {\n    lifetime: cappedLifetime\n  });\n}\n\n/**\n * Interface for `org.matrix.msc4075.rtc.notification` events.\n * Don't cast event content to this directly. Use `parseCallNotificationContent` instead to validate the content first.\n */\n\n/**\n * MSC4310 decline event content for `org.matrix.msc4310.rtc.decline`.\n * Sent as a standard m.reference relation to an `org.matrix.msc4075.rtc.notification` event.\n */\n\nexport var Status = /*#__PURE__*/function (Status) {\n  Status[\"Disconnected\"] = \"Disconnected\";\n  Status[\"Connecting\"] = \"Connecting\";\n  Status[\"Connected\"] = \"Connected\";\n  Status[\"Disconnecting\"] = \"Disconnecting\";\n  Status[\"Unknown\"] = \"Unknown\";\n  return Status;\n}({});\n\n/**\n * A type collecting call encryption statistics for a session.\n */\n\nexport var isMyMembership = (m, userId, deviceId) => m.sender === userId && m.deviceId === deviceId;\n\n/**\n *  A RTC transport is a JSON object that describes how to connect to a RTC member.\n */\n//# sourceMappingURL=types.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nimport { logger as rootLogger } from \"../logger.js\";\nimport { sleep } from \"../utils.js\";\nimport { MembershipActionType } from \"./MembershipManager.js\";\n\n/** @internal */\n\n/** @internal */\n\n/**\n * This scheduler tracks the state of the current membership participation\n * and runs one central timer that wakes up a handler callback with the correct action + state\n * whenever necessary.\n *\n * It can also be awakened whenever a new action is added which is\n * earlier then the current \"next awake\".\n * @internal\n */\nexport class ActionScheduler {\n  constructor(/** This is the callback called for each scheduled action (`this.addAction()`) */\n  membershipLoopHandler, parentLogger) {\n    this.membershipLoopHandler = membershipLoopHandler;\n    _defineProperty(this, \"logger\", void 0);\n    /**\n     * This is tracking the state of the scheduler loop.\n     * Only used to prevent starting the loop twice.\n     */\n    _defineProperty(this, \"running\", false);\n    // function for the wakeup mechanism (in case we add an action externally and need to leave the current sleep)\n    _defineProperty(this, \"wakeup\", update => {\n      this.logger.error(\"Cannot call wakeup before calling `startWithJoin()`\");\n    });\n    _defineProperty(this, \"_actions\", []);\n    this.logger = (parentLogger !== null && parentLogger !== void 0 ? parentLogger : rootLogger).getChild(\"[NewMembershipActionScheduler]\");\n  }\n  get actions() {\n    return this._actions;\n  }\n\n  /**\n   * This starts the main loop of the membership manager that handles event sending, delayed event sending and delayed event restarting.\n   * @param initialActions The initial actions the manager will start with. It should be enough to pass: DelayedLeaveActionType.Initial\n   * @returns Promise that resolves once all actions have run and no more are scheduled.\n   * @throws This throws an error if one of the actions throws.\n   * In most other error cases the manager will try to handle any server errors by itself.\n   */\n  startWithJoin() {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      if (_this.running) {\n        _this.logger.error(\"Cannot call startWithJoin() on NewMembershipActionScheduler while already running\");\n        return;\n      }\n      _this.running = true;\n      _this._actions = [{\n        ts: Date.now(),\n        type: MembershipActionType.SendDelayedEvent\n      }];\n      try {\n        var _loop = function* _loop() {\n          // Sort so next (smallest ts) action is at the beginning\n          _this._actions.sort((a, b) => a.ts - b.ts);\n          var nextAction = _this._actions[0];\n          var wakeupUpdate = undefined;\n\n          // while we await for the next action, wakeup has to resolve the wakeupPromise\n          var wakeupPromise = new Promise(resolve => {\n            _this.wakeup = update => {\n              wakeupUpdate = update;\n              resolve();\n            };\n          });\n          if (nextAction.ts > Date.now()) yield Promise.race([wakeupPromise, sleep(nextAction.ts - Date.now())]);\n          var handlerResult = {};\n          if (!wakeupUpdate) {\n            _this.logger.debug(\"Current MembershipManager processing: \".concat(nextAction.type, \"\\nQueue:\"), _this._actions, \"\\nDate.now: \\\"\".concat(Date.now()));\n            try {\n              // `this.wakeup` can also be called and sets the `wakeupUpdate` object while we are in the handler.\n              handlerResult = yield _this.membershipLoopHandler(nextAction.type);\n            } catch (e) {\n              throw Error(\"The MembershipManager shut down because of the end condition: \".concat(e));\n            }\n          }\n          // remove the processed action only after we are done processing\n          _this._actions.splice(0, 1);\n          // The wakeupUpdate always wins since that is a direct external update.\n          var actionUpdate = wakeupUpdate !== null && wakeupUpdate !== void 0 ? wakeupUpdate : handlerResult;\n          if (\"replace\" in actionUpdate) {\n            _this._actions = actionUpdate.replace;\n          } else if (\"insert\" in actionUpdate) {\n            _this._actions.push(...actionUpdate.insert);\n          }\n        };\n        while (_this._actions.length > 0) {\n          yield* _loop();\n        }\n      } finally {\n        // Set the rtc session running state since we cannot recover from here and the consumer user of the\n        // MatrixRTCSession class needs to manually rejoin.\n        _this.running = false;\n      }\n      _this.logger.debug(\"Leave MembershipManager ActionScheduler loop (no more actions)\");\n    })();\n  }\n  initiateJoin() {\n    var _this$wakeup;\n    (_this$wakeup = this.wakeup) === null || _this$wakeup === void 0 || _this$wakeup.call(this, {\n      replace: [{\n        ts: Date.now(),\n        type: MembershipActionType.SendDelayedEvent\n      }]\n    });\n  }\n  initiateLeave() {\n    var _this$wakeup2;\n    (_this$wakeup2 = this.wakeup) === null || _this$wakeup2 === void 0 || _this$wakeup2.call(this, {\n      replace: [{\n        ts: Date.now(),\n        type: MembershipActionType.SendScheduledDelayedLeaveEvent\n      }]\n    });\n  }\n}\n//# sourceMappingURL=MembershipManagerActionScheduler.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport var InvalidCryptoStoreState = /*#__PURE__*/function (InvalidCryptoStoreState) {\n  InvalidCryptoStoreState[\"TooNew\"] = \"TOO_NEW\";\n  return InvalidCryptoStoreState;\n}({});\nexport class InvalidCryptoStoreError extends Error {\n  constructor(reason) {\n    var message = \"Crypto store is invalid because \".concat(reason, \", \") + \"please stop the client, delete all data and start the client again\";\n    super(message);\n    this.reason = reason;\n    this.name = \"InvalidCryptoStoreError\";\n  }\n}\n_defineProperty(InvalidCryptoStoreError, \"TOO_NEW\", InvalidCryptoStoreState.TooNew);\nexport class KeySignatureUploadError extends Error {\n  constructor(message, value) {\n    super(message);\n    this.value = value;\n  }\n}\n\n/**\n * It is invalid to call most methods once {@link MatrixClient#stopClient} has been called.\n *\n * This error will be thrown if you attempt to do so.\n *\n * {@link MatrixClient#stopClient} itself is an exception to this: it may safely be called multiple times on the same\n * instance.\n */\nexport class ClientStoppedError extends Error {\n  constructor() {\n    super(\"MatrixClient has been stopped\");\n  }\n}\n\n/**\n * This error is thrown when the Homeserver does not support the delayed events endpoints.\n */\nexport class UnsupportedDelayedEventsEndpointError extends Error {\n  constructor(message, clientEndpoint) {\n    super(message);\n    this.clientEndpoint = clientEndpoint;\n    this.name = \"UnsupportedDelayedEventsEndpointError\";\n  }\n}\n\n/**\n * This error is thrown when the Homeserver does not support the sticky events endpoints.\n */\nexport class UnsupportedStickyEventsEndpointError extends Error {\n  constructor(message, clientEndpoint) {\n    super(message);\n    this.clientEndpoint = clientEndpoint;\n    this.name = \"UnsupportedStickyEventsEndpointError\";\n  }\n}\n//# sourceMappingURL=errors.js.map","/*\nCopyright 2025 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport var MembershipManagerEvent = /*#__PURE__*/function (MembershipManagerEvent) {\n  MembershipManagerEvent[\"StatusChanged\"] = \"StatusChanged\";\n  /**\n   * Emitted when the membership manager has not heard back from the server for the duration\n   * of the delayed event and hence failed to restart the delayed event.\n   * This means that the user is probably not joined anymore and the leave event was distributed to other session members.\n   */\n  MembershipManagerEvent[\"ProbablyLeft\"] = \"ProbablyLeft\";\n  /**\n   * Once the membershipManger has aquired the a delay id (after sending the state event)\n   * It will emit and share the delay id.\n   */\n  MembershipManagerEvent[\"DelayIdChanged\"] = \"DelayIdChanged\";\n  return MembershipManagerEvent;\n}({});\n\n/**\n * This interface defines what a MembershipManager uses and exposes.\n * This interface is what we use to write tests and allows changing the actual implementation\n * without breaking tests because of some internal method renaming.\n *\n * @internal\n */\n//# sourceMappingURL=IMembershipManager.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2025 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport { AbortError } from \"p-retry\";\nimport { EventType, RelationType } from \"../@types/event.js\";\nimport { ConnectionError, HTTPError, MatrixError } from \"../http-api/errors.js\";\nimport { logger as rootLogger } from \"../logger.js\";\nimport { DEFAULT_EXPIRE_DURATION } from \"./CallMembership.js\";\nimport { isMyMembership, Status } from \"./types.js\";\nimport { slotDescriptionToId } from \"./MatrixRTCSession.js\";\nimport { ActionScheduler } from \"./MembershipManagerActionScheduler.js\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.js\";\nimport { UnsupportedDelayedEventsEndpointError } from \"../errors.js\";\nimport { MembershipManagerEvent } from \"./IMembershipManager.js\";\nimport { isLivekitTransportConfig } from \"./LivekitTransport.js\";\n\n/* MembershipActionTypes:\nOn Join:  ───────────────┐   ┌───────────────(1)───────────┐\n                         ▼   ▼                             │\n                   ┌────────────────┐                      │\n                   │SendDelayedEvent│ ──────(2)───┐        │\n                   └────────────────┘             │        │\n                           │(3)                   │        │\n                           ▼                      │        │\n                    ┌─────────────┐               │        │\n       ┌──────(4)───│SendJoinEvent│────(4)─────┐  │        │\n       │            └─────────────┘            │  │        │\n       │  ┌─────┐                  ┌──────┐    │  │        │\n       ▼  ▼     │                  │      ▼    ▼  ▼        │\n┌────────────┐  │                  │ ┌───────────────────┐ │\n│UpdateExpiry│ (s)                (s)|RestartDelayedEvent│ │\n└────────────┘  │                  │ └───────────────────┘ │\n          │     │                  │      │        │       │\n          └─────┘                  └──────┘        └───────┘\n\nOn Leave: ─────────  STOP ALL ABOVE\n                           ▼\n            ┌────────────────────────────────┐\n            │ SendScheduledDelayedLeaveEvent │\n            └────────────────────────────────┘\n                           │(5)\n                           ▼\n                    ┌──────────────┐\n                    │SendLeaveEvent│\n                    └──────────────┘\n(1) [Not found error] results in resending the delayed event\n(2) [hasMemberEvent = true] Sending the delayed event if we\n    already have a call member event results jumping to the\n    RestartDelayedEvent loop directly\n(3) [hasMemberEvent = false] if there is not call member event\n    sending it is the next step\n(4) Both (UpdateExpiry and RestartDelayedEvent) actions are\n    scheduled when successfully sending the state event\n(5) Only if delayed event sending failed (fallback)\n(s) Successful restart/resend\n*/\n\n/**\n * Call membership should always remain sticky for this amount\n * of time.\n */\nvar MEMBERSHIP_STICKY_DURATION_MS = 60 * 60 * 1000; // 60 minutes\n\n/**\n * The different types of actions the MembershipManager can take.\n * @internal\n */\nexport var MembershipActionType = /*#__PURE__*/function (MembershipActionType) {\n  MembershipActionType[\"SendDelayedEvent\"] = \"SendDelayedEvent\";\n  //  -> MembershipActionType.SendJoinEvent if successful\n  //  -> DelayedLeaveActionType.SendDelayedEvent on error, retry sending the first delayed event.\n  //  -> DelayedLeaveActionType.RestartDelayedEvent on success start updating the delayed event\n  MembershipActionType[\"SendJoinEvent\"] = \"SendJoinEvent\";\n  //  -> MembershipActionType.SendJoinEvent if we run into a rate limit and need to retry\n  //  -> MembershipActionType.Update if we successfully send the join event then schedule the expire event update\n  //  -> DelayedLeaveActionType.RestartDelayedEvent to recheck the delayed event\n  MembershipActionType[\"RestartDelayedEvent\"] = \"RestartDelayedEvent\";\n  //  -> DelayedLeaveActionType.SendMainDelayedEvent on missing delay id but there is a rtc state event\n  //  -> DelayedLeaveActionType.SendDelayedEvent on missing delay id and there is no state event\n  //  -> DelayedLeaveActionType.RestartDelayedEvent on success we schedule the next restart\n  MembershipActionType[\"UpdateExpiry\"] = \"UpdateExpiry\";\n  //  -> MembershipActionType.Update if the timeout has passed so the next update is required.\n  MembershipActionType[\"SendScheduledDelayedLeaveEvent\"] = \"SendScheduledDelayedLeaveEvent\";\n  //  -> MembershipActionType.SendLeaveEvent on failure (not found) we need to send the leave manually and cannot use the scheduled delayed event\n  //  -> DelayedLeaveActionType.SendScheduledDelayedLeaveEvent on error we try again.\n  MembershipActionType[\"SendLeaveEvent\"] = \"SendLeaveEvent\"; // -> MembershipActionType.SendLeaveEvent\n  return MembershipActionType;\n}({});\n\n/**\n * @internal\n */\n\nfunction createInsertActionUpdate(type, offset) {\n  return {\n    insert: [{\n      ts: Date.now() + (offset !== null && offset !== void 0 ? offset : 0),\n      type\n    }]\n  };\n}\nfunction createReplaceActionUpdate(type, offset) {\n  return {\n    replace: [{\n      ts: Date.now() + (offset !== null && offset !== void 0 ? offset : 0),\n      type\n    }]\n  };\n}\n/**\n * This class is responsible for sending all events relating to the own membership of a matrixRTC call.\n * It has the following tasks:\n *  - Send the users leave delayed event before sending the membership\n *  - Send the users membership if the state machine is started\n *  - Check if the delayed event was canceled due to sending the membership\n *  - update the delayed event (`restart`)\n *  - Update the state event every ~5h = `DEFAULT_EXPIRE_DURATION` (so it does not get treated as expired)\n *  - When the state machine is stopped:\n *   - Disconnect the member\n *   - Stop the timer for the delay refresh\n *   - Stop the timer for updating the state event\n */\nexport class MembershipManager extends TypedEventEmitter {\n  isActivated() {\n    return this.activated;\n  }\n  // DEPRECATED use isActivated\n  isJoined() {\n    return this.isActivated();\n  }\n\n  /**\n   * Puts the MembershipManager in a state where it tries to be joined.\n   * It will send delayed events and membership events\n   * @param fociPreferred the list of preferred foci to use in the joined RTC membership event.\n   * If multiSfuFocus is set, this is only needed if this client wants to publish to multiple transports simultaneously.\n   * @param multiSfuFocus the active focus to use in the joined RTC membership event. Setting this implies the\n   * membership manager will operate in a multi-SFU connection mode. If `undefined`, an `oldest_membership`\n   * transport selection will be used instead.\n   * @param onError This will be called once the membership manager encounters an unrecoverable error.\n   * This should bubble up the the frontend to communicate that the call does not work in the current environment.\n   */\n  join(fociPreferred, multiSfuFocus, onError) {\n    if (this.scheduler.running) {\n      this.logger.error(\"MembershipManager is already running. Ignoring join request.\");\n      return;\n    }\n    this.fociPreferred = fociPreferred;\n    this.rtcTransport = multiSfuFocus;\n    this.leavePromiseResolvers = undefined;\n    this.activated = true;\n    this.oldStatus = this.status;\n    this.state = MembershipManager.defaultState;\n    this.scheduler.startWithJoin().catch(e => {\n      this.logger.error(\"MembershipManager stopped because: \", e);\n      onError === null || onError === void 0 || onError(e);\n    }).finally(() => {\n      // Should already be set to false when calling `leave` in non error cases.\n      this.activated = false;\n      // Here the scheduler is not running anymore so we the `membershipLoopHandler` is not called to emit.\n      if (this.oldStatus && this.oldStatus !== this.status) {\n        this.emit(MembershipManagerEvent.StatusChanged, this.oldStatus, this.status);\n      }\n      if (!this.scheduler.running) {\n        var _this$leavePromiseRes;\n        (_this$leavePromiseRes = this.leavePromiseResolvers) === null || _this$leavePromiseRes === void 0 || _this$leavePromiseRes.resolve(true);\n        this.leavePromiseResolvers = undefined;\n      }\n    });\n  }\n\n  /**\n   * Leave from the call (Send an rtc session event with content: `{}`)\n   * @param timeout the maximum duration this promise will take to resolve\n   * @returns true if it managed to leave and false if the timeout condition happened.\n   */\n  leave(timeout) {\n    if (!this.scheduler.running) {\n      this.logger.warn(\"Called MembershipManager.leave() even though the MembershipManager is not running\");\n      return Promise.resolve(true);\n    }\n\n    // We use the promise to track if we already scheduled a leave event\n    // So we do not check scheduler.actions/scheduler.insertions\n    if (!this.leavePromiseResolvers) {\n      // reset scheduled actions so we will not do any new actions.\n      this.leavePromiseResolvers = Promise.withResolvers();\n      this.activated = false;\n      this.scheduler.initiateLeave();\n      if (timeout) setTimeout(() => {\n        var _this$leavePromiseRes2;\n        return (_this$leavePromiseRes2 = this.leavePromiseResolvers) === null || _this$leavePromiseRes2 === void 0 ? void 0 : _this$leavePromiseRes2.resolve(false);\n      }, timeout);\n    }\n    return this.leavePromiseResolvers.promise;\n  }\n  onRTCSessionMemberUpdate(memberships) {\n    if (!this.isActivated()) {\n      return Promise.resolve();\n    }\n    this._ownMembership = memberships.find(m => isMyMembership(m, this.userId, this.deviceId));\n    if (!this._ownMembership) {\n      // If one of these actions are scheduled or are getting inserted in the next iteration, we should already\n      // take care of our missing membership.\n      var sendingMembershipActions = [MembershipActionType.SendDelayedEvent, MembershipActionType.SendJoinEvent];\n      this.logger.warn(\"Missing own membership: force re-join\");\n      this.state.hasMemberStateEvent = false;\n      if (this.scheduler.actions.some(a => sendingMembershipActions.includes(a.type))) {\n        this.logger.error(\"tried adding another `SendDelayedEvent` actions even though we already have one in the Queue\\nActionQueueOnMemberUpdate:\", this.scheduler.actions);\n      } else {\n        // Only react to our own membership missing if we have not already scheduled sending a new membership DirectMembershipManagerAction.Join\n        this.scheduler.initiateJoin();\n      }\n    }\n    return Promise.resolve();\n  }\n  updateCallIntent(callIntent) {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      if (!_this.activated || !_this.ownMembership) {\n        throw Error(\"You cannot update your intent before joining the call\");\n      }\n      if (_this.ownMembership.callIntent === callIntent) {\n        return; // No-op\n      }\n      _this.callIntent = callIntent;\n      // Kick off a new membership event as a result.\n      yield _this.sendJoinEvent();\n    })();\n  }\n\n  /**\n   * @throws if the client does not return user or device id.\n   * @param joinConfig\n   * @param room\n   * @param client\n   */\n  constructor(joinConfig, room, client, slotDescription, parentLogger) {\n    super();\n    this.joinConfig = joinConfig;\n    this.room = room;\n    this.client = client;\n    this.slotDescription = slotDescription;\n    _defineProperty(this, \"activated\", false);\n    _defineProperty(this, \"logger\", void 0);\n    _defineProperty(this, \"callIntent\", void 0);\n    _defineProperty(this, \"leavePromiseResolvers\", void 0);\n    _defineProperty(this, \"_ownMembership\", void 0);\n    // scheduler\n    _defineProperty(this, \"oldStatus\", void 0);\n    _defineProperty(this, \"scheduler\", void 0);\n    // MembershipManager mutable state.\n    _defineProperty(this, \"state\", void 0);\n    // Membership Event static parameters:\n    _defineProperty(this, \"deviceId\", void 0);\n    _defineProperty(this, \"userId\", void 0);\n    _defineProperty(this, \"stateKey\", void 0);\n    _defineProperty(this, \"rtcTransport\", void 0);\n    /** @deprecated This will be removed in favor or rtcTransport becoming a list of actively used transports */\n    _defineProperty(this, \"fociPreferred\", void 0);\n    // Config:\n    _defineProperty(this, \"delayedLeaveEventDelayMsOverride\", void 0);\n    // an abstraction to switch between sending state or a sticky event\n    _defineProperty(this, \"clientSendDelayedDisconnectMembership\", () => this.client._unstable_sendDelayedStateEvent(this.room.roomId, {\n      delay: this.delayedLeaveEventDelayMs\n    }, EventType.GroupCallMemberPrefix, {}, this.stateKey));\n    _defineProperty(this, \"clientSendMembership\", myMembership => {\n      return this.client.sendStateEvent(this.room.roomId, EventType.GroupCallMemberPrefix, myMembership, this.stateKey);\n    });\n    this.logger = (parentLogger !== null && parentLogger !== void 0 ? parentLogger : rootLogger).getChild(\"[MembershipManager]\");\n    var [userId, deviceId] = [this.client.getUserId(), this.client.getDeviceId()];\n    if (userId === null) throw Error(\"Missing userId in client\");\n    if (deviceId === null) throw Error(\"Missing deviceId in client\");\n    this.deviceId = deviceId;\n    this.userId = userId;\n    // this needs to become a uuid so that consecutive join/leaves result in a key rotation.\n    // we keep it as a string for now for backwards compatibility.\n    this.stateKey = this.makeMembershipStateKey(userId, deviceId);\n    this.state = MembershipManager.defaultState;\n    this.callIntent = joinConfig === null || joinConfig === void 0 ? void 0 : joinConfig.callIntent;\n    this.scheduler = new ActionScheduler(type => {\n      if (this.oldStatus) {\n        // we put this at the beginning of the actions scheduler loop handle callback since it is a loop this\n        // is equivalent to running it at the end of the loop. (just after applying the status/action list changes)\n        // This order is required because this method needs to return the action updates.\n        this.logger.debug(\"MembershipManager applied action changes. Status: \".concat(this.oldStatus, \" -> \").concat(this.status));\n        if (this.oldStatus !== this.status) {\n          this.emit(MembershipManagerEvent.StatusChanged, this.oldStatus, this.status);\n        }\n      }\n      this.oldStatus = this.status;\n      this.logger.debug(\"MembershipManager before processing action. status=\".concat(this.oldStatus));\n      return this.membershipLoopHandler(type);\n    }, this.logger);\n  }\n  get ownMembership() {\n    return this._ownMembership;\n  }\n  static get defaultState() {\n    return {\n      hasMemberStateEvent: false,\n      delayId: undefined,\n      startTime: 0,\n      rateLimitRetries: new Map(),\n      networkErrorRetries: new Map(),\n      expireUpdateIterations: 1,\n      probablyLeft: false\n    };\n  }\n  get networkErrorRetryMs() {\n    var _this$joinConfig$netw, _this$joinConfig;\n    return (_this$joinConfig$netw = (_this$joinConfig = this.joinConfig) === null || _this$joinConfig === void 0 ? void 0 : _this$joinConfig.networkErrorRetryMs) !== null && _this$joinConfig$netw !== void 0 ? _this$joinConfig$netw : 3000;\n  }\n  get membershipEventExpiryMs() {\n    var _this$joinConfig$memb, _this$joinConfig2;\n    return (_this$joinConfig$memb = (_this$joinConfig2 = this.joinConfig) === null || _this$joinConfig2 === void 0 ? void 0 : _this$joinConfig2.membershipEventExpiryMs) !== null && _this$joinConfig$memb !== void 0 ? _this$joinConfig$memb : DEFAULT_EXPIRE_DURATION;\n  }\n  get membershipEventExpiryHeadroomMs() {\n    var _this$joinConfig$memb2, _this$joinConfig3;\n    return (_this$joinConfig$memb2 = (_this$joinConfig3 = this.joinConfig) === null || _this$joinConfig3 === void 0 ? void 0 : _this$joinConfig3.membershipEventExpiryHeadroomMs) !== null && _this$joinConfig$memb2 !== void 0 ? _this$joinConfig$memb2 : 5000;\n  }\n  computeNextExpiryActionTs(iteration) {\n    return this.state.startTime + Math.min(this.membershipEventExpiryMs, MEMBERSHIP_STICKY_DURATION_MS) * iteration - this.membershipEventExpiryHeadroomMs;\n  }\n  get delayedLeaveEventDelayMs() {\n    var _ref, _this$delayedLeaveEve, _this$joinConfig4;\n    return (_ref = (_this$delayedLeaveEve = this.delayedLeaveEventDelayMsOverride) !== null && _this$delayedLeaveEve !== void 0 ? _this$delayedLeaveEve : (_this$joinConfig4 = this.joinConfig) === null || _this$joinConfig4 === void 0 ? void 0 : _this$joinConfig4.delayedLeaveEventDelayMs) !== null && _ref !== void 0 ? _ref : 8000;\n  }\n  get delayedLeaveEventRestartMs() {\n    var _this$joinConfig$dela, _this$joinConfig5;\n    return (_this$joinConfig$dela = (_this$joinConfig5 = this.joinConfig) === null || _this$joinConfig5 === void 0 ? void 0 : _this$joinConfig5.delayedLeaveEventRestartMs) !== null && _this$joinConfig$dela !== void 0 ? _this$joinConfig$dela : 5000;\n  }\n  get maximumRateLimitRetryCount() {\n    var _this$joinConfig$maxi, _this$joinConfig6;\n    return (_this$joinConfig$maxi = (_this$joinConfig6 = this.joinConfig) === null || _this$joinConfig6 === void 0 ? void 0 : _this$joinConfig6.maximumRateLimitRetryCount) !== null && _this$joinConfig$maxi !== void 0 ? _this$joinConfig$maxi : 10;\n  }\n  get maximumNetworkErrorRetryCount() {\n    var _this$joinConfig$maxi2, _this$joinConfig7;\n    return (_this$joinConfig$maxi2 = (_this$joinConfig7 = this.joinConfig) === null || _this$joinConfig7 === void 0 ? void 0 : _this$joinConfig7.maximumNetworkErrorRetryCount) !== null && _this$joinConfig$maxi2 !== void 0 ? _this$joinConfig$maxi2 : 10;\n  }\n  get delayedLeaveEventRestartLocalTimeoutMs() {\n    var _this$joinConfig$dela2, _this$joinConfig8;\n    return (_this$joinConfig$dela2 = (_this$joinConfig8 = this.joinConfig) === null || _this$joinConfig8 === void 0 ? void 0 : _this$joinConfig8.delayedLeaveEventRestartLocalTimeoutMs) !== null && _this$joinConfig$dela2 !== void 0 ? _this$joinConfig$dela2 : 2000;\n  }\n\n  // LOOP HANDLER:\n  membershipLoopHandler(type) {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      switch (type) {\n        case MembershipActionType.SendDelayedEvent:\n          {\n            // Before we start we check if we come from a state where we have a delay id.\n            if (!_this2.state.delayId) {\n              return _this2.sendOrResendDelayedLeaveEvent(); // Normal case without any previous delayed id.\n            } else {\n              // This can happen if someone else (or another client) removes our own membership event.\n              // It will trigger `onRTCSessionMemberUpdate` queue `MembershipActionType.SendDelayedEvent`.\n              // We might still have our delayed event from the previous participation and dependent on the server this might not\n              // get removed automatically if the state changes. Hence, it would remove our membership unexpectedly shortly after the rejoin.\n              //\n              // In this block we will try to cancel this delayed event before setting up a new one.\n\n              return _this2.cancelKnownDelayIdBeforeSendDelayedEvent(_this2.state.delayId);\n            }\n          }\n        case MembershipActionType.RestartDelayedEvent:\n          {\n            if (!_this2.state.delayId) {\n              // Delay id got reset. This action was used to check if the hs canceled the delayed event when the join state got sent.\n              return createInsertActionUpdate(MembershipActionType.SendDelayedEvent);\n            }\n            return _this2.restartDelayedEvent(_this2.state.delayId);\n          }\n        case MembershipActionType.SendScheduledDelayedLeaveEvent:\n          {\n            // We are already good\n            if (!_this2.state.hasMemberStateEvent) {\n              return {\n                replace: []\n              };\n            }\n            if (_this2.state.delayId) {\n              return _this2.sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(_this2.state.delayId);\n            } else {\n              return createInsertActionUpdate(MembershipActionType.SendLeaveEvent);\n            }\n          }\n        case MembershipActionType.SendJoinEvent:\n          {\n            return _this2.sendJoinEvent();\n          }\n        case MembershipActionType.UpdateExpiry:\n          {\n            return _this2.updateExpiryOnJoinedEvent();\n          }\n        case MembershipActionType.SendLeaveEvent:\n          {\n            // We are good already\n            if (!_this2.state.hasMemberStateEvent) {\n              return {\n                replace: []\n              };\n            }\n            // This is only a fallback in case we do not have working delayed events support.\n            // first we should try to just send the scheduled leave event\n            return _this2.sendFallbackLeaveEvent();\n          }\n      }\n    })();\n  }\n  // HANDLERS (used in the membershipLoopHandler)\n  sendOrResendDelayedLeaveEvent() {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      // We can reach this at the start of a call (where we do not yet have a membership: state.hasMemberStateEvent=false)\n      // or during a call if the state event canceled our delayed event or caused by an unexpected error that removed our delayed event.\n      // (Another client could have canceled it, the homeserver might have removed/lost it due to a restart, ...)\n      // In the `then` and `catch` block we treat both cases differently. \"if (this.state.hasMemberStateEvent) {} else {}\"\n      return yield _this3.clientSendDelayedDisconnectMembership().then(response => {\n        _this3.state.expectedServerDelayLeaveTs = Date.now() + _this3.delayedLeaveEventDelayMs;\n        _this3.setAndEmitProbablyLeft(false);\n        // On success we reset retries and set delayId.\n        _this3.resetRateLimitCounter(MembershipActionType.SendDelayedEvent);\n        _this3.setAndEmitDelayId(response.delay_id);\n        if (_this3.state.hasMemberStateEvent) {\n          // This action was scheduled because the previous delayed event was cancelled\n          // due to lack of https://github.com/element-hq/synapse/pull/17810\n          return createInsertActionUpdate(MembershipActionType.RestartDelayedEvent, _this3.delayedLeaveEventRestartMs);\n        } else {\n          // This action was scheduled because we are in the process of joining\n          return createInsertActionUpdate(MembershipActionType.SendJoinEvent);\n        }\n      }).catch(e => {\n        var repeatActionType = MembershipActionType.SendDelayedEvent;\n        if (_this3.manageMaxDelayExceededSituation(e)) {\n          return createInsertActionUpdate(repeatActionType);\n        }\n        var update = _this3.actionUpdateFromErrors(e, repeatActionType, \"_unstable_sendDelayedStateEvent\");\n        if (update) return update;\n        if (_this3.state.hasMemberStateEvent) {\n          // This action was scheduled because the previous delayed event was cancelled\n          // due to lack of https://github.com/element-hq/synapse/pull/17810\n\n          // Don't do any other delayed event work if its not supported.\n          if (_this3.isUnsupportedDelayedEndpoint(e)) return {};\n          throw Error(\"Could not send delayed event, even though delayed events are supported. \" + e);\n        } else {\n          // This action was scheduled because we are in the process of joining\n          // log and fall through\n          if (_this3.isUnsupportedDelayedEndpoint(e)) {\n            _this3.logger.info(\"Not using delayed event because the endpoint is not supported\");\n          } else {\n            _this3.logger.info(\"Not using delayed event because: \" + e);\n          }\n          // On any other error we fall back to not using delayed events and send the join state event immediately\n          return createInsertActionUpdate(MembershipActionType.SendJoinEvent);\n        }\n      });\n    })();\n  }\n  cancelKnownDelayIdBeforeSendDelayedEvent(delayId) {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      // Remove all running updates and restarts\n      return yield _this4.client._unstable_cancelScheduledDelayedEvent(delayId).then(() => {\n        _this4.setAndEmitDelayId(undefined);\n        _this4.resetRateLimitCounter(MembershipActionType.SendDelayedEvent);\n        return createReplaceActionUpdate(MembershipActionType.SendDelayedEvent);\n      }).catch(e => {\n        var repeatActionType = MembershipActionType.SendDelayedEvent;\n        var update = _this4.actionUpdateFromErrors(e, repeatActionType, \"cancelScheduledDelayedEvent\");\n        if (update) return update;\n        if (_this4.isNotFoundError(e)) {\n          // If we get a M_NOT_FOUND we know that the delayed event got already removed.\n          // This means we are good and can set it to undefined and run this again.\n          _this4.setAndEmitDelayId(undefined);\n          return createReplaceActionUpdate(repeatActionType);\n        }\n        if (_this4.isUnsupportedDelayedEndpoint(e)) {\n          return createReplaceActionUpdate(MembershipActionType.SendJoinEvent);\n        }\n        // We do not just ignore and log this error since we would also need to reset the delayId.\n\n        // This becomes an unrecoverable error case since something is significantly off if we don't hit any of the above cases\n        // when state.delayId !== undefined\n        // We do not just ignore and log this error since we would also need to reset the delayId.\n        // It is cleaner if we, the frontend, rejoins instead of resetting the delayId here and behaving like in the success case.\n        throw Error(\"We failed to cancel a delayed event where we already had a delay id with an error we cannot automatically handle\");\n      });\n    })();\n  }\n  setAndEmitProbablyLeft(probablyLeft) {\n    if (this.state.probablyLeft === probablyLeft) {\n      return;\n    }\n    this.state.probablyLeft = probablyLeft;\n    this.emit(MembershipManagerEvent.ProbablyLeft, this.state.probablyLeft);\n  }\n  setAndEmitDelayId(delayId) {\n    if (this.state.delayId === delayId) return;\n    this.state.delayId = delayId;\n    this.emit(MembershipManagerEvent.DelayIdChanged, this.state.delayId);\n  }\n  restartDelayedEvent(delayId) {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      // Compute the duration until we expect the server to send the delayed leave event.\n      var durationUntilServerDelayedLeave = _this5.state.expectedServerDelayLeaveTs ? _this5.state.expectedServerDelayLeaveTs - Date.now() : undefined;\n      var abortPromise = new Promise((_, reject) => {\n        setTimeout(() => {\n          reject(new AbortError(\"Restart delayed event timed out before the HS responded\"));\n        },\n        // We abort immediately at the time where we expect the server to send the delayed leave event.\n        // At this point we want the catch block to run and set the `probablyLeft` state.\n        //\n        // While we are already in probablyLeft state, we use the unaltered delayedLeaveEventRestartLocalTimeoutMs.\n        durationUntilServerDelayedLeave !== undefined && !_this5.state.probablyLeft ? Math.min(_this5.delayedLeaveEventRestartLocalTimeoutMs, durationUntilServerDelayedLeave) : _this5.delayedLeaveEventRestartLocalTimeoutMs);\n      });\n\n      // The obvious choice here would be to use the `IRequestOpts` to set the timeout. Since this call might be forwarded\n      // to the widget driver this information would get lost. That is why we mimic the AbortError using the race.\n      return yield Promise.race([_this5.client._unstable_restartScheduledDelayedEvent(delayId), abortPromise]).then(() => {\n        // Whenever we successfully restart the delayed event we update the `state.expectedServerDelayLeaveTs`\n        // which stores the predicted timestamp at which the server will send the delayed leave event if there wont be any further\n        // successful restart requests.\n        _this5.state.expectedServerDelayLeaveTs = Date.now() + _this5.delayedLeaveEventDelayMs;\n        _this5.resetRateLimitCounter(MembershipActionType.RestartDelayedEvent);\n        _this5.setAndEmitProbablyLeft(false);\n        return createInsertActionUpdate(MembershipActionType.RestartDelayedEvent, _this5.delayedLeaveEventRestartMs);\n      }).catch(e => {\n        if (_this5.state.expectedServerDelayLeaveTs && _this5.state.expectedServerDelayLeaveTs <= Date.now()) {\n          // Once we reach this point it's likely that the server is sending the delayed leave event so we emit `probablyLeft = true`.\n          // It will emit `probablyLeft = false` once we notice about our leave through sync and successfully setup a new state event.\n          _this5.setAndEmitProbablyLeft(true);\n        }\n        var repeatActionType = MembershipActionType.RestartDelayedEvent;\n        if (_this5.isNotFoundError(e)) {\n          _this5.setAndEmitDelayId(undefined);\n          return createInsertActionUpdate(MembershipActionType.SendDelayedEvent);\n        }\n        // If the HS does not support delayed events we wont reschedule.\n        if (_this5.isUnsupportedDelayedEndpoint(e)) return {};\n\n        // TODO this also needs a test: get rate limit while checking id delayed event is scheduled\n        var update = _this5.actionUpdateFromErrors(e, repeatActionType, \"restartScheduledDelayedEvent\");\n        if (update) return update;\n\n        // In other error cases we have no idea what is happening\n        throw Error(\"Could not restart delayed event, even though delayed events are supported. \" + e);\n      });\n    })();\n  }\n  sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(delayId) {\n    var _this6 = this;\n    return _asyncToGenerator(function* () {\n      return yield _this6.client._unstable_sendScheduledDelayedEvent(delayId).then(() => {\n        _this6.state.hasMemberStateEvent = false;\n        _this6.setAndEmitDelayId(undefined);\n        _this6.resetRateLimitCounter(MembershipActionType.SendScheduledDelayedLeaveEvent);\n        return {\n          replace: []\n        };\n      }).catch(e => {\n        var repeatActionType = MembershipActionType.SendLeaveEvent;\n        if (_this6.isUnsupportedDelayedEndpoint(e)) return {};\n        if (_this6.isNotFoundError(e)) {\n          _this6.setAndEmitDelayId(undefined);\n          return createInsertActionUpdate(repeatActionType);\n        }\n        var update = _this6.actionUpdateFromErrors(e, repeatActionType, \"sendScheduledDelayedEvent\");\n        if (update) return update;\n\n        // On any other error we fall back to SendLeaveEvent (this includes hard errors from rate limiting)\n        _this6.logger.warn(\"Encountered unexpected error during SendScheduledDelayedLeaveEvent. Falling back to SendLeaveEvent\", e);\n        return createInsertActionUpdate(repeatActionType);\n      });\n    })();\n  }\n  sendJoinEvent() {\n    var _this7 = this;\n    return _asyncToGenerator(function* () {\n      return yield _this7.clientSendMembership(_this7.makeMyMembership(_this7.membershipEventExpiryMs)).then(() => {\n        _this7.setAndEmitProbablyLeft(false);\n        _this7.state.startTime = Date.now();\n        // The next update should already use twice the membershipEventExpiryTimeout\n        _this7.state.expireUpdateIterations = 1;\n        _this7.state.hasMemberStateEvent = true;\n        _this7.resetRateLimitCounter(MembershipActionType.SendJoinEvent);\n        // An UpdateExpiry action might be left over from a previous join event.\n        // We can reach sendJoinEvent when the delayed leave event gets send by the HS.\n        // The branch where we might have a leftover UpdateExpiry action is:\n        // RestartDelayedEvent (cannot find it, server removed it)\n        // -> SendDelayedEvent (send new delayed event)\n        // -> SendJoinEvent (here with a still scheduled UpdateExpiry action)\n        var actionsWithoutUpdateExpiry = _this7.scheduler.actions.filter(a => a.type !== MembershipActionType.UpdateExpiry &&\n        // A new UpdateExpiry action with an updated will be scheduled,\n        a.type !== MembershipActionType.SendJoinEvent // Manually remove the SendJoinEvent action,\n        );\n        return {\n          replace: [...actionsWithoutUpdateExpiry,\n          // To check if the delayed event is still there or got removed by inserting the stateEvent, we need to restart it.\n          {\n            ts: Date.now(),\n            type: MembershipActionType.RestartDelayedEvent\n          }, {\n            ts: _this7.computeNextExpiryActionTs(_this7.state.expireUpdateIterations),\n            type: MembershipActionType.UpdateExpiry\n          }]\n        };\n      }).catch(e => {\n        var update = _this7.actionUpdateFromErrors(e, MembershipActionType.SendJoinEvent, \"sendStateEvent\");\n        if (update) return update;\n        throw e;\n      });\n    })();\n  }\n  updateExpiryOnJoinedEvent() {\n    var _this8 = this;\n    return _asyncToGenerator(function* () {\n      var nextExpireUpdateIteration = _this8.state.expireUpdateIterations + 1;\n      return yield _this8.clientSendMembership(_this8.makeMyMembership(_this8.membershipEventExpiryMs * nextExpireUpdateIteration)).then(() => {\n        // Success, we reset retries and schedule update.\n        _this8.resetRateLimitCounter(MembershipActionType.UpdateExpiry);\n        _this8.state.expireUpdateIterations = nextExpireUpdateIteration;\n        return {\n          insert: [{\n            ts: _this8.computeNextExpiryActionTs(nextExpireUpdateIteration),\n            type: MembershipActionType.UpdateExpiry\n          }]\n        };\n      }).catch(e => {\n        var update = _this8.actionUpdateFromErrors(e, MembershipActionType.UpdateExpiry, \"sendStateEvent\");\n        if (update) return update;\n        throw e;\n      });\n    })();\n  }\n  sendFallbackLeaveEvent() {\n    var _this9 = this;\n    return _asyncToGenerator(function* () {\n      return yield _this9.clientSendMembership({}).then(() => {\n        _this9.resetRateLimitCounter(MembershipActionType.SendLeaveEvent);\n        _this9.state.hasMemberStateEvent = false;\n        return {\n          replace: []\n        };\n      }).catch(e => {\n        var update = _this9.actionUpdateFromErrors(e, MembershipActionType.SendLeaveEvent, \"sendStateEvent\");\n        if (update) return update;\n        throw e;\n      });\n    })();\n  }\n\n  // HELPERS\n  /**\n   * this creates `${localUserId}_${localDeviceId}_${this.slotDescription.application}${this.slotDescription.id}`\n   * which is not compatible with membershipID of session type member events. They have to be `${localUserId}:${localDeviceId}`\n   */\n  makeMembershipStateKey(localUserId, localDeviceId) {\n    // INFO_SLOT_ID_LEGACY_CASE  (search for all occurances of this INFO to get the full picture)\n    // Revert back to \"\" just for the state key (state keys are always legacy. we use sticky events for non legacy events)\n    var application = this.slotDescription.application;\n    var needsEmptyStringRoomFix = application === \"m.call\" && this.slotDescription.id === \"ROOM\";\n    var slotId = needsEmptyStringRoomFix ? \"\" : this.slotDescription.id;\n    var stateKey = \"\".concat(localUserId, \"_\").concat(localDeviceId, \"_\").concat(application).concat(slotId);\n    if (/^org\\.matrix\\.msc(3757|3779)\\b/.exec(this.room.getVersion())) {\n      return stateKey;\n    } else {\n      return \"_\".concat(stateKey);\n    }\n  }\n\n  /**\n   * Constructs our own membership\n   */\n  makeMyMembership(expires) {\n    var _this$fociPreferred, _this$fociPreferred2;\n    var ownMembership = this.ownMembership;\n    var needsEmptyStringRoomFix = this.slotDescription.application === \"m.call\" && this.slotDescription.id === \"ROOM\";\n    var focusObjects = this.rtcTransport === undefined ? {\n      focus_active: {\n        type: \"livekit\",\n        focus_selection: \"oldest_membership\"\n      },\n      foci_preferred: (_this$fociPreferred = this.fociPreferred) !== null && _this$fociPreferred !== void 0 ? _this$fociPreferred : []\n    } : {\n      focus_active: {\n        type: \"livekit\",\n        focus_selection: \"multi_sfu\"\n      },\n      foci_preferred: [this.rtcTransport, ...((_this$fociPreferred2 = this.fociPreferred) !== null && _this$fociPreferred2 !== void 0 ? _this$fociPreferred2 : [])]\n    };\n    return _objectSpread(_objectSpread({\n      \"application\": this.slotDescription.application,\n      // INFO_SLOT_ID_LEGACY_CASE  (search for all occurances of this INFO to get the full picture)\n      // Revert back to \"\" just for the sending the event.\n      \"call_id\": needsEmptyStringRoomFix ? \"\" : this.slotDescription.id,\n      \"scope\": \"m.room\",\n      \"device_id\": this.deviceId,\n      // DO NOT use this.memberId here since that is the state key (using application...)\n      // But for session events we use the colon seperated userId and deviceId. The SFU will automatically\n      // assign those values to the media participant for those versions.\n      \"membershipID\": \"\".concat(this.userId, \":\").concat(this.deviceId),\n      expires,\n      \"m.call.intent\": this.callIntent\n    }, focusObjects), ownMembership !== undefined ? {\n      created_ts: ownMembership.createdTs()\n    } : undefined);\n  }\n\n  // Error checks and handlers\n\n  /**\n   * Check if its a NOT_FOUND error\n   * @param error the error causing this handler check/execution\n   * @returns true if its a not found error\n   */\n  isNotFoundError(error) {\n    return error instanceof MatrixError && error.errcode === \"M_NOT_FOUND\";\n  }\n\n  /**\n   * Check if this is a DelayExceeded timeout and update the TimeoutOverride for the next try\n   * @param error the error causing this handler check/execution\n   * @returns true if its a delay exceeded error and we updated the local TimeoutOverride\n   */\n  manageMaxDelayExceededSituation(error) {\n    if (error instanceof MatrixError && error.errcode === \"M_UNKNOWN\" && error.data[\"org.matrix.msc4140.errcode\"] === \"M_MAX_DELAY_EXCEEDED\") {\n      var maxDelayAllowed = error.data[\"org.matrix.msc4140.max_delay\"];\n      if (typeof maxDelayAllowed === \"number\" && this.delayedLeaveEventDelayMs > maxDelayAllowed) {\n        this.delayedLeaveEventDelayMsOverride = maxDelayAllowed;\n      }\n      this.logger.warn(\"Retry sending delayed disconnection event due to server timeout limitations:\", error);\n      return true;\n    }\n    return false;\n  }\n  actionUpdateFromErrors(error, type, method) {\n    var updateLimit = this.actionUpdateFromRateLimitError(error, method, type);\n    if (updateLimit) return updateLimit;\n    var updateNetwork = this.actionUpdateFromNetworkErrorRetry(error, type);\n    if (updateNetwork) return updateNetwork;\n  }\n  /**\n   * Check if we have a rate limit error and schedule the same action again if we dont exceed the rate limit retry count yet.\n   * @param error the error causing this handler check/execution\n   * @param method the method used for the throw message\n   * @param type which MembershipActionType we reschedule because of a rate limit.\n   * @throws If it is a rate limit error and the retry count got exceeded\n   * @returns Returns true if we handled the error by rescheduling the correct next action.\n   * Returns false if it is not a network error.\n   */\n  actionUpdateFromRateLimitError(error, method, type) {\n    var _this$state$rateLimit;\n    // \"Is rate limit\"-boundary\n    if (!((error instanceof HTTPError || error instanceof MatrixError) && error.isRateLimitError())) {\n      return undefined;\n    }\n\n    // retry boundary\n    var rateLimitRetries = (_this$state$rateLimit = this.state.rateLimitRetries.get(type)) !== null && _this$state$rateLimit !== void 0 ? _this$state$rateLimit : 0;\n    if (rateLimitRetries < this.maximumRateLimitRetryCount) {\n      var resendDelay;\n      var defaultMs = 5000;\n      try {\n        var _error$getRetryAfterM;\n        resendDelay = (_error$getRetryAfterM = error.getRetryAfterMs()) !== null && _error$getRetryAfterM !== void 0 ? _error$getRetryAfterM : defaultMs;\n        this.logger.info(\"Rate limited by server, retrying in \".concat(resendDelay, \"ms\"));\n      } catch (e) {\n        this.logger.warn(\"Error while retrieving a rate-limit retry delay, retrying after default delay of \".concat(defaultMs), e);\n        resendDelay = defaultMs;\n      }\n      this.state.rateLimitRetries.set(type, rateLimitRetries + 1);\n      return createInsertActionUpdate(type, resendDelay);\n    }\n    throw Error(\"Exceeded maximum retries for \" + type + \" attempts (client.\" + method + \")\", {\n      cause: error\n    });\n  }\n\n  /**\n   * FIXME Don't Check the error and retry the same MembershipAction again in the configured time and for the configured retry count.\n   * @param error the error causing this handler check/execution\n   * @param type the action type that we need to repeat because of the error\n   * @throws If it is a network error and the retry count got exceeded\n   * @returns\n   * Returns true if we handled the error by rescheduling the correct next action.\n   * Returns false if it is not a network error.\n   */\n  actionUpdateFromNetworkErrorRetry(error, type) {\n    var _this$state$networkEr;\n    // \"Is a network error\"-boundary\n    var retries = (_this$state$networkEr = this.state.networkErrorRetries.get(type)) !== null && _this$state$networkEr !== void 0 ? _this$state$networkEr : 0;\n\n    // Strings for error logging\n    var retryDurationString = this.networkErrorRetryMs / 1000 + \"s\";\n    var retryCounterString = \"(\" + retries + \"/\" + this.maximumNetworkErrorRetryCount + \")\";\n\n    // Variables for scheduling the new event\n    var retryDuration = this.networkErrorRetryMs;\n    if (error instanceof Error && error.name === \"AbortError\") {\n      // We do not wait for the timeout on local timeouts.\n      retryDuration = 0;\n      this.logger.warn(\"Network local timeout error while sending event, immediate retry (\" + retryCounterString + \")\", error);\n    } else if (error instanceof Error && error.message.includes(\"updating delayed event\")) {\n      // TODO: We do not want error message matching here but instead the error should be a typed HTTPError\n      // and be handled below automatically (the same as in the SPA case).\n      //\n      // The error originates because of https://github.com/matrix-org/matrix-widget-api/blob/5d81d4a26ff69e4bd3ddc79a884c9527999fb2f4/src/ClientWidgetApi.ts#L698-L701\n      // uses `e` instance of HttpError (and not MatrixError)\n      // The element web widget driver (only checks for MatrixError) is then failing to process (`processError`) it as a typed error: https://github.com/element-hq/element-web/blob/471712cbf06a067e5499bd5d2d7a75f693d9a12d/src/stores/widgets/StopGapWidgetDriver.ts#L711-L715\n      // So it will not call: `error.asWidgetApiErrorData()` which is also missing for `HttpError`\n      //\n      // A proper fix would be to either find a place to convert the `HttpError` into a `MatrixError` and the `processError`\n      // method to handle it as expected or to adjust `processError` to also process `HttpError`'s.\n      this.logger.warn(\"delayed event update timeout error, retrying in \" + retryDurationString + \" \" + retryCounterString, error);\n    } else if (error instanceof ConnectionError) {\n      this.logger.warn(\"Network connection error while sending event, retrying in \" + retryDurationString + \" \" + retryCounterString, error);\n    } else if ((error instanceof HTTPError || error instanceof MatrixError) && typeof error.httpStatus === \"number\" && error.httpStatus >= 500 && error.httpStatus < 600) {\n      this.logger.warn(\"Server error while sending event, retrying in \" + retryDurationString + \" \" + retryCounterString, error);\n    } else {\n      return undefined;\n    }\n\n    // retry boundary\n    if (retries < this.maximumNetworkErrorRetryCount) {\n      this.state.networkErrorRetries.set(type, retries + 1);\n      return createInsertActionUpdate(type, retryDuration);\n    }\n\n    // Failure\n    throw Error(\"Reached maximum (\" + this.maximumNetworkErrorRetryCount + \") retries cause by: \" + error);\n  }\n\n  /**\n   * Check if its an UnsupportedDelayedEventsEndpointError and which implies that we cannot do any delayed event logic\n   * @param error The error to check\n   * @returns true it its an UnsupportedDelayedEventsEndpointError\n   */\n  isUnsupportedDelayedEndpoint(error) {\n    return error instanceof UnsupportedDelayedEventsEndpointError;\n  }\n  resetRateLimitCounter(type) {\n    this.state.rateLimitRetries.set(type, 0);\n    this.state.networkErrorRetries.set(type, 0);\n  }\n  get status() {\n    var actions = this.scheduler.actions;\n    if (actions.length === 1) {\n      var {\n        type\n      } = actions[0];\n      switch (type) {\n        case MembershipActionType.SendDelayedEvent:\n        case MembershipActionType.SendJoinEvent:\n          return Status.Connecting;\n        case MembershipActionType.UpdateExpiry:\n          // where no delayed events\n          return Status.Connected;\n        case MembershipActionType.SendScheduledDelayedLeaveEvent:\n        case MembershipActionType.SendLeaveEvent:\n          return Status.Disconnecting;\n        default:\n        // pass through as not expected\n      }\n    } else if (actions.length === 2) {\n      var types = actions.map(a => a.type);\n      // normal state for connected with delayed events\n      if ((types.includes(MembershipActionType.RestartDelayedEvent) || types.includes(MembershipActionType.SendDelayedEvent) && this.state.hasMemberStateEvent) && types.includes(MembershipActionType.UpdateExpiry)) {\n        return Status.Connected;\n      }\n    } else if (actions.length === 3) {\n      var _types = actions.map(a => a.type);\n      // It is a correct connected state if we already schedule the next Restart but have not yet cleaned up\n      // the current restart.\n      if (_types.filter(t => t === MembershipActionType.RestartDelayedEvent).length === 2 && _types.includes(MembershipActionType.UpdateExpiry)) {\n        return Status.Connected;\n      }\n    }\n    if (!this.scheduler.running) {\n      return Status.Disconnected;\n    }\n    this.logger.error(\"MembershipManager has an unknown state. Actions: \", actions);\n    return Status.Unknown;\n  }\n  get probablyLeft() {\n    return this.state.probablyLeft;\n  }\n  get delayId() {\n    return this.state.delayId;\n  }\n}\n\n/**\n * Implementation of the Membership manager that uses sticky events\n * rather than state events.\n */\nexport class StickyEventMembershipManager extends MembershipManager {\n  constructor(joinConfig, room, clientWithSticky, sessionDescription,\n  // this needs to become a uuid so that consecutive join/leaves result in a key rotation.\n  // we keep it as a string for now for backwards compatibility.\n  memberId, parentLogger) {\n    super(joinConfig, room, clientWithSticky, sessionDescription, parentLogger);\n    this.clientWithSticky = clientWithSticky;\n    this.memberId = memberId;\n    _defineProperty(this, \"clientSendDelayedDisconnectMembership\", () => this.clientWithSticky._unstable_sendStickyDelayedEvent(this.room.roomId, MEMBERSHIP_STICKY_DURATION_MS, {\n      delay: this.delayedLeaveEventDelayMs\n    }, null, EventType.RTCMembership, {\n      msc4354_sticky_key: this.memberId\n    }));\n    _defineProperty(this, \"clientSendMembership\", myMembership => {\n      return this.clientWithSticky._unstable_sendStickyEvent(this.room.roomId, MEMBERSHIP_STICKY_DURATION_MS, null, EventType.RTCMembership, _objectSpread(_objectSpread({}, myMembership), {}, {\n        msc4354_sticky_key: this.memberId\n      }));\n    });\n  }\n  actionUpdateFromErrors(e, t, m) {\n    var _StickyEventMembershi;\n    return super.actionUpdateFromErrors(e, t, (_StickyEventMembershi = StickyEventMembershipManager.nameMap.get(m)) !== null && _StickyEventMembershi !== void 0 ? _StickyEventMembershi : \"unknown\");\n  }\n  makeMyMembership(expires) {\n    var ownMembership = this.ownMembership;\n    var livekitTransport = isLivekitTransportConfig(this.rtcTransport) ? this.rtcTransport : undefined;\n    var relationObject = ownMembership !== null && ownMembership !== void 0 && ownMembership.eventId ? {\n      \"m.relation\": {\n        rel_type: RelationType.Reference,\n        event_id: ownMembership === null || ownMembership === void 0 ? void 0 : ownMembership.eventId\n      }\n    } : {};\n    return _objectSpread({\n      application: _objectSpread({\n        type: this.slotDescription.application\n      }, this.callIntent ? {\n        \"m.call.intent\": this.callIntent\n      } : {}),\n      slot_id: slotDescriptionToId(this.slotDescription),\n      // Make sure we do not add the alias to the transport.\n      // It is not needed in matrix2.0. The additional session information will be used to find the right alias on the sfu.\n      rtc_transports: livekitTransport ? [{\n        type: livekitTransport.type,\n        livekit_service_url: livekitTransport.livekit_service_url\n      }] : [],\n      member: {\n        device_id: this.deviceId,\n        user_id: this.userId,\n        id: this.memberId\n      },\n      versions: []\n    }, relationObject);\n  }\n}\n_defineProperty(StickyEventMembershipManager, \"nameMap\", new Map([[\"sendStateEvent\", \"_unstable_sendStickyEvent\"], [\"sendDelayedStateEvent\", \"_unstable_sendStickyDelayedEvent\"]]));\n//# sourceMappingURL=MembershipManager.js.map","/*\nCopyright 2025 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport var KeyTransportEvents = /*#__PURE__*/function (KeyTransportEvents) {\n  KeyTransportEvents[\"ReceivedKeys\"] = \"received_keys\";\n  KeyTransportEvents[\"NotSupportedError\"] = \"not_supported_error\";\n  return KeyTransportEvents;\n}({});\n\n/**\n * Generic interface for the transport used to share room keys.\n * Keys can be shared using different transports, e.g. to-device messages or room messages.\n */\n//# sourceMappingURL=IKeyTransport.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nimport { logger as rootLogger } from \"../logger.js\";\nimport { secureRandomBase64Url } from \"../randomstring.js\";\nimport { decodeBase64, encodeUnpaddedBase64 } from \"../base64.js\";\nimport { safeGetRetryAfterMs } from \"../http-api/errors.js\";\nimport { KeyTransportEvents } from \"./IKeyTransport.js\";\nimport { isMyMembership } from \"./types.js\";\n\n/**\n * The string used for the keys in the the encryption key map.\n * `@bob:examle.org:DEVICEID(UUIDRANDOM_MEMBERID_RANDOMUUID)`\n */\nexport function getEncryptionKeyMapKey(membership) {\n  return \"\".concat(membership.userId, \":\").concat(membership.deviceId, \"(\").concat(membership.memberId, \")\");\n}\n\n/**\n * This interface is for testing and for making it possible to interchange the encryption manager.\n * @internal\n */\n\n/**\n * This class implements the IEncryptionManager interface,\n * and takes care of managing the encryption keys of all rtc members:\n *  - generate new keys for the local user and send them to other participants\n *  - track all keys of all other members and update livekit.\n *\n * @internal\n */\nexport class EncryptionManager {\n  get updateEncryptionKeyThrottle() {\n    var _this$joinConfig$upda, _this$joinConfig;\n    return (_this$joinConfig$upda = (_this$joinConfig = this.joinConfig) === null || _this$joinConfig === void 0 ? void 0 : _this$joinConfig.updateEncryptionKeyThrottle) !== null && _this$joinConfig$upda !== void 0 ? _this$joinConfig$upda : 3000;\n  }\n  get makeKeyDelay() {\n    var _this$joinConfig$make, _this$joinConfig2;\n    return (_this$joinConfig$make = (_this$joinConfig2 = this.joinConfig) === null || _this$joinConfig2 === void 0 ? void 0 : _this$joinConfig2.makeKeyDelay) !== null && _this$joinConfig$make !== void 0 ? _this$joinConfig$make : 3000;\n  }\n  get useKeyDelay() {\n    var _this$joinConfig$useK, _this$joinConfig3;\n    return (_this$joinConfig$useK = (_this$joinConfig3 = this.joinConfig) === null || _this$joinConfig3 === void 0 ? void 0 : _this$joinConfig3.useKeyDelay) !== null && _this$joinConfig$useK !== void 0 ? _this$joinConfig$useK : 5000;\n  }\n  constructor(membership, getMemberships, transport, statistics, onEncryptionKeysChanged, parentLogger) {\n    var _this = this;\n    this.membership = membership;\n    this.getMemberships = getMemberships;\n    this.transport = transport;\n    this.statistics = statistics;\n    this.onEncryptionKeysChanged = onEncryptionKeysChanged;\n    _defineProperty(this, \"manageMediaKeys\", false);\n    _defineProperty(this, \"keysEventUpdateTimeout\", void 0);\n    _defineProperty(this, \"makeNewKeyTimeout\", void 0);\n    _defineProperty(this, \"setNewKeyTimeouts\", new Set());\n    _defineProperty(this, \"encryptionKeys\", new Map());\n    _defineProperty(this, \"lastEncryptionKeyUpdateRequest\", void 0);\n    // We use this to store the last membership fingerprints we saw, so we can proactively re-send encryption keys\n    // if it looks like a membership has been updated.\n    _defineProperty(this, \"lastMembershipFingerprints\", void 0);\n    _defineProperty(this, \"latestGeneratedKeyIndex\", -1);\n    _defineProperty(this, \"joinConfig\", void 0);\n    _defineProperty(this, \"logger\", void 0);\n    _defineProperty(this, \"joined\", false);\n    /**\n     * Re-sends the encryption keys room event\n     */\n    _defineProperty(this, \"sendEncryptionKeysEvent\", /*#__PURE__*/function () {\n      var _ref = _asyncToGenerator(function* (indexToSend) {\n        if (_this.keysEventUpdateTimeout !== undefined) {\n          clearTimeout(_this.keysEventUpdateTimeout);\n          _this.keysEventUpdateTimeout = undefined;\n        }\n        _this.lastEncryptionKeyUpdateRequest = Date.now();\n        if (!_this.joined) return;\n        var myKeys = _this.getKeysForParticipant(_this.membership);\n        if (!myKeys) {\n          _this.logger.warn(\"Tried to send encryption keys event but no keys found!\");\n          return;\n        }\n        if (typeof indexToSend !== \"number\" && _this.latestGeneratedKeyIndex === -1) {\n          _this.logger.warn(\"Tried to send encryption keys event but no current key index found!\");\n          return;\n        }\n        var keyIndexToSend = indexToSend !== null && indexToSend !== void 0 ? indexToSend : _this.latestGeneratedKeyIndex;\n        _this.logger.info(\"Try sending encryption keys event. keyIndexToSend=\".concat(keyIndexToSend, \" (method parameter: \").concat(indexToSend, \")\"));\n        var keyToSend = myKeys[keyIndexToSend];\n        try {\n          _this.statistics.counters.roomEventEncryptionKeysSent += 1;\n          var targets = _this.getMemberships().filter(membership => {\n            return membership.sender != undefined;\n          }).map(membership => {\n            return {\n              userId: membership.sender,\n              deviceId: membership.deviceId,\n              membershipTs: membership.createdTs()\n            };\n          });\n          yield _this.transport.sendKey(encodeUnpaddedBase64(keyToSend), keyIndexToSend, targets);\n          _this.logger.debug(\"sendEncryptionKeysEvent participantId=\".concat(_this.membership.userId, \":\").concat(_this.membership.deviceId, \" numKeys=\").concat(myKeys.length, \" currentKeyIndex=\").concat(_this.latestGeneratedKeyIndex, \" keyIndexToSend=\").concat(keyIndexToSend));\n        } catch (error) {\n          if (_this.keysEventUpdateTimeout === undefined) {\n            var resendDelay = safeGetRetryAfterMs(error, 5000);\n            _this.logger.warn(\"Failed to send m.call.encryption_key, retrying in \".concat(resendDelay), error);\n            _this.keysEventUpdateTimeout = setTimeout(() => void _this.sendEncryptionKeysEvent(), resendDelay);\n          } else {\n            _this.logger.info(\"Not scheduling key resend as another re-send is already pending\");\n          }\n        }\n      });\n      return function (_x) {\n        return _ref.apply(this, arguments);\n      };\n    }());\n    _defineProperty(this, \"onNewKeyReceived\", (membership, keyBase64Encoded, index, timestamp) => {\n      this.logger.debug(\"Received key over key transport \".concat(membership.userId, \":\").concat(membership.deviceId, \" at index \").concat(index));\n      this.setEncryptionKey(membership, index, keyBase64Encoded, timestamp);\n    });\n    _defineProperty(this, \"onRotateKeyTimeout\", () => {\n      if (!this.manageMediaKeys) return;\n      this.makeNewKeyTimeout = undefined;\n      this.logger.info(\"Making new sender key for key rotation\");\n      var newKeyIndex = this.makeNewSenderKey(true);\n      // send immediately: if we're about to start sending with a new key, it's\n      // important we get it out to others as soon as we can.\n      void this.sendEncryptionKeysEvent(newKeyIndex);\n    });\n    this.logger = (parentLogger !== null && parentLogger !== void 0 ? parentLogger : rootLogger).getChild(\"[EncryptionManager]\");\n  }\n  rtcBackendIdentityFromMembershipParts(membership) {\n    // Implement logic to construct rtcBackendIdentity from membership parts\n    return \"\".concat(membership.userId, \":\").concat(membership.deviceId);\n  }\n  getEncryptionKeys() {\n    var keysMap = new Map();\n    for (var [userId, userKeyEntry] of this.encryptionKeys) {\n      var keys = userKeyEntry.map((entry, index) => ({\n        key: entry.key,\n        membership: entry.membership,\n        keyIndex: index,\n        rtcBackendIdentity: this.rtcBackendIdentityFromMembershipParts(entry.membership)\n      }));\n      keysMap.set(userId, keys);\n    }\n    return keysMap;\n  }\n  join(joinConfig) {\n    var _this$joinConfig$mana, _this$joinConfig4, _this$joinConfig5;\n    this.joinConfig = joinConfig;\n    this.joined = true;\n    this.manageMediaKeys = (_this$joinConfig$mana = (_this$joinConfig4 = this.joinConfig) === null || _this$joinConfig4 === void 0 ? void 0 : _this$joinConfig4.manageMediaKeys) !== null && _this$joinConfig$mana !== void 0 ? _this$joinConfig$mana : this.manageMediaKeys;\n    this.transport.on(KeyTransportEvents.ReceivedKeys, this.onNewKeyReceived);\n    this.transport.start();\n    if ((_this$joinConfig5 = this.joinConfig) !== null && _this$joinConfig5 !== void 0 && _this$joinConfig5.manageMediaKeys) {\n      this.makeNewSenderKey();\n      this.requestSendCurrentKey();\n    }\n  }\n  leave() {\n    // clear our encryption keys as we're done with them now (we'll\n    // make new keys if we rejoin). We leave keys for other participants\n    // as they may still be using the same ones.\n    this.encryptionKeys.set(getEncryptionKeyMapKey(this.membership), []);\n    this.transport.off(KeyTransportEvents.ReceivedKeys, this.onNewKeyReceived);\n    this.transport.stop();\n    if (this.makeNewKeyTimeout !== undefined) {\n      clearTimeout(this.makeNewKeyTimeout);\n      this.makeNewKeyTimeout = undefined;\n    }\n    for (var t of this.setNewKeyTimeouts) {\n      clearTimeout(t);\n    }\n    this.setNewKeyTimeouts.clear();\n    this.manageMediaKeys = false;\n    this.joined = false;\n  }\n  onMembershipsUpdate(oldMemberships) {\n    if (this.manageMediaKeys && this.joined) {\n      var oldMembershipIds = new Set(oldMemberships.filter(m => !isMyMembership(m, this.membership.userId, this.membership.deviceId)).map(getEncryptionKeyMapKey));\n      var newMembershipIds = new Set(this.getMemberships().filter(m => !isMyMembership(m, this.membership.userId, this.membership.deviceId)).map(getEncryptionKeyMapKey));\n\n      // We can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/symmetricDifference\n      // for this once available\n      var anyLeft = Array.from(oldMembershipIds).some(x => !newMembershipIds.has(x));\n      var anyJoined = Array.from(newMembershipIds).some(x => !oldMembershipIds.has(x));\n      var oldFingerprints = this.lastMembershipFingerprints;\n      // always store the fingerprints of these latest memberships\n      this.storeLastMembershipFingerprints();\n      if (anyLeft) {\n        if (this.makeNewKeyTimeout) {\n          // existing rotation in progress, so let it complete\n        } else {\n          this.logger.debug(\"Member(s) have left: queueing sender key rotation\");\n          this.makeNewKeyTimeout = setTimeout(this.onRotateKeyTimeout, this.makeKeyDelay);\n        }\n      } else if (anyJoined) {\n        this.logger.debug(\"New member(s) have joined: re-sending keys\");\n        this.requestSendCurrentKey();\n      } else if (oldFingerprints) {\n        // does it look like any of the members have updated their memberships?\n        var newFingerprints = this.lastMembershipFingerprints;\n\n        // We can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/symmetricDifference\n        // for this once available\n        var candidateUpdates = Array.from(oldFingerprints).some(x => !newFingerprints.has(x)) || Array.from(newFingerprints).some(x => !oldFingerprints.has(x));\n        if (candidateUpdates) {\n          this.logger.debug(\"Member(s) have updated/reconnected: re-sending keys to everyone\");\n          this.requestSendCurrentKey();\n        }\n      }\n    }\n  }\n\n  /**\n   * Generate a new sender key and add it at the next available index\n   * @param delayBeforeUse - If true, wait for a short period before setting the key for the\n   *                         media encryptor to use. If false, set the key immediately.\n   * @returns The index of the new key\n   */\n  makeNewSenderKey() {\n    var delayBeforeUse = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n    var encryptionKey = secureRandomBase64Url(16);\n    var encryptionKeyIndex = this.getNewEncryptionKeyIndex();\n    this.logger.info(\"Generated new key at index \" + encryptionKeyIndex);\n    this.setEncryptionKey(this.membership, encryptionKeyIndex, encryptionKey, Date.now(), delayBeforeUse);\n    return encryptionKeyIndex;\n  }\n\n  /**\n   * Requests that we resend our current keys to the room. May send a keys event immediately\n   * or queue for alter if one has already been sent recently.\n   */\n  requestSendCurrentKey() {\n    if (!this.manageMediaKeys) return;\n    if (this.lastEncryptionKeyUpdateRequest && this.lastEncryptionKeyUpdateRequest + this.updateEncryptionKeyThrottle > Date.now()) {\n      this.logger.info(\"Last encryption key event sent too recently: postponing\");\n      if (this.keysEventUpdateTimeout === undefined) {\n        this.keysEventUpdateTimeout = setTimeout(() => void this.sendEncryptionKeysEvent(), this.updateEncryptionKeyThrottle);\n      }\n      return;\n    }\n    void this.sendEncryptionKeysEvent();\n  }\n\n  /**\n   * Get the known encryption keys for a given participant device.\n   *\n   * @param membership - The membership identity parts of the participant\n   * @returns The encryption keys for the given participant, or undefined if they are not known.\n   */\n  getKeysForParticipant(membership) {\n    var _this$encryptionKeys$;\n    return (_this$encryptionKeys$ = this.encryptionKeys.get(getEncryptionKeyMapKey(membership))) === null || _this$encryptionKeys$ === void 0 ? void 0 : _this$encryptionKeys$.map(entry => entry.key);\n  }\n  storeLastMembershipFingerprints() {\n    this.lastMembershipFingerprints = new Set(this.getMemberships().filter(m => !isMyMembership(m, this.membership.userId, this.membership.deviceId)).map(m => \"\".concat(getEncryptionKeyMapKey(m), \":\").concat(m.createdTs())));\n  }\n  getNewEncryptionKeyIndex() {\n    if (this.latestGeneratedKeyIndex === -1) {\n      return 0;\n    }\n\n    // maximum key index is 255\n    return (this.latestGeneratedKeyIndex + 1) % 256;\n  }\n\n  /**\n   * Sets an encryption key at a specified index for a participant.\n   * The encryption keys for the local participant are also stored here under the\n   * user and device ID of the local participant.\n   * If the key is older than the existing key at the index, it will be ignored.\n   * @param userId - The user ID of the participant\n   * @param deviceId - Device ID of the participant\n   * @param encryptionKeyIndex - The index of the key to set\n   * @param encryptionKeyString - The string representation of the key to set in base64\n   * @param timestamp - The timestamp of the key. We assume that these are monotonic for each participant device.\n   * @param delayBeforeUse - If true, delay before emitting a key changed event. Useful when setting\n   *                         encryption keys for the local participant to allow time for the key to\n   *                         be distributed.\n   */\n  setEncryptionKey(membership, encryptionKeyIndex, encryptionKeyString, timestamp) {\n    var delayBeforeUse = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;\n    this.logger.debug(\"Setting encryption key for \".concat(membership.userId, \":\").concat(membership.deviceId, \" at index \").concat(encryptionKeyIndex));\n    var keyBin = decodeBase64(encryptionKeyString);\n    var mapKey = getEncryptionKeyMapKey(membership);\n    if (!this.encryptionKeys.has(mapKey)) {\n      this.encryptionKeys.set(mapKey, []);\n    }\n    var participantKeys = this.encryptionKeys.get(mapKey);\n    var existingKeyAtIndex = participantKeys[encryptionKeyIndex];\n    if (existingKeyAtIndex) {\n      if (existingKeyAtIndex.timestamp > timestamp) {\n        this.logger.info(\"Ignoring new key at index \".concat(encryptionKeyIndex, \" for \").concat(mapKey, \" as it is older than existing known key\"));\n        return;\n      }\n      if (keysEqual(existingKeyAtIndex.key, keyBin)) {\n        existingKeyAtIndex.timestamp = timestamp;\n        return;\n      }\n    }\n    if (membership.userId === this.membership.userId && membership.deviceId === this.membership.deviceId) {\n      // It is important to already update the latestGeneratedKeyIndex here\n      // NOT IN THE `delayBeforeUse` `setTimeout`.\n      // Even though this is where we call onEncryptionKeysChanged and set the key in EC (and livekit).\n      // It needs to happen here because we will send the key before the timeout has passed and sending\n      // the key will use latestGeneratedKeyIndex as the index. if we update it in the `setTimeout` callback\n      // it will use the wrong index (index - 1)!\n      this.latestGeneratedKeyIndex = encryptionKeyIndex;\n    }\n    participantKeys[encryptionKeyIndex] = {\n      key: keyBin,\n      timestamp,\n      membership: membership\n    };\n    if (delayBeforeUse) {\n      var useKeyTimeout = setTimeout(() => {\n        this.setNewKeyTimeouts.delete(useKeyTimeout);\n        this.logger.info(\"Delayed-emitting key changed event for \".concat(mapKey, \" index \").concat(encryptionKeyIndex));\n        this.onEncryptionKeysChanged(keyBin, encryptionKeyIndex, membership, this.rtcBackendIdentityFromMembershipParts(membership));\n      }, this.useKeyDelay);\n      this.setNewKeyTimeouts.add(useKeyTimeout);\n    } else {\n      this.onEncryptionKeysChanged(keyBin, encryptionKeyIndex, membership, this.rtcBackendIdentityFromMembershipParts(membership));\n    }\n  }\n}\nfunction keysEqual(a, b) {\n  if (a === b) return true;\n  return !!a && !!b && a.length === b.length && a.every((x, i) => x === b[i]);\n}\n//# sourceMappingURL=EncryptionManager.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2025 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { getEncryptionKeyMapKey } from \"./EncryptionManager.js\";\n/**\n * Detects when a key for a given index is outdated.\n */\nexport class OutdatedKeyFilter {\n  constructor() {\n    // Map of participantId -> keyIndex -> timestamp\n    _defineProperty(this, \"tsBuffer\", new Map());\n  }\n\n  /**\n   * Check if there is a recent key with the same keyId (index) and then use the creationTS to decide what to\n   * do with the key. If the key received is older than the one already in the buffer, it is ignored.\n   * @param participantId\n   * @param item\n   */\n  isOutdated(membership, item) {\n    var _this$tsBuffer$get;\n    var mapKey = getEncryptionKeyMapKey(membership);\n    if (!this.tsBuffer.has(mapKey)) {\n      this.tsBuffer.set(mapKey, new Map());\n    }\n    var latestTimestamp = (_this$tsBuffer$get = this.tsBuffer.get(mapKey)) === null || _this$tsBuffer$get === void 0 ? void 0 : _this$tsBuffer$get.get(item.keyIndex);\n    if (latestTimestamp && latestTimestamp > item.creationTS) {\n      // The existing key is more recent, ignore this one\n      return true;\n    }\n    this.tsBuffer.get(mapKey).set(item.keyIndex, item.creationTS);\n    return false;\n  }\n}\n//# sourceMappingURL=utils.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2025 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { getEncryptionKeyMapKey } from \"./EncryptionManager.js\";\nimport { CallMembership } from \"./CallMembership.js\";\nimport { decodeBase64, encodeBase64 } from \"../base64.js\";\nimport { KeyTransportEvents } from \"./IKeyTransport.js\";\nimport { sleep } from \"../utils.js\";\nimport { OutdatedKeyFilter } from \"./utils.js\";\n\n/**\n * RTCEncryptionManager is used to manage the encryption keys for a call.\n *\n * It is responsible for distributing the keys to the other participants and rotating the keys if needed.\n *\n * This manager when used with to-device transport will share the existing key only to new joiners, and rotate\n * if there is a leaver.\n *\n * XXX In the future we want to distribute a ratcheted key not the current one for new joiners.\n */\nexport class RTCEncryptionManager {\n  /**\n   *\n   * @param ownMembership - our own membership info\n   * @param getMemberships - function to get current memberships\n   * @param transport - key transport (room or to-device)\n   * @param statistics - statistics collector\n   * @param onEncryptionKeysChanged - callback to notify the media layer of new keys\n   * @param parentLogger - optional parent logger\n   * @param rtcBackendIdProvider - A function to compute the rtc backend identity, exposed for testing purposes\n   */\n  constructor(ownMembership, getMemberships, transport, statistics,\n  // Callback to notify the media layer of new keys\n  onEncryptionKeysChanged, parentLogger, rtcBackendIdProvider) {\n    this.ownMembership = ownMembership;\n    this.getMemberships = getMemberships;\n    this.transport = transport;\n    this.statistics = statistics;\n    this.onEncryptionKeysChanged = onEncryptionKeysChanged;\n    // This is a stop-gap solution for now. The preferred way to handle this case would be instead\n    // to create a NoOpEncryptionManager that does nothing and use it for the session.\n    // This will be done when removing the legacy EncryptionManager.\n    _defineProperty(this, \"manageMediaKeys\", false);\n    _defineProperty(this, \"useHashedRtcBackendIdentity\", false);\n    _defineProperty(this, \"ownRtcBackendIdentityCache\", void 0);\n    /**\n     * Store the key rings for each participant.\n     * The encryption manager stores the keys because the application layer might not be ready yet to handle the keys.\n     * The keys are stored and can be retrieved later when the application layer is ready {@link RTCEncryptionManager#getEncryptionKeys}.\n     */\n    _defineProperty(this, \"participantKeyRings\", new Map());\n    // The current per-sender media key for this device\n    _defineProperty(this, \"outboundSession\", null);\n    /**\n     * Ensures that there is only one distribute operation at a time for that call.\n     */\n    _defineProperty(this, \"currentKeyDistributionPromise\", null);\n    /**\n     * The time to wait before using the outbound session after it has been distributed.\n     * This is to ensure that the key is delivered to all participants before it is used.\n     * When creating the first key, this is set to 0 so that the key can be used immediately.\n     */\n    _defineProperty(this, \"useKeyDelay\", 5000);\n    /**\n     * We want to avoid rolling out a new outbound key when the previous one was created less than `keyRotationGracePeriodMs` milliseconds ago.\n     * This is to avoid expensive key rotations when users quickly join the call in a row.\n     *\n     * This must be higher than `useKeyDelay` to have an effect.\n     * If it is lower, the current key will always be older than the grace period.\n     * @private\n     */\n    _defineProperty(this, \"keyRotationGracePeriodMs\", 10000);\n    /**\n     * If a new key distribution is being requested while one is going on, we will set this flag to true.\n     * This will ensure that a new round is started after the current one.\n     * @private\n     */\n    _defineProperty(this, \"needToEnsureKeyAgain\", false);\n    /**\n     * There is a possibility that keys arrive in the wrong order.\n     * For example, after a quick join/leave/join, there will be 2 keys of index 0 distributed, and\n     * if they are received in the wrong order, the stream won't be decryptable.\n     * For that reason we keep a small buffer of keys for a limited time to disambiguate.\n     * @private\n     */\n    _defineProperty(this, \"keyBuffer\", new OutdatedKeyFilter());\n    _defineProperty(this, \"logger\", undefined);\n    _defineProperty(this, \"rtcIdentityProvider\", void 0);\n    _defineProperty(this, \"keysWithoutMatchingRTCMembership\", []);\n    _defineProperty(this, \"onNewKeyReceived\", (membership, keyBase64Encoded, index, timestamp) => {\n      var _this$logger2;\n      // `manageMediaKeys` is a stop-gap solution for now. The preferred way to handle this case would be instead\n      // to create a NoOpEncryptionManager that does nothing and use it for the session.\n      // This will be done when removing the legacy EncryptionManager.\n      if (!this.manageMediaKeys) {\n        var _this$logger;\n        (_this$logger = this.logger) === null || _this$logger === void 0 || _this$logger.warn(\"Received key over transport \".concat(membership.userId, \":\").concat(membership.deviceId, \" at index \").concat(index, \" but media keys are disabled\"));\n        return;\n      }\n      (_this$logger2 = this.logger) === null || _this$logger2 === void 0 || _this$logger2.debug(\"Received key over transport \".concat(membership.userId, \":\").concat(membership.deviceId, \" at index \").concat(index));\n\n      // We received a new key, notify the video layer of this new key so that it can decrypt the frames properly.\n      var keyBin = decodeBase64(keyBase64Encoded);\n      var candidateInboundSession = {\n        key: keyBin,\n        membership,\n        keyIndex: index,\n        creationTS: timestamp\n      };\n      var outdated = this.keyBuffer.isOutdated(membership, candidateInboundSession);\n      if (!outdated) {\n        this.addKeyToParticipant(candidateInboundSession.key, candidateInboundSession.keyIndex, candidateInboundSession.membership);\n        this.statistics.counters.roomEventEncryptionKeysReceived += 1;\n      } else {\n        var _this$logger3;\n        (_this$logger3 = this.logger) === null || _this$logger3 === void 0 || _this$logger3.info(\"Received an out of order key for \".concat(membership.userId, \":\").concat(membership.deviceId, \", dropping it\"));\n      }\n    });\n    this.logger = parentLogger === null || parentLogger === void 0 ? void 0 : parentLogger.getChild(\"[EncryptionManager]\");\n    this.rtcIdentityProvider = rtcBackendIdProvider !== null && rtcBackendIdProvider !== void 0 ? rtcBackendIdProvider : CallMembership.computeRtcIdentityRaw;\n  }\n  getOwnRtcBackendIdentity() {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      if (_this.ownRtcBackendIdentityCache) return _this.ownRtcBackendIdentityCache;\n      if (_this.useHashedRtcBackendIdentity) {\n        var _this$logger4;\n        var {\n          userId,\n          deviceId,\n          memberId\n        } = _this.ownMembership;\n        (_this$logger4 = _this.logger) === null || _this$logger4 === void 0 || _this$logger4.info(// If we see this log multiple times, we need to reconsider the precompute call of getOwnRtcBackendIdentity\n        \"Computing RTC backend identity for \".concat(userId, \":\").concat(deviceId, \":\").concat(memberId, \" (SHOULD ONLY BE CALLED ONCE)\"));\n        _this.ownRtcBackendIdentityCache = yield _this.rtcIdentityProvider(userId, deviceId, memberId);\n      } else {\n        _this.ownRtcBackendIdentityCache = \"\".concat(_this.ownMembership.userId, \":\").concat(_this.ownMembership.deviceId);\n      }\n      return _this.ownRtcBackendIdentityCache;\n    })();\n  }\n  getEncryptionKeys() {\n    return new Map(this.participantKeyRings);\n  }\n  checkKeysWithoutMatchingRTCMembership() {\n    var keyInfoTemp = this.keysWithoutMatchingRTCMembership;\n    this.keysWithoutMatchingRTCMembership = [];\n    keyInfoTemp.forEach(keyInfo => {\n      this.addKeyToParticipant(keyInfo.key, keyInfo.keyIndex, keyInfo.membership);\n    });\n  }\n  addKeyToParticipant(key, keyIndex, membership) {\n    var knownRtcMembership = this.getMemberships();\n    var fullMembership = knownRtcMembership.find(member => member.userId === membership.userId && member.deviceId === membership.deviceId);\n    if (!fullMembership) {\n      var _this$logger5;\n      (_this$logger5 = this.logger) === null || _this$logger5 === void 0 || _this$logger5.info(\"No matching RTC membership for key from \".concat(membership.userId, \":\").concat(membership.deviceId, \", delaying key addition\"));\n      this.keysWithoutMatchingRTCMembership.push({\n        key,\n        keyIndex,\n        membership\n      });\n      return;\n    }\n    this.addKeyToParticipantWithBackendIdentity(key, keyIndex, membership, fullMembership.rtcBackendIdentity);\n  }\n  addKeyToParticipantWithBackendIdentity(key, keyIndex, membership, rtcBackendIdentity) {\n    var mapKey = getEncryptionKeyMapKey(membership);\n    if (!this.participantKeyRings.has(mapKey)) {\n      this.participantKeyRings.set(mapKey, []);\n    }\n    this.participantKeyRings.get(mapKey).push({\n      key,\n      keyIndex,\n      membership,\n      rtcBackendIdentity\n    });\n    this.onEncryptionKeysChanged(key, keyIndex, membership, rtcBackendIdentity);\n  }\n  join(joinConfig) {\n    var _joinConfig$manageMed, _joinConfig$unstableS, _joinConfig$useKeyDel, _joinConfig$keyRotati, _this$logger6;\n    this.manageMediaKeys = (_joinConfig$manageMed = joinConfig === null || joinConfig === void 0 ? void 0 : joinConfig.manageMediaKeys) !== null && _joinConfig$manageMed !== void 0 ? _joinConfig$manageMed : true; // default to true\n    this.useHashedRtcBackendIdentity = (_joinConfig$unstableS = joinConfig === null || joinConfig === void 0 ? void 0 : joinConfig.unstableSendStickyEvents) !== null && _joinConfig$unstableS !== void 0 ? _joinConfig$unstableS : false;\n    this.useKeyDelay = (_joinConfig$useKeyDel = joinConfig === null || joinConfig === void 0 ? void 0 : joinConfig.useKeyDelay) !== null && _joinConfig$useKeyDel !== void 0 ? _joinConfig$useKeyDel : 1000;\n    this.keyRotationGracePeriodMs = (_joinConfig$keyRotati = joinConfig === null || joinConfig === void 0 ? void 0 : joinConfig.keyRotationGracePeriodMs) !== null && _joinConfig$keyRotati !== void 0 ? _joinConfig$keyRotati : 10000;\n    this.transport.on(KeyTransportEvents.ReceivedKeys, this.onNewKeyReceived);\n    void this.getOwnRtcBackendIdentity(); // precompute own identity\n\n    (_this$logger6 = this.logger) === null || _this$logger6 === void 0 || _this$logger6.info(\"Joining room\");\n    this.transport.start();\n  }\n  leave() {\n    this.transport.off(KeyTransportEvents.ReceivedKeys, this.onNewKeyReceived);\n    this.transport.stop();\n    this.participantKeyRings.clear();\n  }\n\n  /**\n   * Will ensure that a new key is distributed and used to encrypt our media.\n   * If there is already a key distribution in progress, it will schedule a new distribution round just after the current one is completed.\n   * If this function is called repeatedly while a distribution is in progress,\n   * the calls will be coalesced to a single new distribution (that will start just after the current one has completed).\n   */\n  ensureKeyDistribution() {\n    // `manageMediaKeys` is a stop-gap solution for now. The preferred way to handle this case would be instead\n    // to create a NoOpEncryptionManager that does nothing and use it for the session.\n    // This will be done when removing the legacy EncryptionManager.\n    if (!this.manageMediaKeys) return;\n    if (this.currentKeyDistributionPromise == null) {\n      var _this$logger7;\n      (_this$logger7 = this.logger) === null || _this$logger7 === void 0 || _this$logger7.debug(\"No active rollout, start a new one\");\n      // start a rollout\n      this.currentKeyDistributionPromise = this.rolloutOutboundKey().then(() => {\n        var _this$logger8;\n        (_this$logger8 = this.logger) === null || _this$logger8 === void 0 || _this$logger8.debug(\"Rollout completed\");\n        this.currentKeyDistributionPromise = null;\n        if (this.needToEnsureKeyAgain) {\n          var _this$logger9;\n          (_this$logger9 = this.logger) === null || _this$logger9 === void 0 || _this$logger9.debug(\"New Rollout needed\");\n          this.needToEnsureKeyAgain = false;\n          // rollout a new one\n          this.ensureKeyDistribution();\n        }\n      });\n    } else {\n      var _this$logger0;\n      // There is a rollout in progress, but a key rotation is requested (could be caused by a ownMembership change)\n      // Remember that a new rotation is needed after the current one.\n      (_this$logger0 = this.logger) === null || _this$logger0 === void 0 || _this$logger0.debug(\"Rollout in progress, a new rollout will be started after the current one\");\n      this.needToEnsureKeyAgain = true;\n    }\n  }\n  /**\n   * Called when the ownMembership of the call changes.\n   * This encryption manager is very basic, it will rotate the key everytime this is called.\n   * @param oldMemberships - This parameter is not used here, but it is kept for compatibility with the interface.\n   */\n  onMembershipsUpdate() {\n    var _this$logger1;\n    var oldMemberships = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n    (_this$logger1 = this.logger) === null || _this$logger1 === void 0 || _this$logger1.trace(\"onMembershipsUpdate\");\n\n    // Ensure the key is distributed. This will be no-op if the key is already being distributed to everyone.\n    // If there is an ongoing distribution, it will be completed before a new one is started.\n    this.ensureKeyDistribution();\n    // ensure key emission to the rtc backend\n    this.checkKeysWithoutMatchingRTCMembership();\n  }\n  rolloutOutboundKey() {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      var _this2$outboundSessio, _this2$outboundSessio2;\n      var isFirstKey = _this2.outboundSession == null;\n      if (isFirstKey) {\n        // create the first key\n        var firstKey = {\n          key: _this2.generateRandomKey(),\n          creationTS: Date.now(),\n          sharedWith: [],\n          keyId: 0\n        };\n        _this2.outboundSession = firstKey;\n        _this2.addKeyToParticipantWithBackendIdentity(firstKey.key, firstKey.keyId, _this2.ownMembership, yield _this2.getOwnRtcBackendIdentity());\n      }\n      // get current memberships\n      var toShareWith = _this2.getMemberships().filter(membership => {\n        return membership.sender != undefined;\n      }).map(membership => {\n        return {\n          userId: membership.sender,\n          deviceId: membership.deviceId,\n          membershipTs: membership.createdTs()\n        };\n      });\n      var alreadySharedWith = (_this2$outboundSessio = (_this2$outboundSessio2 = _this2.outboundSession) === null || _this2$outboundSessio2 === void 0 ? void 0 : _this2$outboundSessio2.sharedWith) !== null && _this2$outboundSessio !== void 0 ? _this2$outboundSessio : [];\n\n      // Some users might have rotate their ownMembership event (formally called fingerprint) meaning they might have\n      // clear their key. Reset the `alreadySharedWith` flag for them.\n      alreadySharedWith = alreadySharedWith.filter(x =>\n      // If there was a member with same userId and deviceId but different membershipTs, we need to clear it\n      !toShareWith.some(o => x.userId == o.userId && x.deviceId == o.deviceId && x.membershipTs != o.membershipTs));\n      var anyLeft = alreadySharedWith.filter(x => !toShareWith.some(o => x.userId == o.userId && x.deviceId == o.deviceId && x.membershipTs == o.membershipTs));\n      var anyJoined = toShareWith.filter(x => !alreadySharedWith.some(o => x.userId == o.userId && x.deviceId == o.deviceId && x.membershipTs == o.membershipTs));\n      var toDistributeTo = [];\n      var outboundKey;\n      var hasKeyChanged = false;\n      if (anyLeft.length > 0) {\n        // We need to rotate the key\n        var newOutboundKey = _this2.createNewOutboundSession();\n        hasKeyChanged = true;\n        toDistributeTo = toShareWith;\n        outboundKey = newOutboundKey;\n      } else if (anyJoined.length > 0) {\n        var now = Date.now();\n        var keyAge = now - _this2.outboundSession.creationTS;\n        // If the current key is recently created (less than `keyRotationGracePeriodMs`), we can keep it and just distribute it to the new joiners.\n        if (keyAge < _this2.keyRotationGracePeriodMs) {\n          var _this2$logger;\n          // keep the same key\n          // XXX In the future we want to distribute a ratcheted key, not the current one\n          (_this2$logger = _this2.logger) === null || _this2$logger === void 0 || _this2$logger.debug(\"New joiners detected, but the key is recent enough (age:\".concat(keyAge, \"), keeping it\"));\n          toDistributeTo = anyJoined;\n          outboundKey = _this2.outboundSession;\n        } else {\n          var _this2$logger2;\n          // We need to rotate the key\n          (_this2$logger2 = _this2.logger) === null || _this2$logger2 === void 0 || _this2$logger2.debug(\"New joiners detected, rotating the key\");\n          var _newOutboundKey = _this2.createNewOutboundSession();\n          hasKeyChanged = true;\n          toDistributeTo = toShareWith;\n          outboundKey = _newOutboundKey;\n        }\n      } else {\n        // no changes\n        return;\n      }\n      try {\n        var _this2$logger3, _this2$logger4;\n        (_this2$logger3 = _this2.logger) === null || _this2$logger3 === void 0 || _this2$logger3.trace(\"Sending key...\");\n        yield _this2.transport.sendKey(encodeBase64(outboundKey.key), outboundKey.keyId, toDistributeTo);\n        _this2.statistics.counters.roomEventEncryptionKeysSent += 1;\n        outboundKey.sharedWith.push(...toDistributeTo);\n        (_this2$logger4 = _this2.logger) === null || _this2$logger4 === void 0 || _this2$logger4.trace(\"key index:\".concat(outboundKey.keyId, \" sent to \").concat(outboundKey.sharedWith.map(m => \"\".concat(m.userId, \":\").concat(m.deviceId)).join(\",\")));\n        if (hasKeyChanged) {\n          var _this2$logger5, _this2$logger6;\n          // Delay a bit before using this key\n          // It is recommended not to start using a key immediately but instead wait for a short time to make sure it is delivered.\n          (_this2$logger5 = _this2.logger) === null || _this2$logger5 === void 0 || _this2$logger5.trace(\"Delay Rollout for key:\".concat(outboundKey.keyId, \"...\"));\n          yield sleep(_this2.useKeyDelay);\n          (_this2$logger6 = _this2.logger) === null || _this2$logger6 === void 0 || _this2$logger6.trace(\"...Delayed rollout of index:\".concat(outboundKey.keyId, \" \"));\n          _this2.addKeyToParticipantWithBackendIdentity(outboundKey.key, outboundKey.keyId, _this2.ownMembership, yield _this2.getOwnRtcBackendIdentity());\n        }\n      } catch (err) {\n        var _this2$logger7;\n        (_this2$logger7 = _this2.logger) === null || _this2$logger7 === void 0 || _this2$logger7.error(\"Failed to rollout key\", err);\n      }\n    })();\n  }\n  createNewOutboundSession() {\n    var _this$logger10;\n    var newOutboundKey = {\n      key: this.generateRandomKey(),\n      creationTS: Date.now(),\n      sharedWith: [],\n      keyId: this.nextKeyIndex()\n    };\n    (_this$logger10 = this.logger) === null || _this$logger10 === void 0 || _this$logger10.info(\"creating new outbound key index:\".concat(newOutboundKey.keyId));\n    // Set this new key as the current one\n    this.outboundSession = newOutboundKey;\n    return newOutboundKey;\n  }\n  nextKeyIndex() {\n    if (this.outboundSession) {\n      return (this.outboundSession.keyId + 1) % 256;\n    }\n    return 0;\n  }\n  generateRandomKey() {\n    var key = new Uint8Array(16);\n    globalThis.crypto.getRandomValues(key);\n    return key;\n  }\n}\n//# sourceMappingURL=RTCEncryptionManager.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2025 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.js\";\nimport { KeyTransportEvents } from \"./IKeyTransport.js\";\nimport { logger as rootLogger } from \"../logger.js\";\nimport { ClientEvent } from \"../client.js\";\nimport { EventType } from \"../@types/event.js\";\nexport class NotSupportedError extends Error {\n  constructor(message) {\n    super(message);\n  }\n  get name() {\n    return \"NotSupportedError\";\n  }\n}\n/**\n * ToDeviceKeyTransport is used to send MatrixRTC keys to other devices using the\n * to-device CS-API.\n */\nexport class ToDeviceKeyTransport extends TypedEventEmitter {\n  setParentLogger(parentLogger) {\n    this.logger = parentLogger.getChild(\"[ToDeviceKeyTransport]\");\n  }\n  constructor(membership, roomId, client, statistics, parentLogger) {\n    super();\n    this.membership = membership;\n    this.roomId = roomId;\n    this.client = client;\n    this.statistics = statistics;\n    _defineProperty(this, \"logger\", rootLogger);\n    _defineProperty(this, \"onToDeviceEvent\", event => {\n      if (event.getType() !== EventType.CallEncryptionKeysPrefix) {\n        // Ignore this is not a call encryption event\n        return;\n      }\n\n      // TODO: Not possible to check if the event is encrypted or not\n      // see https://github.com/matrix-org/matrix-rust-sdk/issues/4883\n      // if (evnt.getWireType() != EventType.RoomMessageEncrypted) {\n      //     // WARN: The call keys were sent in clear. Ignore them\n      //     logger.warn(`Call encryption keys sent in clear from: ${event.getSender()}`);\n      //     return;\n      // }\n\n      var content = this.getValidEventContent(event);\n      if (!content) return;\n      if (!event.getSender()) return;\n      this.receiveCallKeyEvent(event.getSender(), content);\n    });\n    this.setParentLogger(parentLogger !== null && parentLogger !== void 0 ? parentLogger : rootLogger);\n  }\n  start() {\n    this.client.on(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);\n  }\n  stop() {\n    this.client.off(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);\n  }\n  sendKey(keyBase64Encoded, index, members) {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      var content = {\n        keys: {\n          index: index,\n          key: keyBase64Encoded\n        },\n        room_id: _this.roomId,\n        member: {\n          claimed_device_id: _this.membership.deviceId,\n          id: _this.membership.memberId\n        },\n        session: {\n          call_id: \"\",\n          application: \"m.call\",\n          scope: \"m.room\"\n        },\n        sent_ts: Date.now()\n      };\n      var targets = members.map(member => {\n        return {\n          userId: member.userId,\n          deviceId: member.deviceId\n        };\n      })\n      // filter out me\n      .filter(member => !(member.userId == _this.membership.userId && member.deviceId == _this.membership.deviceId));\n      if (targets.length > 0) {\n        yield _this.client.encryptAndSendToDevice(EventType.CallEncryptionKeysPrefix, targets, content).catch(error => {\n          var msg = error.message;\n          // This is not ideal. We would want to have a custom error type for unsupported actions.\n          // This is not part of the widget API spec. Since as of now there are only two implementations:\n          // Rust SDK + JS-SDK, and the JS-SDK does support to-device sending, we can assume that\n          // this is a widget driver issue error message.\n          if (msg.includes(\"unknown variant\") && msg.includes(\"send_to_device\") || msg.includes(\"not supported\")) {\n            throw new NotSupportedError(\"The widget driver does not support to-device encryption\");\n          }\n        });\n        _this.statistics.counters.roomEventEncryptionKeysSent += 1;\n      } else {\n        _this.logger.warn(\"No targets found for sending key\");\n      }\n    })();\n  }\n  receiveCallKeyEvent(fromUser, content) {\n    var _content$member$id;\n    // The event has already been validated at this point.\n\n    this.statistics.counters.roomEventEncryptionKeysReceived += 1;\n\n    // What is this, and why is it needed?\n    // Also to device events do not have an origin server ts\n    var now = Date.now();\n    var age = now - (typeof content.sent_ts === \"number\" ? content.sent_ts : now);\n    this.statistics.totals.roomEventEncryptionKeysReceivedTotalAge += age;\n    var hardcodedMemberIdAlternative = \"\".concat(fromUser, \":\").concat(content.member.claimed_device_id);\n    this.emit(KeyTransportEvents.ReceivedKeys,\n    // TODO userId this is claimed information, deviceId is claimed information\n    {\n      userId: fromUser,\n      deviceId: content.member.claimed_device_id,\n      memberId: (_content$member$id = content.member.id) !== null && _content$member$id !== void 0 ? _content$member$id : hardcodedMemberIdAlternative\n    }, content.keys.key, content.keys.index, now);\n  }\n  getValidEventContent(event) {\n    var content = event.getContent();\n    var roomId = content.room_id;\n    if (!roomId) {\n      // Invalid event\n      this.logger.warn(\"Malformed Event: invalid call encryption keys event, no roomId\");\n      return;\n    }\n    if (roomId !== this.roomId) {\n      this.logger.warn(\"Malformed Event: Mismatch roomId\");\n      return;\n    }\n    if (!content.keys || !content.keys.key || typeof content.keys.index !== \"number\") {\n      this.logger.warn(\"Malformed Event: Missing keys field\");\n      return;\n    }\n    if (!content.member || !content.member.claimed_device_id) {\n      this.logger.warn(\"Malformed Event: Missing claimed_device_id\");\n      return;\n    }\n\n    // TODO check for session related fields once the to-device encryption uses the new format.\n    return content;\n  }\n}\n//# sourceMappingURL=ToDeviceKeyTransport.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2025 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventType } from \"../@types/event.js\";\nimport { logger as rootLogger } from \"../logger.js\";\nimport { KeyTransportEvents } from \"./IKeyTransport.js\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.js\";\nimport { RoomEvent } from \"../models/room.js\";\n\n/**\n * @deprecated This is depreacted and not used anymore. use the ToDeviceTransport\n */\nexport class RoomKeyTransport extends TypedEventEmitter {\n  setParentLogger(parentLogger) {\n    this.logger = parentLogger.getChild(\"[RoomKeyTransport]\");\n  }\n  constructor(room, client, statistics, parentLogger) {\n    super();\n    this.room = room;\n    this.client = client;\n    this.statistics = statistics;\n    _defineProperty(this, \"logger\", rootLogger);\n    this.setParentLogger(parentLogger !== null && parentLogger !== void 0 ? parentLogger : rootLogger);\n  }\n  start() {\n    this.room.on(RoomEvent.Timeline, ev => void this.consumeCallEncryptionEvent(ev));\n  }\n  stop() {\n    this.room.off(RoomEvent.Timeline, ev => void this.consumeCallEncryptionEvent(ev));\n  }\n  consumeCallEncryptionEvent(event) {\n    var _arguments = arguments,\n      _this = this;\n    return _asyncToGenerator(function* () {\n      var isRetry = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : false;\n      yield _this.client.decryptEventIfNeeded(event);\n      if (event.isDecryptionFailure()) {\n        if (!isRetry) {\n          _this.logger.warn(\"Decryption failed for event \".concat(event.getId(), \": \").concat(event.decryptionFailureReason, \" will retry once only\"));\n          // retry after 1 second. After this we give up.\n          setTimeout(() => void _this.consumeCallEncryptionEvent(event, true), 1000);\n        } else {\n          _this.logger.warn(\"Decryption failed for event \".concat(event.getId(), \": \").concat(event.decryptionFailureReason));\n        }\n        return;\n      } else if (isRetry) {\n        _this.logger.info(\"Decryption succeeded for event \".concat(event.getId(), \" after retry\"));\n      }\n      if (event.getType() !== EventType.CallEncryptionKeysPrefix) return Promise.resolve();\n      if (!_this.room) {\n        _this.logger.error(\"Got room state event for unknown room \".concat(event.getRoomId(), \"!\"));\n        return Promise.resolve();\n      }\n      _this.onEncryptionEvent(event);\n    })();\n  }\n\n  /** implements {@link IKeyTransport#sendKey} */\n  sendKey(keyBase64Encoded, index, members) {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      // members not used in room transports as the keys are sent to all room members\n      var content = {\n        keys: [{\n          index: index,\n          key: keyBase64Encoded\n        }],\n        device_id: _this2.client.getDeviceId(),\n        call_id: \"\",\n        sent_ts: Date.now()\n      };\n      try {\n        yield _this2.client.sendEvent(_this2.room.roomId, EventType.CallEncryptionKeysPrefix, content);\n      } catch (error) {\n        _this2.logger.error(\"Failed to send call encryption keys\", error);\n        var matrixError = error;\n        if (matrixError.event) {\n          // cancel the pending event: we'll just generate a new one with our latest\n          // keys when we resend\n          _this2.client.cancelPendingEvent(matrixError.event);\n        }\n        throw error;\n      }\n    })();\n  }\n  onEncryptionEvent(event) {\n    var userId = event.getSender();\n    var content = event.getContent();\n    var deviceId = content[\"device_id\"];\n    var callId = content[\"call_id\"];\n    if (!userId) {\n      this.logger.warn(\"Received m.call.encryption_keys with no userId: callId=\".concat(callId));\n      return;\n    }\n\n    // We currently only handle callId = \"\" (which is the default for room scoped calls)\n    if (callId !== \"\") {\n      this.logger.warn(\"Received m.call.encryption_keys with unsupported callId: userId=\".concat(userId, \", deviceId=\").concat(deviceId, \", callId=\").concat(callId));\n      return;\n    }\n    if (!Array.isArray(content.keys)) {\n      this.logger.warn(\"Received m.call.encryption_keys where keys wasn't an array: callId=\".concat(callId));\n      return;\n    }\n    if (userId === this.client.getUserId() && deviceId === this.client.getDeviceId()) {\n      // We store our own sender key in the same set along with keys from others, so it's\n      // important we don't allow our own keys to be set by one of these events (apart from\n      // the fact that we don't need it anyway because we already know our own keys).\n      this.logger.info(\"Ignoring our own keys event\");\n      return;\n    }\n    this.statistics.counters.roomEventEncryptionKeysReceived += 1;\n    var age = Date.now() - (typeof content.sent_ts === \"number\" ? content.sent_ts : event.getTs());\n    this.statistics.totals.roomEventEncryptionKeysReceivedTotalAge += age;\n    for (var key of content.keys) {\n      if (!key) {\n        this.logger.info(\"Ignoring false-y key in keys event\");\n        continue;\n      }\n      var encryptionKey = key.key;\n      var encryptionKeyIndex = key.index;\n      if (!encryptionKey || encryptionKeyIndex === undefined || encryptionKeyIndex === null || callId === undefined || callId === null || typeof deviceId !== \"string\" || typeof callId !== \"string\" || typeof encryptionKey !== \"string\" || typeof encryptionKeyIndex !== \"number\") {\n        this.logger.warn(\"Malformed call encryption_key: userId=\".concat(userId, \", deviceId=\").concat(deviceId, \", encryptionKeyIndex=\").concat(encryptionKeyIndex, \" callId=\").concat(callId));\n      } else {\n        this.logger.debug(\"onCallEncryption userId=\".concat(userId, \":\").concat(deviceId, \" encryptionKeyIndex=\").concat(encryptionKeyIndex, \" age=\").concat(age, \"ms\"));\n        this.emit(KeyTransportEvents.ReceivedKeys,\n        // Using `${userId}:${deviceId}` makes no sense (but works). It does not matter since the RoomKeyTransport is deprecated\n        {\n          userId,\n          deviceId,\n          memberId: \"\".concat(userId, \":\").concat(deviceId)\n        }, encryptionKey, encryptionKeyIndex, event.getTs());\n      }\n    }\n  }\n}\n//# sourceMappingURL=RoomKeyTransport.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2023 - 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger as rootLogger } from \"../logger.js\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.js\";\nimport { EventTimeline } from \"../models/event-timeline.js\";\nimport { EventType, RelationType } from \"../@types/event.js\";\nimport { KnownMembership } from \"../@types/membership.js\";\nimport { CallMembership } from \"./CallMembership.js\";\nimport { RoomStateEvent } from \"../models/room-state.js\";\nimport { MembershipManager, StickyEventMembershipManager } from \"./MembershipManager.js\";\nimport { EncryptionManager } from \"./EncryptionManager.js\";\nimport { logDurationSync } from \"../utils.js\";\nimport { MembershipManagerEvent } from \"./IMembershipManager.js\";\nimport { RTCEncryptionManager } from \"./RTCEncryptionManager.js\";\nimport { ToDeviceKeyTransport } from \"./ToDeviceKeyTransport.js\";\nimport { TypedReEmitter } from \"../ReEmitter.js\";\nimport { RoomStickyEventsEvent } from \"../models/room-sticky-events.js\";\nimport { RoomKeyTransport } from \"./RoomKeyTransport.js\";\n\n/**\n * Events emitted by MatrixRTCSession\n */\nexport var MatrixRTCSessionEvent = /*#__PURE__*/function (MatrixRTCSessionEvent) {\n  // A member joined, left, or updated a property of their membership.\n  MatrixRTCSessionEvent[\"MembershipsChanged\"] = \"memberships_changed\";\n  // We joined or left the session: our own local idea of whether we are joined,\n  // separate from MembershipsChanged, ie. independent of whether our member event\n  // has successfully gone through.\n  MatrixRTCSessionEvent[\"JoinStateChanged\"] = \"join_state_changed\";\n  // The key used to encrypt media has changed\n  MatrixRTCSessionEvent[\"EncryptionKeyChanged\"] = \"encryption_key_changed\";\n  /** The membership manager had to shut down caused by an unrecoverable error */\n  MatrixRTCSessionEvent[\"MembershipManagerError\"] = \"membership_manager_error\";\n  /** The RTCSession did send a call notification caused by joining the call as the first member */\n  MatrixRTCSessionEvent[\"DidSendCallNotification\"] = \"did_send_call_notification\";\n  return MatrixRTCSessionEvent;\n}({});\n\n/**\n * The session description is used to identify a session. Used in the state event.\n */\n\nexport function slotIdToDescription(slotId) {\n  var [application, id] = slotId.split(\"#\");\n  return {\n    application,\n    id\n  };\n}\nexport function slotDescriptionToId(slotDescription) {\n  return \"\".concat(slotDescription.application, \"#\").concat(slotDescription.id);\n}\n\n// The names follow these principles:\n// - we use the technical term delay if the option is related to delayed events.\n// - we use delayedLeaveEvent if the option is related to the delayed leave event.\n// - we use membershipEvent if the option is related to the rtc member state event.\n// - we use the technical term expiry if the option is related to the expiry field of the membership state event.\n// - we use a `Ms` postfix if the option is a duration to avoid using words like:\n//   `time`, `duration`, `delay`, `timeout`... that might be mistaken/confused with technical terms.\n\nvar DEFAULT_SESSION_MEMBERSHIPS_FOR_SLOT_OPTS = {\n  listenForStickyEvents: true,\n  listenForMemberStateEvents: true\n};\n\n/**\n * A MatrixRTCSession manages the membership & properties of a MatrixRTC session.\n * This class doesn't deal with media at all, just membership & properties of a session.\n */\nexport class MatrixRTCSession extends TypedEventEmitter {\n  get membershipStatus() {\n    var _this$membershipManag;\n    return (_this$membershipManag = this.membershipManager) === null || _this$membershipManag === void 0 ? void 0 : _this$membershipManag.status;\n  }\n  get probablyLeft() {\n    var _this$membershipManag2;\n    return (_this$membershipManag2 = this.membershipManager) === null || _this$membershipManag2 === void 0 ? void 0 : _this$membershipManag2.probablyLeft;\n  }\n  get delayId() {\n    var _this$membershipManag3;\n    return (_this$membershipManag3 = this.membershipManager) === null || _this$membershipManag3 === void 0 ? void 0 : _this$membershipManag3.delayId;\n  }\n\n  /**\n   * The callId (sessionId) of the call.\n   *\n   * It can be undefined since the callId is only known once the first membership joins.\n   * The callId is the property that, per definition, groups memberships into one call.\n   * @deprecated use `slotId` instead.\n   */\n  get callId() {\n    var _this$slotDescription;\n    return (_this$slotDescription = this.slotDescription) === null || _this$slotDescription === void 0 ? void 0 : _this$slotDescription.id;\n  }\n  /**\n   * The slotId of the call.\n   * `{application}#{appSpecificId}`\n   * It can be undefined since the slotId is only known once the first membership joins.\n   * The slotId is the property that, per definition, groups memberships into one call.\n   */\n  get slotId() {\n    return slotDescriptionToId(this.slotDescription);\n  }\n\n  /**\n   * Returns all the call memberships for a room that match the provided `sessionDescription`,\n   * oldest first.\n   *\n   * By default, this will return *both* sticky and member state events.\n   */\n  static sessionMembershipsForSlot(room, slotId) {\n    var _arguments = arguments;\n    return _asyncToGenerator(function* () {\n      var options = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : DEFAULT_SESSION_MEMBERSHIPS_FOR_SLOT_OPTS;\n      var logger = rootLogger.getChild(\"[MatrixRTCSession \".concat(room.roomId, \"]\"));\n      var callMemberEvents = collectMembersEvents(room, options, logger);\n      var callMemberships = yield computeBackendIdentityAndVerifyMemberEvents(room, callMemberEvents, slotId, logger);\n      callMemberships.sort((a, b) => a.createdTs() - b.createdTs());\n      if (callMemberships.length > 1) {\n        logger.debug(\"Call memberships in room \".concat(room.roomId, \", in order: \"), callMemberships.map(m => [m.createdTs(), m.userId]));\n      }\n      return callMemberships;\n    })();\n  }\n\n  /**\n   * Return the MatrixRTC session for the room.\n   * This returned session can be used to find out if there are active sessions\n   * for the requested room and `slotDescription`.\n   */\n  static sessionForSlot(client, room, slotDescription, opts) {\n    return new MatrixRTCSession(client, room, slotDescription, opts);\n  }\n\n  /**\n   * WARN: this can in theory only be a subset of the room with the properties required by\n   * this class.\n   * Outside of tests this most likely will be a full room, however.\n   * @deprecated Relying on a full Room object being available here is an anti-pattern. You should be tracking\n   * the room object in your own code and passing it in when needed.\n   */\n  get room() {\n    return this.roomSubset;\n  }\n\n  /**\n   * This constructs a room session. When using MatrixRTC inside the js-sdk this is expected\n   * to be used with the MatrixRTCSessionManager exclusively.\n   *\n   * In cases where you don't use the js-sdk but build on top of another Matrix stack this class can be used standalone\n   * to manage a joined MatrixRTC session.\n   *\n   * @param client A subset of the {@link MatrixClient} that lets the session interact with the Matrix room.\n   * @param roomSubset The room this session is attached to. A subset of a js-sdk Room that the session needs.\n   * @param slotDescription The slot description is a virtual address where participants are allowed to meet.\n   * This session will only manage memberships that match this slot description.Sessions are distinct if any of\n   * those properties are distinct: `roomSubset.roomId`, `slotDescription.application`, `slotDescription.id`.\n   */\n  constructor(client, roomSubset, slotDescription, calculateMembershipsOpts) {\n    var _this;\n    super();\n    _this = this;\n    this.client = client;\n    this.roomSubset = roomSubset;\n    this.slotDescription = slotDescription;\n    this.calculateMembershipsOpts = calculateMembershipsOpts;\n    _defineProperty(this, \"membershipManager\", void 0);\n    _defineProperty(this, \"encryptionManager\", void 0);\n    _defineProperty(this, \"joinConfig\", void 0);\n    _defineProperty(this, \"logger\", void 0);\n    _defineProperty(this, \"pendingNotificationToSend\", void 0);\n    /**\n     * This timeout is responsible to track any expiration. We need to know when we have to start\n     * to ignore other call members. There is no callback for this. This timeout will always be configured to\n     * emit when the next membership expires.\n     */\n    _defineProperty(this, \"expiryTimeout\", void 0);\n    _defineProperty(this, \"memberships\", []);\n    /**\n     * The statistics for this session.\n     */\n    _defineProperty(this, \"statistics\", {\n      counters: {\n        roomEventEncryptionKeysSent: 0,\n        roomEventEncryptionKeysReceived: 0\n      },\n      totals: {\n        roomEventEncryptionKeysReceivedTotalAge: 0\n      }\n    });\n    _defineProperty(this, \"reEmitter\", new TypedReEmitter(this));\n    /**\n     * Call this when the Matrix room members have changed.\n     */\n    _defineProperty(this, \"onRoomMemberUpdate\", () => {\n      this.ensureRecalculateSessionMembers();\n    });\n    /**\n     * Call this when a sticky event update has occured.\n     */\n    _defineProperty(this, \"onStickyEventUpdate\", (added, updated, removed) => {\n      if ([...added, ...removed, ...updated.flatMap(v => [v.current, v.previous])].some(e => e.getType() === EventType.RTCMembership)) {\n        this.ensureRecalculateSessionMembers();\n      }\n    });\n    /**\n     * Call this when something changed that may impacts the current MatrixRTC members in this session.\n     */\n    // We allow this name schema since this function should only be used for testing purposes.\n    // eslint-disable-next-line @typescript-eslint/naming-convention\n    _defineProperty(this, \"_onRTCSessionMemberUpdate\", /*#__PURE__*/_asyncToGenerator(function* () {\n      yield _this.recalculateSessionMembers();\n    }));\n    // helper variables to make sure we do not have parallel running recalculations.\n    _defineProperty(this, \"recalculateSessionMembersDirty\", false);\n    _defineProperty(this, \"recalculateSessionMembersPromise\", undefined);\n    /**\n     * Call this when anything that could impact rtc memberships has changed: Room Members or RTC members.\n     *\n     * Examines the latest call memberships and handles any encryption key sending or rotation that is needed.\n     *\n     * This function should be called when the room members or call memberships might have changed.\n     */\n    _defineProperty(this, \"recalculateSessionMembers\", /*#__PURE__*/_asyncToGenerator(function* () {\n      var _this$encryptionManag;\n      var oldMemberships = _this.memberships;\n      _this.memberships = yield MatrixRTCSession.sessionMembershipsForSlot(_this.room, slotDescriptionToId(_this.slotDescription), _this.calculateMembershipsOpts);\n      var changed = oldMemberships.length != _this.memberships.length || oldMemberships.some((m, i) => !CallMembership.equal(m, _this.memberships[i]));\n      if (changed) {\n        var _this$membershipManag4, _this$membershipManag5;\n        _this.logger.info(\"Memberships for call in room \".concat(_this.roomSubset.roomId, \" have changed: emitting (\").concat(_this.memberships.length, \" members)\"));\n        logDurationSync(_this.logger, \"emit MatrixRTCSessionEvent.MembershipsChanged\", () => {\n          _this.emit(MatrixRTCSessionEvent.MembershipsChanged, oldMemberships, _this.memberships);\n        });\n        void ((_this$membershipManag4 = _this.membershipManager) === null || _this$membershipManag4 === void 0 ? void 0 : _this$membershipManag4.onRTCSessionMemberUpdate(_this.memberships));\n        // The `ownMembership` will be set when calling `onRTCSessionMemberUpdate`.\n        var ownMembership = (_this$membershipManag5 = _this.membershipManager) === null || _this$membershipManag5 === void 0 ? void 0 : _this$membershipManag5.ownMembership;\n        if (_this.pendingNotificationToSend && ownMembership && oldMemberships.length === 0) {\n          var _this$joinConfig;\n          // If we're the first member in the call, we're responsible for\n          // sending the notification event\n          if (ownMembership.eventId && (_this$joinConfig = _this.joinConfig) !== null && _this$joinConfig !== void 0 && _this$joinConfig.notificationType) {\n            _this.sendCallNotify(ownMembership.eventId, _this.joinConfig.notificationType, ownMembership.callIntent);\n          } else {\n            _this.logger.warn(\"Own membership eventId is undefined, cannot send call notification\");\n          }\n        }\n        // If anyone else joins the session it is no longer our responsibility to send the notification.\n        // (If we were the joiner we already did sent the notification in the block above.)\n        if (_this.memberships.length > 0) _this.pendingNotificationToSend = undefined;\n      } else {\n        _this.logger.debug(\"No membership changes detected for room \".concat(_this.roomSubset.roomId));\n      }\n      // This also needs to be done if `changed` = false\n      // A member might have updated their fingerprint (created_ts)\n      void ((_this$encryptionManag = _this.encryptionManager) === null || _this$encryptionManag === void 0 ? void 0 : _this$encryptionManag.onMembershipsUpdate(oldMemberships));\n      _this.setExpiryTimer();\n    }));\n    this.logger = rootLogger.getChild(\"[MatrixRTCSession \".concat(roomSubset.roomId, \"]\"));\n    this.roomSubset.on(RoomStateEvent.Members, this.onRoomMemberUpdate);\n    this.roomSubset.on(RoomStickyEventsEvent.Update, this.onStickyEventUpdate);\n\n    // We can ignore this promise because `recalculateSessionMembers` will emit\n    // `MatrixRTCSessionEvent.MembershipsChanged` once it has completed.\n    this.ensureRecalculateSessionMembers();\n    this.setExpiryTimer();\n  }\n  /*\n   * Returns true if we intend to be participating in the MatrixRTC session.\n   * This is determined by checking if the relativeExpiry has been set.\n   */\n  isJoined() {\n    var _this$membershipManag6, _this$membershipManag7;\n    return (_this$membershipManag6 = (_this$membershipManag7 = this.membershipManager) === null || _this$membershipManag7 === void 0 ? void 0 : _this$membershipManag7.isJoined()) !== null && _this$membershipManag6 !== void 0 ? _this$membershipManag6 : false;\n  }\n\n  /**\n   * Performs cleanup & removes timers for client shutdown\n   */\n  stop() {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      var _this2$membershipMana;\n      yield (_this2$membershipMana = _this2.membershipManager) === null || _this2$membershipMana === void 0 ? void 0 : _this2$membershipMana.leave(1000);\n      if (_this2.expiryTimeout) {\n        clearTimeout(_this2.expiryTimeout);\n        _this2.expiryTimeout = undefined;\n      }\n      _this2.roomSubset.off(RoomStateEvent.Members, _this2.onRoomMemberUpdate);\n      _this2.roomSubset.off(RoomStickyEventsEvent.Update, _this2.onStickyEventUpdate);\n    })();\n  }\n  /**\n   * Announces this user and device as joined to the MatrixRTC session,\n   * and continues to update the membership event to keep it valid until\n   * leaveRoomSession() is called\n   * This will not subscribe to updates: remember to call subscribe() separately if\n   * desired.\n   * This method will return immediately and the session will be joined in the background.\n   * @param ownMembershipIdentity the identity of the user and device joining the session.\n   * This will be put into the content.member.\n   * @param fociPreferred the list of preferred foci to use in the joined RTC membership event.\n   * If multiSfuFocus is set, this is only needed if this client wants to publish to multiple transports simultaneously.\n   * @param multiSfuFocus the active focus to use in the joined RTC membership event. Setting this implies the\n   * membership manager will operate in a multi-SFU connection mode. If `undefined`, an `oldest_membership`\n   * transport selection will be used instead.\n   * @param joinConfig - Additional configuration for the joined session.\n   */\n  joinRTCSession(ownMembershipIdentity, fociPreferred, multiSfuFocus, joinConfig) {\n    var _this$joinConfig2;\n    if (this.isJoined()) {\n      this.logger.info(\"Already joined to session in room \".concat(this.roomSubset.roomId, \": ignoring join call\"));\n      return;\n    } else {\n      // Create MembershipManager and pass the RTCSession logger (with room id info)\n      this.membershipManager = joinConfig !== null && joinConfig !== void 0 && joinConfig.unstableSendStickyEvents ? new StickyEventMembershipManager(joinConfig, this.roomSubset, this.client, this.slotDescription, ownMembershipIdentity.memberId, this.logger) : new MembershipManager(joinConfig, this.roomSubset, this.client, this.slotDescription, this.logger);\n      this.reEmitter.reEmit(this.membershipManager, [MembershipManagerEvent.ProbablyLeft, MembershipManagerEvent.StatusChanged, MembershipManagerEvent.DelayIdChanged]);\n      // Create Encryption manager\n      var transport;\n      if (joinConfig !== null && joinConfig !== void 0 && joinConfig.useExperimentalToDeviceTransport) {\n        this.logger.info(\"Using experimental to-device transport for encryption keys\");\n        this.logger.info(\"Using to-device with room fallback transport for encryption keys\");\n        var [room, _client, statistics] = [this.roomSubset, this.client, this.statistics];\n        var _transport = new ToDeviceKeyTransport(ownMembershipIdentity, room.roomId, _client, statistics);\n        this.encryptionManager = new RTCEncryptionManager(ownMembershipIdentity, () => this.memberships, _transport, this.statistics, (keyBin, encryptionKeyIndex, membership, rtcBackendIdentity) => {\n          this.emit(MatrixRTCSessionEvent.EncryptionKeyChanged, keyBin, encryptionKeyIndex, membership, rtcBackendIdentity);\n        }, this.logger);\n      } else {\n        // TODO REMOVE ME!\n        transport = new RoomKeyTransport(this.roomSubset, this.client, this.statistics);\n        this.encryptionManager = new EncryptionManager(ownMembershipIdentity, () => this.memberships, transport, this.statistics, (keyBin, encryptionKeyIndex, membership, rtcBackendIdentity) => {\n          this.emit(MatrixRTCSessionEvent.EncryptionKeyChanged, keyBin, encryptionKeyIndex, membership, rtcBackendIdentity);\n        });\n      }\n    }\n    this.joinConfig = joinConfig;\n    this.pendingNotificationToSend = (_this$joinConfig2 = this.joinConfig) === null || _this$joinConfig2 === void 0 ? void 0 : _this$joinConfig2.notificationType;\n\n    // Join!\n    this.membershipManager.join(fociPreferred, multiSfuFocus, e => {\n      this.logger.error(\"MembershipManager encountered an unrecoverable error: \", e);\n      this.emit(MatrixRTCSessionEvent.MembershipManagerError, e);\n      this.emit(MatrixRTCSessionEvent.JoinStateChanged, this.isJoined());\n    });\n    this.encryptionManager.join(joinConfig);\n    this.emit(MatrixRTCSessionEvent.JoinStateChanged, true);\n  }\n\n  /**\n   *\n   * @param fociPreferred\n   * @param multiSfuFocus\n   * @param joinConfig\n   * @deprecated use the joinRTCSession method instead\n   */\n  joinRoomSession(fociPreferred, multiSfuFocus, joinConfig) {\n    var [userId, deviceId] = [this.client.getUserId(), this.client.getDeviceId()];\n    // TODO this wants to become a UUID\n    var memberId = \"\".concat(userId, \":\").concat(deviceId);\n    this.joinRTCSession({\n      userId,\n      deviceId,\n      memberId\n    }, fociPreferred, multiSfuFocus, joinConfig);\n  }\n\n  /**\n   * Announces this user and device as having left the MatrixRTC session\n   * and stops scheduled updates.\n   * This will not unsubscribe from updates: remember to call unsubscribe() separately if\n   * desired.\n   * The membership update required to leave the session will retry if it fails.\n   * Without network connection the promise will never resolve.\n   * A timeout can be provided so that there is a guarantee for the promise to resolve.\n   * @returns Whether the membership update was attempted and did not time out.\n   */\n  leaveRoomSession() {\n    var _arguments2 = arguments,\n      _this3 = this;\n    return _asyncToGenerator(function* () {\n      var timeout = _arguments2.length > 0 && _arguments2[0] !== undefined ? _arguments2[0] : undefined;\n      if (!_this3.isJoined()) {\n        _this3.logger.info(\"Not joined to session in room \".concat(_this3.roomSubset.roomId, \": ignoring leave call\"));\n        return false;\n      }\n      _this3.logger.info(\"Leaving call session in room \".concat(_this3.roomSubset.roomId));\n      _this3.encryptionManager.leave();\n      var leavePromise = _this3.membershipManager.leave(timeout);\n      _this3.emit(MatrixRTCSessionEvent.JoinStateChanged, false);\n      return yield leavePromise;\n    })();\n  }\n  /**\n   * This returns the focus in use by the oldest membership.\n   * Do not use since this might be just the focus for the oldest membership. others might use a different focus.\n   * @deprecated use `member.getTransport(session.getOldestMembership())` instead for the specific member you want to get the focus for.\n   */\n  getFocusInUse() {\n    var oldestMembership = this.getOldestMembership();\n    return oldestMembership === null || oldestMembership === void 0 ? void 0 : oldestMembership.getTransport(oldestMembership);\n  }\n\n  /**\n   * The used focusActive of the oldest membership (to find out the selection type multi-sfu or oldest membership active focus)\n   * @deprecated does not work with m.rtc.member. Do not rely on it.\n   */\n  getActiveFocus() {\n    var _this$getOldestMember;\n    return (_this$getOldestMember = this.getOldestMembership()) === null || _this$getOldestMember === void 0 ? void 0 : _this$getOldestMember.getFocusActive();\n  }\n  getOldestMembership() {\n    return this.memberships[0];\n  }\n\n  /**\n   * Get the call intent for the current call, based on what members are advertising. If one or more\n   * members disagree on the current call intent, or nobody specifies one then `undefined` is returned.\n   *\n   * If all members that specify a call intent agree, that value is returned.\n   * @returns A call intent, or `undefined` if no consensus or not given.\n   */\n  getConsensusCallIntent() {\n    var _this$memberships$fin;\n    var getFirstCallIntent = (_this$memberships$fin = this.memberships.find(m => !!m.callIntent)) === null || _this$memberships$fin === void 0 ? void 0 : _this$memberships$fin.callIntent;\n    if (!getFirstCallIntent) {\n      return undefined;\n    }\n    if (this.memberships.every(m => !m.callIntent || m.callIntent === getFirstCallIntent)) {\n      return getFirstCallIntent;\n    }\n    return undefined;\n  }\n  updateCallIntent(callIntent) {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      var _this4$membershipMana, _this4$membershipMana2;\n      var myMembership = (_this4$membershipMana = _this4.membershipManager) === null || _this4$membershipMana === void 0 ? void 0 : _this4$membershipMana.ownMembership;\n      if (!myMembership) {\n        throw Error(\"Not connected yet\");\n      }\n      yield (_this4$membershipMana2 = _this4.membershipManager) === null || _this4$membershipMana2 === void 0 ? void 0 : _this4$membershipMana2.updateCallIntent(callIntent);\n    })();\n  }\n\n  /**\n   * Re-emit an EncryptionKeyChanged event for each tracked encryption key. This can be used to export\n   * the keys.\n   */\n  reemitEncryptionKeys() {\n    var _this$encryptionManag2;\n    (_this$encryptionManag2 = this.encryptionManager) === null || _this$encryptionManag2 === void 0 || _this$encryptionManag2.getEncryptionKeys().forEach((keyRing, key) => {\n      keyRing.forEach(keyInfo => {\n        this.emit(MatrixRTCSessionEvent.EncryptionKeyChanged, keyInfo.key, keyInfo.keyIndex, keyInfo.membership, keyInfo.rtcBackendIdentity);\n      });\n    });\n  }\n\n  /**\n   * Sets a timer for the soonest membership expiry\n   */\n  setExpiryTimer() {\n    if (this.expiryTimeout) {\n      clearTimeout(this.expiryTimeout);\n      this.expiryTimeout = undefined;\n    }\n    var soonestExpiry;\n    for (var membership of this.memberships) {\n      var thisExpiry = membership.getMsUntilExpiry();\n      // If getMsUntilExpiry is undefined we have a MSC4143 (MatrixRTC) compliant event - it never expires\n      // but will be reliably resent on disconnect.\n      if (thisExpiry !== undefined && (soonestExpiry === undefined || thisExpiry < soonestExpiry)) {\n        soonestExpiry = thisExpiry;\n      }\n    }\n    if (soonestExpiry != undefined) {\n      this.expiryTimeout = setTimeout(this.ensureRecalculateSessionMembers.bind(this), soonestExpiry);\n    }\n  }\n\n  /**\n   * Sends notification events to indiciate the call has started.\n   * Note: This does not return a promise, instead scheduling the notification events to be sent.\n   * @param parentEventId Event id linking to your RTC call membership event.\n   * @param notificationType The type of notification to send\n   * @param callIntent The type of call this is (e.g. \"audio\").\n   */\n  sendCallNotify(parentEventId, notificationType, callIntent) {\n    var _this5 = this;\n    var sendNotificationEvent = /*#__PURE__*/function () {\n      var _ref3 = _asyncToGenerator(function* () {\n        var content = {\n          \"m.mentions\": {\n            user_ids: [],\n            room: true\n          },\n          \"notification_type\": notificationType,\n          \"m.relates_to\": {\n            event_id: parentEventId,\n            rel_type: RelationType.Reference\n          },\n          \"sender_ts\": Date.now(),\n          \"lifetime\": 30000 // 30 seconds\n        };\n        if (callIntent) {\n          content[\"m.call.intent\"] = callIntent;\n        }\n        var response = yield _this5.client.sendEvent(_this5.roomSubset.roomId, EventType.RTCNotification, content);\n        return {\n          response,\n          content\n        };\n      });\n      return function sendNotificationEvent() {\n        return _ref3.apply(this, arguments);\n      };\n    }();\n    void sendNotificationEvent().then(notification => {\n      // Join event_id and origin event content\n      var newResult = _objectSpread(_objectSpread({}, notification.response), notification.content);\n      this.emit(MatrixRTCSessionEvent.DidSendCallNotification, newResult);\n    }).catch(_ref4 => {\n      var [errorLegacy, errorNew] = _ref4;\n      return this.logger.error(\"Failed to send call notification\", errorLegacy, errorNew);\n    });\n  }\n  ensureRecalculateSessionMembers() {\n    if (this.recalculateSessionMembersPromise === undefined) {\n      this.recalculateSessionMembersPromise = this.recalculateSessionMembers().then(() => {\n        this.recalculateSessionMembersPromise = undefined;\n        if (this.recalculateSessionMembersDirty) {\n          this.ensureRecalculateSessionMembers();\n          this.recalculateSessionMembersDirty = false;\n        }\n      });\n    } else {\n      this.recalculateSessionMembersDirty = true;\n    }\n  }\n}\n\n/// Private helpers\nfunction computeBackendIdentityAndVerifyMemberEvents(_x, _x2, _x3, _x4) {\n  return _computeBackendIdentityAndVerifyMemberEvents.apply(this, arguments);\n}\nfunction _computeBackendIdentityAndVerifyMemberEvents() {\n  _computeBackendIdentityAndVerifyMemberEvents = _asyncToGenerator(function* (room, callMemberEvents, slotId, logger) {\n    var callMemberships = [];\n    for (var memberEvent of callMemberEvents) {\n      var content = memberEvent.getContent();\n\n      // Quick filter to avoid unneeded processing of invalid events or left events.\n      // A more thorough validation will be done later with CallMembership.membershipDataFromMatrixEvent.\n      if (!quickFilterNonRelevantContents(content, logger)) {\n        continue;\n      }\n      try {\n        var membershipData = CallMembership.membershipDataFromMatrixEvent(memberEvent);\n        var membership = new CallMembership(memberEvent, membershipData, yield CallMembership.computeRtcBackendIdentity(memberEvent, membershipData), logger);\n        if (isValidMembership(membership, room, slotId, logger)) {\n          callMemberships.push(membership);\n        }\n      } catch (e) {\n        logger.warn(\"Couldn't construct call membership: \", e);\n      }\n    }\n    return callMemberships;\n  });\n  return _computeBackendIdentityAndVerifyMemberEvents.apply(this, arguments);\n}\nfunction quickFilterNonRelevantContents(content, logger) {\n  // Ignore sticky keys for the count\n  var eventKeysCount = Object.keys(content).filter(k => k !== \"msc4354_sticky_key\").length;\n  // Don't even bother about empty events (saves us from costly type/\"key in\" checks in bigger rooms)\n  if (eventKeysCount === 0) return false;\n\n  // We first decide if it's a MSC4143 event (per device state key)\n  if (eventKeysCount > 1 && \"application\" in content) {\n    // We have a MSC4143 event membership event with a proper joined content\n    return true;\n  } else if (eventKeysCount === 1 && \"memberships\" in content) {\n    logger.warn(\"Legacy event found. Those are ignored, they do not contribute to the MatrixRTC session\");\n    return false;\n  } else {\n    // Invalid or left content\n    return false;\n  }\n}\nfunction isValidMembership(membership, room, slotId, logger) {\n  var _membership$userId;\n  if (membership.slotId !== slotId) {\n    logger.info(\"Ignoring membership of user \".concat(membership.userId, \" for a different slot:  user: \").concat(JSON.stringify(membership.slotDescription), \", slotId: \").concat(slotId, \")\"));\n    return false;\n  }\n  if (membership.isExpired()) {\n    logger.info(\"Ignoring expired device membership \".concat(membership.userId, \"/\").concat(membership.deviceId));\n    return false;\n  }\n  if (!room.hasMembershipState((_membership$userId = membership.userId) !== null && _membership$userId !== void 0 ? _membership$userId : \"\", KnownMembership.Join)) {\n    logger.info(\"Ignoring membership of user \".concat(membership.userId, \" who is not in the room.\"));\n    return false;\n  }\n  return true;\n}\n\n/**\n * Collects the raw member events from room state and sticky store.\n */\nfunction collectMembersEvents(room, options, logger) {\n  var {\n    listenForStickyEvents,\n    listenForMemberStateEvents\n  } = options;\n  var callMemberEvents = [];\n  if (listenForStickyEvents) {\n    // prefill with sticky events\n    callMemberEvents = [...room._unstable_getStickyEvents()].filter(e => e.getType() === EventType.RTCMembership);\n  }\n  if (listenForMemberStateEvents) {\n    var roomState = room.getLiveTimeline().getState(EventTimeline.FORWARDS);\n    if (!roomState) {\n      logger.warn(\"Couldn't get state for room \" + room.roomId + \"using empty membership array\");\n      return [];\n    }\n    var callMemberStateEvents = roomState.getStateEvents(EventType.GroupCallMemberPrefix);\n    callMemberEvents = callMemberEvents.concat(callMemberStateEvents.filter(callMemberStateEvent => !callMemberEvents.some(\n    // only care about state events which have keys which we have not yet seen in the sticky events.\n    // TODO: I believe this can discard a joined state event if there is a matching left sticky event.\n    stickyEvent => stickyEvent.getContent().msc4354_sticky_key === callMemberStateEvent.getStateKey())));\n  }\n  return callMemberEvents;\n}\n//# sourceMappingURL=MatrixRTCSession.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { ClientEvent } from \"../client.js\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.js\";\nimport { RoomStateEvent } from \"../models/room-state.js\";\nimport { MatrixRTCSession } from \"./MatrixRTCSession.js\";\nimport { EventType } from \"../@types/event.js\";\nexport var MatrixRTCSessionManagerEvents = /*#__PURE__*/function (MatrixRTCSessionManagerEvents) {\n  // A member has joined the MatrixRTC session, creating an active session in a room where there wasn't previously\n  MatrixRTCSessionManagerEvents[\"SessionStarted\"] = \"session_started\";\n  // All participants have left a given MatrixRTC session.\n  MatrixRTCSessionManagerEvents[\"SessionEnded\"] = \"session_ended\";\n  return MatrixRTCSessionManagerEvents;\n}({});\n/**\n * Holds all active MatrixRTC session objects and creates new ones as events arrive.\n * One `MatrixRTCSessionManager` is required for each MatrixRTC sessionDescription (application, session id) that the client wants to support.\n * If no application type is specified in the constructor, the default is \"m.call\".\n *\n * This interface is UNSTABLE and may change without warning.\n */\nexport class MatrixRTCSessionManager extends TypedEventEmitter {\n  constructor(rootLogger, client) {\n    var slotDescription = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {\n      application: \"m.call\",\n      id: \"ROOM\"\n    };\n    super();\n    this.client = client;\n    this.slotDescription = slotDescription;\n    // All the room-scoped sessions we know about. This will include any where the app\n    // has queried for the MatrixRTC sessions in a room, whether it's ever had any members\n    // or not). We keep a (lazily created) session object for every room to ensure that there\n    // is only ever one single room session object for any given room for the lifetime of the\n    // client: that way there can never be any code holding onto a stale object that is no\n    // longer the correct session object for the room.\n    _defineProperty(this, \"roomSessions\", new Map());\n    _defineProperty(this, \"logger\", void 0);\n    _defineProperty(this, \"onRoom\", room => {\n      void this.refreshRoom(room);\n    });\n    _defineProperty(this, \"onEvent\", event => {\n      if (!event.unstableStickyExpiresAt) return; // Not sticky, not interested.\n\n      if (event.getType() !== EventType.RTCMembership) return;\n      var room = this.client.getRoom(event.getRoomId());\n      if (!room) return;\n      void this.refreshRoom(room);\n    });\n    _defineProperty(this, \"onRoomState\", event => {\n      if (event.getType() !== EventType.GroupCallMemberPrefix) {\n        return;\n      }\n      var room = this.client.getRoom(event.getRoomId());\n      if (!room) {\n        this.logger.error(\"Got room state event for unknown room \".concat(event.getRoomId(), \"!\"));\n        return;\n      }\n      void this.refreshRoom(room);\n    });\n    this.logger = rootLogger.getChild(\"[MatrixRTCSessionManager]\");\n  }\n  start() {\n    // We shouldn't need to null-check here, but matrix-client.spec.ts mocks getRooms\n    // returning nothing, and breaks tests if you change it to return an empty array :'(\n    for (var room of (_this$client$getRooms = this.client.getRooms()) !== null && _this$client$getRooms !== void 0 ? _this$client$getRooms : []) {\n      var _this$client$getRooms;\n      var session = MatrixRTCSession.sessionForSlot(this.client, room, this.slotDescription);\n      if (session.memberships.length > 0) {\n        this.roomSessions.set(room.roomId, session);\n      }\n    }\n    this.client.on(ClientEvent.Room, this.onRoom);\n    this.client.on(ClientEvent.Event, this.onEvent);\n    this.client.on(RoomStateEvent.Events, this.onRoomState);\n  }\n  stop() {\n    for (var sess of this.roomSessions.values()) {\n      void sess.stop();\n    }\n    this.roomSessions.clear();\n    this.client.off(ClientEvent.Room, this.onRoom);\n    this.client.off(ClientEvent.Event, this.onEvent);\n    this.client.off(RoomStateEvent.Events, this.onRoomState);\n  }\n\n  /**\n   * Gets the main MatrixRTC session for a room, or undefined if there is\n   * no current session\n   */\n  getActiveRoomSession(room) {\n    return this.roomSessions.get(room.roomId);\n  }\n\n  /**\n   * Gets the main MatrixRTC session for a room, returning an empty session\n   * if no members are currently participating\n   */\n  getRoomSession(room) {\n    if (!this.roomSessions.has(room.roomId)) {\n      this.roomSessions.set(room.roomId, MatrixRTCSession.sessionForSlot(this.client, room, this.slotDescription));\n    }\n    return this.roomSessions.get(room.roomId);\n  }\n  refreshRoom(room) {\n    var _this = this;\n    return _asyncToGenerator(function* () {\n      var isNewSession = !_this.roomSessions.has(room.roomId);\n      var session = _this.getRoomSession(room);\n      var wasActiveAndKnown = session.memberships.length > 0 && !isNewSession;\n      // This needs to be here and the event listener cannot be setup in the MatrixRTCSession,\n      // because we need the update to happen between:\n      // wasActiveAndKnown = session.memberships.length > 0 and\n      // nowActive = session.memberships.length\n      // Alternatively we would need to setup some event emission when the RTC session ended.\n      // TODO we want to add the emission en session end. This makes the responsibility of the session manager more clear.\n\n      yield session._onRTCSessionMemberUpdate().catch(error => {\n        _this.logger.error(\"Error updating RTC session members for \".concat(room.roomId, \": \").concat(error));\n      });\n      var nowActive = session.memberships.length > 0;\n      if (wasActiveAndKnown && !nowActive) {\n        _this.logger.trace(\"Session ended for \".concat(room.roomId, \" (\").concat(session.memberships.length, \" members)\"));\n        _this.emit(MatrixRTCSessionManagerEvents.SessionEnded, room.roomId, _this.roomSessions.get(room.roomId));\n      } else if (!wasActiveAndKnown && nowActive) {\n        _this.logger.trace(\"Session started for \".concat(room.roomId, \" (\").concat(session.memberships.length, \" members)\"));\n        _this.emit(MatrixRTCSessionManagerEvents.SessionStarted, room.roomId, _this.roomSessions.get(room.roomId));\n      }\n    })();\n  }\n}\n//# sourceMappingURL=MatrixRTCSessionManager.js.map","/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { THREAD_RELATION_TYPE } from \"./models/thread.js\";\n/**\n * Returns a filter function for the /relations endpoint to filter out relations directly\n * to the thread root event that should not live in the thread timeline\n *\n * @param threadId - the thread ID (ie. the event ID of the root event of the thread)\n * @returns the filtered list of events\n */\nexport function getRelationsThreadFilter(threadId) {\n  return e => {\n    var _e$content, _e$content2;\n    return ((_e$content = e.content) === null || _e$content === void 0 || (_e$content = _e$content[\"m.relates_to\"]) === null || _e$content === void 0 ? void 0 : _e$content.event_id) !== threadId || ((_e$content2 = e.content) === null || _e$content2 === void 0 || (_e$content2 = _e$content2[\"m.relates_to\"]) === null || _e$content2 === void 0 ? void 0 : _e$content2.rel_type) === THREAD_RELATION_TYPE.name;\n  };\n}\n//# sourceMappingURL=thread-utils.js.map","export class InvalidTokenError extends Error {\n}\nInvalidTokenError.prototype.name = \"InvalidTokenError\";\nfunction b64DecodeUnicode(str) {\n    return decodeURIComponent(atob(str).replace(/(.)/g, (m, p) => {\n        let code = p.charCodeAt(0).toString(16).toUpperCase();\n        if (code.length < 2) {\n            code = \"0\" + code;\n        }\n        return \"%\" + code;\n    }));\n}\nfunction base64UrlDecode(str) {\n    let output = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n    switch (output.length % 4) {\n        case 0:\n            break;\n        case 2:\n            output += \"==\";\n            break;\n        case 3:\n            output += \"=\";\n            break;\n        default:\n            throw new Error(\"base64 string is not of the correct length\");\n    }\n    try {\n        return b64DecodeUnicode(output);\n    }\n    catch (err) {\n        return atob(output);\n    }\n}\nexport function jwtDecode(token, options) {\n    if (typeof token !== \"string\") {\n        throw new InvalidTokenError(\"Invalid token specified: must be a string\");\n    }\n    options || (options = {});\n    const pos = options.header === true ? 0 : 1;\n    const part = token.split(\".\")[pos];\n    if (typeof part !== \"string\") {\n        throw new InvalidTokenError(`Invalid token specified: missing part #${pos + 1}`);\n    }\n    let decoded;\n    try {\n        decoded = base64UrlDecode(part);\n    }\n    catch (e) {\n        throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${pos + 1} (${e.message})`);\n    }\n    try {\n        return JSON.parse(decoded);\n    }\n    catch (e) {\n        throw new InvalidTokenError(`Invalid token specified: invalid json for part #${pos + 1} (${e.message})`);\n    }\n}\n","// src/utils/Logger.ts\nvar nopLogger = {\n  debug: () => void 0,\n  info: () => void 0,\n  warn: () => void 0,\n  error: () => void 0\n};\nvar level;\nvar logger;\nvar Log = /* @__PURE__ */ ((Log2) => {\n  Log2[Log2[\"NONE\"] = 0] = \"NONE\";\n  Log2[Log2[\"ERROR\"] = 1] = \"ERROR\";\n  Log2[Log2[\"WARN\"] = 2] = \"WARN\";\n  Log2[Log2[\"INFO\"] = 3] = \"INFO\";\n  Log2[Log2[\"DEBUG\"] = 4] = \"DEBUG\";\n  return Log2;\n})(Log || {});\n((Log2) => {\n  function reset() {\n    level = 3 /* INFO */;\n    logger = nopLogger;\n  }\n  Log2.reset = reset;\n  function setLevel(value) {\n    if (!(0 /* NONE */ <= value && value <= 4 /* DEBUG */)) {\n      throw new Error(\"Invalid log level\");\n    }\n    level = value;\n  }\n  Log2.setLevel = setLevel;\n  function setLogger(value) {\n    logger = value;\n  }\n  Log2.setLogger = setLogger;\n})(Log || (Log = {}));\nvar Logger = class _Logger {\n  constructor(_name) {\n    this._name = _name;\n  }\n  /* eslint-disable @typescript-eslint/no-unsafe-enum-comparison */\n  debug(...args) {\n    if (level >= 4 /* DEBUG */) {\n      logger.debug(_Logger._format(this._name, this._method), ...args);\n    }\n  }\n  info(...args) {\n    if (level >= 3 /* INFO */) {\n      logger.info(_Logger._format(this._name, this._method), ...args);\n    }\n  }\n  warn(...args) {\n    if (level >= 2 /* WARN */) {\n      logger.warn(_Logger._format(this._name, this._method), ...args);\n    }\n  }\n  error(...args) {\n    if (level >= 1 /* ERROR */) {\n      logger.error(_Logger._format(this._name, this._method), ...args);\n    }\n  }\n  /* eslint-enable @typescript-eslint/no-unsafe-enum-comparison */\n  throw(err) {\n    this.error(err);\n    throw err;\n  }\n  create(method) {\n    const methodLogger = Object.create(this);\n    methodLogger._method = method;\n    methodLogger.debug(\"begin\");\n    return methodLogger;\n  }\n  static createStatic(name, staticMethod) {\n    const staticLogger = new _Logger(`${name}.${staticMethod}`);\n    staticLogger.debug(\"begin\");\n    return staticLogger;\n  }\n  static _format(name, method) {\n    const prefix = `[${name}]`;\n    return method ? `${prefix} ${method}:` : prefix;\n  }\n  /* eslint-disable @typescript-eslint/no-unsafe-enum-comparison */\n  // helpers for static class methods\n  static debug(name, ...args) {\n    if (level >= 4 /* DEBUG */) {\n      logger.debug(_Logger._format(name), ...args);\n    }\n  }\n  static info(name, ...args) {\n    if (level >= 3 /* INFO */) {\n      logger.info(_Logger._format(name), ...args);\n    }\n  }\n  static warn(name, ...args) {\n    if (level >= 2 /* WARN */) {\n      logger.warn(_Logger._format(name), ...args);\n    }\n  }\n  static error(name, ...args) {\n    if (level >= 1 /* ERROR */) {\n      logger.error(_Logger._format(name), ...args);\n    }\n  }\n  /* eslint-enable @typescript-eslint/no-unsafe-enum-comparison */\n};\nLog.reset();\n\n// src/utils/JwtUtils.ts\nimport { jwtDecode } from \"jwt-decode\";\nvar JwtUtils = class {\n  // IMPORTANT: doesn't validate the token\n  static decode(token) {\n    try {\n      return jwtDecode(token);\n    } catch (err) {\n      Logger.error(\"JwtUtils.decode\", err);\n      throw err;\n    }\n  }\n  static async generateSignedJwt(header, payload, privateKey) {\n    const encodedHeader = CryptoUtils.encodeBase64Url(new TextEncoder().encode(JSON.stringify(header)));\n    const encodedPayload = CryptoUtils.encodeBase64Url(new TextEncoder().encode(JSON.stringify(payload)));\n    const encodedToken = `${encodedHeader}.${encodedPayload}`;\n    const signature = await window.crypto.subtle.sign(\n      {\n        name: \"ECDSA\",\n        hash: { name: \"SHA-256\" }\n      },\n      privateKey,\n      new TextEncoder().encode(encodedToken)\n    );\n    const encodedSignature = CryptoUtils.encodeBase64Url(new Uint8Array(signature));\n    return `${encodedToken}.${encodedSignature}`;\n  }\n};\n\n// src/utils/CryptoUtils.ts\nvar UUID_V4_TEMPLATE = \"10000000-1000-4000-8000-100000000000\";\nvar toBase64 = (val) => btoa([...new Uint8Array(val)].map((chr) => String.fromCharCode(chr)).join(\"\"));\nvar _CryptoUtils = class _CryptoUtils {\n  static _randomWord() {\n    const arr = new Uint32Array(1);\n    crypto.getRandomValues(arr);\n    return arr[0];\n  }\n  /**\n   * Generates RFC4122 version 4 guid\n   */\n  static generateUUIDv4() {\n    const uuid = UUID_V4_TEMPLATE.replace(\n      /[018]/g,\n      (c) => (+c ^ _CryptoUtils._randomWord() & 15 >> +c / 4).toString(16)\n    );\n    return uuid.replace(/-/g, \"\");\n  }\n  /**\n   * PKCE: Generate a code verifier\n   */\n  static generateCodeVerifier() {\n    return _CryptoUtils.generateUUIDv4() + _CryptoUtils.generateUUIDv4() + _CryptoUtils.generateUUIDv4();\n  }\n  /**\n   * PKCE: Generate a code challenge\n   */\n  static async generateCodeChallenge(code_verifier) {\n    if (!crypto.subtle) {\n      throw new Error(\"Crypto.subtle is available only in secure contexts (HTTPS).\");\n    }\n    try {\n      const encoder = new TextEncoder();\n      const data = encoder.encode(code_verifier);\n      const hashed = await crypto.subtle.digest(\"SHA-256\", data);\n      return toBase64(hashed).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n    } catch (err) {\n      Logger.error(\"CryptoUtils.generateCodeChallenge\", err);\n      throw err;\n    }\n  }\n  /**\n   * Generates a base64-encoded string for a basic auth header\n   */\n  static generateBasicAuth(client_id, client_secret) {\n    const encoder = new TextEncoder();\n    const data = encoder.encode([client_id, client_secret].join(\":\"));\n    return toBase64(data);\n  }\n  /**\n   * Generates a hash of a string using a given algorithm\n   * @param alg\n   * @param message\n   */\n  static async hash(alg, message) {\n    const msgUint8 = new TextEncoder().encode(message);\n    const hashBuffer = await crypto.subtle.digest(alg, msgUint8);\n    return new Uint8Array(hashBuffer);\n  }\n  /**\n   * Generates a rfc7638 compliant jwk thumbprint\n   * @param jwk\n   */\n  static async customCalculateJwkThumbprint(jwk) {\n    let jsonObject;\n    switch (jwk.kty) {\n      case \"RSA\":\n        jsonObject = {\n          \"e\": jwk.e,\n          \"kty\": jwk.kty,\n          \"n\": jwk.n\n        };\n        break;\n      case \"EC\":\n        jsonObject = {\n          \"crv\": jwk.crv,\n          \"kty\": jwk.kty,\n          \"x\": jwk.x,\n          \"y\": jwk.y\n        };\n        break;\n      case \"OKP\":\n        jsonObject = {\n          \"crv\": jwk.crv,\n          \"kty\": jwk.kty,\n          \"x\": jwk.x\n        };\n        break;\n      case \"oct\":\n        jsonObject = {\n          \"crv\": jwk.k,\n          \"kty\": jwk.kty\n        };\n        break;\n      default:\n        throw new Error(\"Unknown jwk type\");\n    }\n    const utf8encodedAndHashed = await _CryptoUtils.hash(\"SHA-256\", JSON.stringify(jsonObject));\n    return _CryptoUtils.encodeBase64Url(utf8encodedAndHashed);\n  }\n  static async generateDPoPProof({\n    url,\n    accessToken,\n    httpMethod,\n    keyPair,\n    nonce\n  }) {\n    let hashedToken;\n    let encodedHash;\n    const payload = {\n      \"jti\": window.crypto.randomUUID(),\n      \"htm\": httpMethod != null ? httpMethod : \"GET\",\n      \"htu\": url,\n      \"iat\": Math.floor(Date.now() / 1e3)\n    };\n    if (accessToken) {\n      hashedToken = await _CryptoUtils.hash(\"SHA-256\", accessToken);\n      encodedHash = _CryptoUtils.encodeBase64Url(hashedToken);\n      payload.ath = encodedHash;\n    }\n    if (nonce) {\n      payload.nonce = nonce;\n    }\n    try {\n      const publicJwk = await crypto.subtle.exportKey(\"jwk\", keyPair.publicKey);\n      const header = {\n        \"alg\": \"ES256\",\n        \"typ\": \"dpop+jwt\",\n        \"jwk\": {\n          \"crv\": publicJwk.crv,\n          \"kty\": publicJwk.kty,\n          \"x\": publicJwk.x,\n          \"y\": publicJwk.y\n        }\n      };\n      return await JwtUtils.generateSignedJwt(header, payload, keyPair.privateKey);\n    } catch (err) {\n      if (err instanceof TypeError) {\n        throw new Error(`Error exporting dpop public key: ${err.message}`);\n      } else {\n        throw err;\n      }\n    }\n  }\n  static async generateDPoPJkt(keyPair) {\n    try {\n      const publicJwk = await crypto.subtle.exportKey(\"jwk\", keyPair.publicKey);\n      return await _CryptoUtils.customCalculateJwkThumbprint(publicJwk);\n    } catch (err) {\n      if (err instanceof TypeError) {\n        throw new Error(`Could not retrieve dpop keys from storage: ${err.message}`);\n      } else {\n        throw err;\n      }\n    }\n  }\n  static async generateDPoPKeys() {\n    return await window.crypto.subtle.generateKey(\n      {\n        name: \"ECDSA\",\n        namedCurve: \"P-256\"\n      },\n      false,\n      [\"sign\", \"verify\"]\n    );\n  }\n};\n/**\n * Generates a base64url encoded string\n */\n_CryptoUtils.encodeBase64Url = (input) => {\n  return toBase64(input).replace(/=/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n};\nvar CryptoUtils = _CryptoUtils;\n\n// src/utils/Event.ts\nvar Event = class {\n  constructor(_name) {\n    this._name = _name;\n    this._callbacks = [];\n    this._logger = new Logger(`Event('${this._name}')`);\n  }\n  addHandler(cb) {\n    this._callbacks.push(cb);\n    return () => this.removeHandler(cb);\n  }\n  removeHandler(cb) {\n    const idx = this._callbacks.lastIndexOf(cb);\n    if (idx >= 0) {\n      this._callbacks.splice(idx, 1);\n    }\n  }\n  async raise(...ev) {\n    this._logger.debug(\"raise:\", ...ev);\n    for (const cb of this._callbacks) {\n      await cb(...ev);\n    }\n  }\n};\n\n// src/utils/PopupUtils.ts\nvar PopupUtils = class {\n  /**\n   * Populates a map of window features with a placement centered in front of\n   * the current window. If no explicit width is given, a default value is\n   * binned into [800, 720, 600, 480, 360] based on the current window's width.\n   */\n  static center({ ...features }) {\n    var _a, _b, _c;\n    if (features.width == null)\n      features.width = (_a = [800, 720, 600, 480].find((width) => width <= window.outerWidth / 1.618)) != null ? _a : 360;\n    (_b = features.left) != null ? _b : features.left = Math.max(0, Math.round(window.screenX + (window.outerWidth - features.width) / 2));\n    if (features.height != null)\n      (_c = features.top) != null ? _c : features.top = Math.max(0, Math.round(window.screenY + (window.outerHeight - features.height) / 2));\n    return features;\n  }\n  static serialize(features) {\n    return Object.entries(features).filter(([, value]) => value != null).map(([key, value]) => `${key}=${typeof value !== \"boolean\" ? value : value ? \"yes\" : \"no\"}`).join(\",\");\n  }\n};\n\n// src/utils/Timer.ts\nvar Timer = class _Timer extends Event {\n  constructor() {\n    super(...arguments);\n    this._logger = new Logger(`Timer('${this._name}')`);\n    this._timerHandle = null;\n    this._expiration = 0;\n    this._callback = () => {\n      const diff = this._expiration - _Timer.getEpochTime();\n      this._logger.debug(\"timer completes in\", diff);\n      if (this._expiration <= _Timer.getEpochTime()) {\n        this.cancel();\n        void super.raise();\n      }\n    };\n  }\n  // get the time\n  static getEpochTime() {\n    return Math.floor(Date.now() / 1e3);\n  }\n  init(durationInSeconds) {\n    const logger2 = this._logger.create(\"init\");\n    durationInSeconds = Math.max(Math.floor(durationInSeconds), 1);\n    const expiration = _Timer.getEpochTime() + durationInSeconds;\n    if (this.expiration === expiration && this._timerHandle) {\n      logger2.debug(\"skipping since already initialized for expiration at\", this.expiration);\n      return;\n    }\n    this.cancel();\n    logger2.debug(\"using duration\", durationInSeconds);\n    this._expiration = expiration;\n    const timerDurationInSeconds = Math.min(durationInSeconds, 5);\n    this._timerHandle = setInterval(this._callback, timerDurationInSeconds * 1e3);\n  }\n  get expiration() {\n    return this._expiration;\n  }\n  cancel() {\n    this._logger.create(\"cancel\");\n    if (this._timerHandle) {\n      clearInterval(this._timerHandle);\n      this._timerHandle = null;\n    }\n  }\n};\n\n// src/utils/UrlUtils.ts\nvar UrlUtils = class {\n  static readParams(url, responseMode = \"query\") {\n    if (!url) throw new TypeError(\"Invalid URL\");\n    const parsedUrl = new URL(url, \"http://127.0.0.1\");\n    const params = parsedUrl[responseMode === \"fragment\" ? \"hash\" : \"search\"];\n    return new URLSearchParams(params.slice(1));\n  }\n};\nvar URL_STATE_DELIMITER = \";\";\n\n// src/errors/ErrorResponse.ts\nvar ErrorResponse = class extends Error {\n  constructor(args, form) {\n    var _a, _b, _c;\n    super(args.error_description || args.error || \"\");\n    this.form = form;\n    /** Marker to detect class: \"ErrorResponse\" */\n    this.name = \"ErrorResponse\";\n    if (!args.error) {\n      Logger.error(\"ErrorResponse\", \"No error passed\");\n      throw new Error(\"No error passed\");\n    }\n    this.error = args.error;\n    this.error_description = (_a = args.error_description) != null ? _a : null;\n    this.error_uri = (_b = args.error_uri) != null ? _b : null;\n    this.state = args.userState;\n    this.session_state = (_c = args.session_state) != null ? _c : null;\n    this.url_state = args.url_state;\n  }\n};\n\n// src/errors/ErrorTimeout.ts\nvar ErrorTimeout = class extends Error {\n  constructor(message) {\n    super(message);\n    /** Marker to detect class: \"ErrorTimeout\" */\n    this.name = \"ErrorTimeout\";\n  }\n};\n\n// src/AccessTokenEvents.ts\nvar AccessTokenEvents = class {\n  constructor(args) {\n    this._logger = new Logger(\"AccessTokenEvents\");\n    this._expiringTimer = new Timer(\"Access token expiring\");\n    this._expiredTimer = new Timer(\"Access token expired\");\n    this._expiringNotificationTimeInSeconds = args.expiringNotificationTimeInSeconds;\n  }\n  load(container) {\n    const logger2 = this._logger.create(\"load\");\n    if (container.access_token && container.expires_in !== void 0) {\n      const duration = container.expires_in;\n      logger2.debug(\"access token present, remaining duration:\", duration);\n      if (duration > 0) {\n        let expiring = duration - this._expiringNotificationTimeInSeconds;\n        if (expiring <= 0) {\n          expiring = 1;\n        }\n        logger2.debug(\"registering expiring timer, raising in\", expiring, \"seconds\");\n        this._expiringTimer.init(expiring);\n      } else {\n        logger2.debug(\"canceling existing expiring timer because we're past expiration.\");\n        this._expiringTimer.cancel();\n      }\n      const expired = duration + 1;\n      logger2.debug(\"registering expired timer, raising in\", expired, \"seconds\");\n      this._expiredTimer.init(expired);\n    } else {\n      this._expiringTimer.cancel();\n      this._expiredTimer.cancel();\n    }\n  }\n  unload() {\n    this._logger.debug(\"unload: canceling existing access token timers\");\n    this._expiringTimer.cancel();\n    this._expiredTimer.cancel();\n  }\n  /**\n   * Add callback: Raised prior to the access token expiring.\n   */\n  addAccessTokenExpiring(cb) {\n    return this._expiringTimer.addHandler(cb);\n  }\n  /**\n   * Remove callback: Raised prior to the access token expiring.\n   */\n  removeAccessTokenExpiring(cb) {\n    this._expiringTimer.removeHandler(cb);\n  }\n  /**\n   * Add callback: Raised after the access token has expired.\n   */\n  addAccessTokenExpired(cb) {\n    return this._expiredTimer.addHandler(cb);\n  }\n  /**\n   * Remove callback: Raised after the access token has expired.\n   */\n  removeAccessTokenExpired(cb) {\n    this._expiredTimer.removeHandler(cb);\n  }\n};\n\n// src/CheckSessionIFrame.ts\nvar CheckSessionIFrame = class {\n  constructor(_callback, _client_id, url, _intervalInSeconds, _stopOnError) {\n    this._callback = _callback;\n    this._client_id = _client_id;\n    this._intervalInSeconds = _intervalInSeconds;\n    this._stopOnError = _stopOnError;\n    this._logger = new Logger(\"CheckSessionIFrame\");\n    this._timer = null;\n    this._session_state = null;\n    this._message = (e) => {\n      if (e.origin === this._frame_origin && e.source === this._frame.contentWindow) {\n        if (e.data === \"error\") {\n          this._logger.error(\"error message from check session op iframe\");\n          if (this._stopOnError) {\n            this.stop();\n          }\n        } else if (e.data === \"changed\") {\n          this._logger.debug(\"changed message from check session op iframe\");\n          this.stop();\n          void this._callback();\n        } else {\n          this._logger.debug(e.data + \" message from check session op iframe\");\n        }\n      }\n    };\n    const parsedUrl = new URL(url);\n    this._frame_origin = parsedUrl.origin;\n    this._frame = window.document.createElement(\"iframe\");\n    this._frame.style.visibility = \"hidden\";\n    this._frame.style.position = \"fixed\";\n    this._frame.style.left = \"-1000px\";\n    this._frame.style.top = \"0\";\n    this._frame.width = \"0\";\n    this._frame.height = \"0\";\n    this._frame.src = parsedUrl.href;\n  }\n  load() {\n    return new Promise((resolve) => {\n      this._frame.onload = () => {\n        resolve();\n      };\n      window.document.body.appendChild(this._frame);\n      window.addEventListener(\"message\", this._message, false);\n    });\n  }\n  start(session_state) {\n    if (this._session_state === session_state) {\n      return;\n    }\n    this._logger.create(\"start\");\n    this.stop();\n    this._session_state = session_state;\n    const send = () => {\n      if (!this._frame.contentWindow || !this._session_state) {\n        return;\n      }\n      this._frame.contentWindow.postMessage(this._client_id + \" \" + this._session_state, this._frame_origin);\n    };\n    send();\n    this._timer = setInterval(send, this._intervalInSeconds * 1e3);\n  }\n  stop() {\n    this._logger.create(\"stop\");\n    this._session_state = null;\n    if (this._timer) {\n      clearInterval(this._timer);\n      this._timer = null;\n    }\n  }\n};\n\n// src/InMemoryWebStorage.ts\nvar InMemoryWebStorage = class {\n  constructor() {\n    this._logger = new Logger(\"InMemoryWebStorage\");\n    this._data = {};\n  }\n  clear() {\n    this._logger.create(\"clear\");\n    this._data = {};\n  }\n  getItem(key) {\n    this._logger.create(`getItem('${key}')`);\n    return this._data[key];\n  }\n  setItem(key, value) {\n    this._logger.create(`setItem('${key}')`);\n    this._data[key] = value;\n  }\n  removeItem(key) {\n    this._logger.create(`removeItem('${key}')`);\n    delete this._data[key];\n  }\n  get length() {\n    return Object.getOwnPropertyNames(this._data).length;\n  }\n  key(index) {\n    return Object.getOwnPropertyNames(this._data)[index];\n  }\n};\n\n// src/errors/ErrorDPoPNonce.ts\nvar ErrorDPoPNonce = class extends Error {\n  constructor(nonce, message) {\n    super(message);\n    /** Marker to detect class: \"ErrorDPoPNonce\" */\n    this.name = \"ErrorDPoPNonce\";\n    this.nonce = nonce;\n  }\n};\n\n// src/JsonService.ts\nvar JsonService = class {\n  constructor(additionalContentTypes = [], _jwtHandler = null, _extraHeaders = {}) {\n    this._jwtHandler = _jwtHandler;\n    this._extraHeaders = _extraHeaders;\n    this._logger = new Logger(\"JsonService\");\n    this._contentTypes = [];\n    this._contentTypes.push(...additionalContentTypes, \"application/json\");\n    if (_jwtHandler) {\n      this._contentTypes.push(\"application/jwt\");\n    }\n  }\n  async fetchWithTimeout(input, init = {}) {\n    const { timeoutInSeconds, ...initFetch } = init;\n    if (!timeoutInSeconds) {\n      return await fetch(input, initFetch);\n    }\n    const controller = new AbortController();\n    const timeoutId = setTimeout(() => controller.abort(), timeoutInSeconds * 1e3);\n    try {\n      const response = await fetch(input, {\n        ...init,\n        signal: controller.signal\n      });\n      return response;\n    } catch (err) {\n      if (err instanceof DOMException && err.name === \"AbortError\") {\n        throw new ErrorTimeout(\"Network timed out\");\n      }\n      throw err;\n    } finally {\n      clearTimeout(timeoutId);\n    }\n  }\n  async getJson(url, {\n    token,\n    credentials,\n    timeoutInSeconds\n  } = {}) {\n    const logger2 = this._logger.create(\"getJson\");\n    const headers = {\n      \"Accept\": this._contentTypes.join(\", \")\n    };\n    if (token) {\n      logger2.debug(\"token passed, setting Authorization header\");\n      headers[\"Authorization\"] = \"Bearer \" + token;\n    }\n    this.appendExtraHeaders(headers);\n    let response;\n    try {\n      logger2.debug(\"url:\", url);\n      response = await this.fetchWithTimeout(url, { method: \"GET\", headers, timeoutInSeconds, credentials });\n    } catch (err) {\n      logger2.error(\"Network Error\");\n      throw err;\n    }\n    logger2.debug(\"HTTP response received, status\", response.status);\n    const contentType = response.headers.get(\"Content-Type\");\n    if (contentType && !this._contentTypes.find((item) => contentType.startsWith(item))) {\n      logger2.throw(new Error(`Invalid response Content-Type: ${contentType != null ? contentType : \"undefined\"}, from URL: ${url}`));\n    }\n    if (response.ok && this._jwtHandler && (contentType == null ? void 0 : contentType.startsWith(\"application/jwt\"))) {\n      return await this._jwtHandler(await response.text());\n    }\n    let json;\n    try {\n      json = await response.json();\n    } catch (err) {\n      logger2.error(\"Error parsing JSON response\", err);\n      if (response.ok) throw err;\n      throw new Error(`${response.statusText} (${response.status})`);\n    }\n    if (!response.ok) {\n      logger2.error(\"Error from server:\", json);\n      if (json.error) {\n        throw new ErrorResponse(json);\n      }\n      throw new Error(`${response.statusText} (${response.status}): ${JSON.stringify(json)}`);\n    }\n    return json;\n  }\n  async postForm(url, {\n    body,\n    basicAuth,\n    timeoutInSeconds,\n    initCredentials,\n    extraHeaders\n  }) {\n    const logger2 = this._logger.create(\"postForm\");\n    const headers = {\n      \"Accept\": this._contentTypes.join(\", \"),\n      \"Content-Type\": \"application/x-www-form-urlencoded\",\n      ...extraHeaders\n    };\n    if (basicAuth !== void 0) {\n      headers[\"Authorization\"] = \"Basic \" + basicAuth;\n    }\n    this.appendExtraHeaders(headers);\n    let response;\n    try {\n      logger2.debug(\"url:\", url);\n      response = await this.fetchWithTimeout(url, { method: \"POST\", headers, body, timeoutInSeconds, credentials: initCredentials });\n    } catch (err) {\n      logger2.error(\"Network error\");\n      throw err;\n    }\n    logger2.debug(\"HTTP response received, status\", response.status);\n    const contentType = response.headers.get(\"Content-Type\");\n    if (contentType && !this._contentTypes.find((item) => contentType.startsWith(item))) {\n      throw new Error(`Invalid response Content-Type: ${contentType != null ? contentType : \"undefined\"}, from URL: ${url}`);\n    }\n    const responseText = await response.text();\n    let json = {};\n    if (responseText) {\n      try {\n        json = JSON.parse(responseText);\n      } catch (err) {\n        logger2.error(\"Error parsing JSON response\", err);\n        if (response.ok) throw err;\n        throw new Error(`${response.statusText} (${response.status})`);\n      }\n    }\n    if (!response.ok) {\n      logger2.error(\"Error from server:\", json);\n      if (response.headers.has(\"dpop-nonce\")) {\n        const nonce = response.headers.get(\"dpop-nonce\");\n        throw new ErrorDPoPNonce(nonce, `${JSON.stringify(json)}`);\n      }\n      if (json.error) {\n        throw new ErrorResponse(json, body);\n      }\n      throw new Error(`${response.statusText} (${response.status}): ${JSON.stringify(json)}`);\n    }\n    return json;\n  }\n  appendExtraHeaders(headers) {\n    const logger2 = this._logger.create(\"appendExtraHeaders\");\n    const customKeys = Object.keys(this._extraHeaders);\n    const protectedHeaders = [\n      \"authorization\",\n      \"accept\",\n      \"content-type\"\n    ];\n    if (customKeys.length === 0) {\n      return;\n    }\n    customKeys.forEach((headerName) => {\n      if (protectedHeaders.includes(headerName.toLocaleLowerCase())) {\n        logger2.warn(\"Protected header could not be overridden\", headerName, protectedHeaders);\n        return;\n      }\n      const content = typeof this._extraHeaders[headerName] === \"function\" ? this._extraHeaders[headerName]() : this._extraHeaders[headerName];\n      if (content && content !== \"\") {\n        headers[headerName] = content;\n      }\n    });\n  }\n};\n\n// src/MetadataService.ts\nvar MetadataService = class {\n  constructor(_settings) {\n    this._settings = _settings;\n    this._logger = new Logger(\"MetadataService\");\n    this._signingKeys = null;\n    this._metadata = null;\n    this._metadataUrl = this._settings.metadataUrl;\n    this._jsonService = new JsonService(\n      [\"application/jwk-set+json\"],\n      null,\n      this._settings.extraHeaders\n    );\n    if (this._settings.signingKeys) {\n      this._logger.debug(\"using signingKeys from settings\");\n      this._signingKeys = this._settings.signingKeys;\n    }\n    if (this._settings.metadata) {\n      this._logger.debug(\"using metadata from settings\");\n      this._metadata = this._settings.metadata;\n    }\n    if (this._settings.fetchRequestCredentials) {\n      this._logger.debug(\"using fetchRequestCredentials from settings\");\n      this._fetchRequestCredentials = this._settings.fetchRequestCredentials;\n    }\n  }\n  resetSigningKeys() {\n    this._signingKeys = null;\n  }\n  async getMetadata() {\n    const logger2 = this._logger.create(\"getMetadata\");\n    if (this._metadata) {\n      logger2.debug(\"using cached values\");\n      return this._metadata;\n    }\n    if (!this._metadataUrl) {\n      logger2.throw(new Error(\"No authority or metadataUrl configured on settings\"));\n      throw null;\n    }\n    logger2.debug(\"getting metadata from\", this._metadataUrl);\n    const metadata = await this._jsonService.getJson(this._metadataUrl, { credentials: this._fetchRequestCredentials, timeoutInSeconds: this._settings.requestTimeoutInSeconds });\n    logger2.debug(\"merging remote JSON with seed metadata\");\n    this._metadata = Object.assign({}, this._settings.metadataSeed, metadata);\n    return this._metadata;\n  }\n  getIssuer() {\n    return this._getMetadataProperty(\"issuer\");\n  }\n  getAuthorizationEndpoint() {\n    return this._getMetadataProperty(\"authorization_endpoint\");\n  }\n  getUserInfoEndpoint() {\n    return this._getMetadataProperty(\"userinfo_endpoint\");\n  }\n  getTokenEndpoint(optional = true) {\n    return this._getMetadataProperty(\"token_endpoint\", optional);\n  }\n  getCheckSessionIframe() {\n    return this._getMetadataProperty(\"check_session_iframe\", true);\n  }\n  getEndSessionEndpoint() {\n    return this._getMetadataProperty(\"end_session_endpoint\", true);\n  }\n  getRevocationEndpoint(optional = true) {\n    return this._getMetadataProperty(\"revocation_endpoint\", optional);\n  }\n  getKeysEndpoint(optional = true) {\n    return this._getMetadataProperty(\"jwks_uri\", optional);\n  }\n  async _getMetadataProperty(name, optional = false) {\n    const logger2 = this._logger.create(`_getMetadataProperty('${name}')`);\n    const metadata = await this.getMetadata();\n    logger2.debug(\"resolved\");\n    if (metadata[name] === void 0) {\n      if (optional === true) {\n        logger2.warn(\"Metadata does not contain optional property\");\n        return void 0;\n      }\n      logger2.throw(new Error(\"Metadata does not contain property \" + name));\n    }\n    return metadata[name];\n  }\n  async getSigningKeys() {\n    const logger2 = this._logger.create(\"getSigningKeys\");\n    if (this._signingKeys) {\n      logger2.debug(\"returning signingKeys from cache\");\n      return this._signingKeys;\n    }\n    const jwks_uri = await this.getKeysEndpoint(false);\n    logger2.debug(\"got jwks_uri\", jwks_uri);\n    const keySet = await this._jsonService.getJson(jwks_uri, { timeoutInSeconds: this._settings.requestTimeoutInSeconds });\n    logger2.debug(\"got key set\", keySet);\n    if (!Array.isArray(keySet.keys)) {\n      logger2.throw(new Error(\"Missing keys on keyset\"));\n      throw null;\n    }\n    this._signingKeys = keySet.keys;\n    return this._signingKeys;\n  }\n};\n\n// src/WebStorageStateStore.ts\nvar WebStorageStateStore = class {\n  constructor({\n    prefix = \"oidc.\",\n    store = localStorage\n  } = {}) {\n    this._logger = new Logger(\"WebStorageStateStore\");\n    this._store = store;\n    this._prefix = prefix;\n  }\n  async set(key, value) {\n    this._logger.create(`set('${key}')`);\n    key = this._prefix + key;\n    await this._store.setItem(key, value);\n  }\n  async get(key) {\n    this._logger.create(`get('${key}')`);\n    key = this._prefix + key;\n    const item = await this._store.getItem(key);\n    return item;\n  }\n  async remove(key) {\n    this._logger.create(`remove('${key}')`);\n    key = this._prefix + key;\n    const item = await this._store.getItem(key);\n    await this._store.removeItem(key);\n    return item;\n  }\n  async getAllKeys() {\n    this._logger.create(\"getAllKeys\");\n    const len = await this._store.length;\n    const keys = [];\n    for (let index = 0; index < len; index++) {\n      const key = await this._store.key(index);\n      if (key && key.indexOf(this._prefix) === 0) {\n        keys.push(key.substr(this._prefix.length));\n      }\n    }\n    return keys;\n  }\n};\n\n// src/OidcClientSettings.ts\nvar DefaultResponseType = \"code\";\nvar DefaultScope = \"openid\";\nvar DefaultClientAuthentication = \"client_secret_post\";\nvar DefaultStaleStateAgeInSeconds = 60 * 15;\nvar OidcClientSettingsStore = class {\n  constructor({\n    // metadata related\n    authority,\n    metadataUrl,\n    metadata,\n    signingKeys,\n    metadataSeed,\n    // client related\n    client_id,\n    client_secret,\n    response_type = DefaultResponseType,\n    scope = DefaultScope,\n    redirect_uri,\n    post_logout_redirect_uri,\n    client_authentication = DefaultClientAuthentication,\n    // optional protocol\n    prompt,\n    display,\n    max_age,\n    ui_locales,\n    acr_values,\n    resource,\n    response_mode,\n    // behavior flags\n    filterProtocolClaims = true,\n    loadUserInfo = false,\n    requestTimeoutInSeconds,\n    staleStateAgeInSeconds = DefaultStaleStateAgeInSeconds,\n    mergeClaimsStrategy = { array: \"replace\" },\n    disablePKCE = false,\n    // other behavior\n    stateStore,\n    revokeTokenAdditionalContentTypes,\n    fetchRequestCredentials,\n    refreshTokenAllowedScope,\n    // extra\n    extraQueryParams = {},\n    extraTokenParams = {},\n    extraHeaders = {},\n    dpop,\n    omitScopeWhenRequesting = false\n  }) {\n    var _a;\n    this.authority = authority;\n    if (metadataUrl) {\n      this.metadataUrl = metadataUrl;\n    } else {\n      this.metadataUrl = authority;\n      if (authority) {\n        if (!this.metadataUrl.endsWith(\"/\")) {\n          this.metadataUrl += \"/\";\n        }\n        this.metadataUrl += \".well-known/openid-configuration\";\n      }\n    }\n    this.metadata = metadata;\n    this.metadataSeed = metadataSeed;\n    this.signingKeys = signingKeys;\n    this.client_id = client_id;\n    this.client_secret = client_secret;\n    this.response_type = response_type;\n    this.scope = scope;\n    this.redirect_uri = redirect_uri;\n    this.post_logout_redirect_uri = post_logout_redirect_uri;\n    this.client_authentication = client_authentication;\n    this.prompt = prompt;\n    this.display = display;\n    this.max_age = max_age;\n    this.ui_locales = ui_locales;\n    this.acr_values = acr_values;\n    this.resource = resource;\n    this.response_mode = response_mode;\n    this.filterProtocolClaims = filterProtocolClaims != null ? filterProtocolClaims : true;\n    this.loadUserInfo = !!loadUserInfo;\n    this.staleStateAgeInSeconds = staleStateAgeInSeconds;\n    this.mergeClaimsStrategy = mergeClaimsStrategy;\n    this.omitScopeWhenRequesting = omitScopeWhenRequesting;\n    this.disablePKCE = !!disablePKCE;\n    this.revokeTokenAdditionalContentTypes = revokeTokenAdditionalContentTypes;\n    this.fetchRequestCredentials = fetchRequestCredentials ? fetchRequestCredentials : \"same-origin\";\n    this.requestTimeoutInSeconds = requestTimeoutInSeconds;\n    if (stateStore) {\n      this.stateStore = stateStore;\n    } else {\n      const store = typeof window !== \"undefined\" ? window.localStorage : new InMemoryWebStorage();\n      this.stateStore = new WebStorageStateStore({ store });\n    }\n    this.refreshTokenAllowedScope = refreshTokenAllowedScope;\n    this.extraQueryParams = extraQueryParams;\n    this.extraTokenParams = extraTokenParams;\n    this.extraHeaders = extraHeaders;\n    this.dpop = dpop;\n    if (this.dpop && !((_a = this.dpop) == null ? void 0 : _a.store)) {\n      throw new Error(\"A DPoPStore is required when dpop is enabled\");\n    }\n  }\n};\n\n// src/UserInfoService.ts\nvar UserInfoService = class {\n  constructor(_settings, _metadataService) {\n    this._settings = _settings;\n    this._metadataService = _metadataService;\n    this._logger = new Logger(\"UserInfoService\");\n    this._getClaimsFromJwt = async (responseText) => {\n      const logger2 = this._logger.create(\"_getClaimsFromJwt\");\n      try {\n        const payload = JwtUtils.decode(responseText);\n        logger2.debug(\"JWT decoding successful\");\n        return payload;\n      } catch (err) {\n        logger2.error(\"Error parsing JWT response\");\n        throw err;\n      }\n    };\n    this._jsonService = new JsonService(\n      void 0,\n      this._getClaimsFromJwt,\n      this._settings.extraHeaders\n    );\n  }\n  async getClaims(token) {\n    const logger2 = this._logger.create(\"getClaims\");\n    if (!token) {\n      this._logger.throw(new Error(\"No token passed\"));\n    }\n    const url = await this._metadataService.getUserInfoEndpoint();\n    logger2.debug(\"got userinfo url\", url);\n    const claims = await this._jsonService.getJson(url, {\n      token,\n      credentials: this._settings.fetchRequestCredentials,\n      timeoutInSeconds: this._settings.requestTimeoutInSeconds\n    });\n    logger2.debug(\"got claims\", claims);\n    return claims;\n  }\n};\n\n// src/TokenClient.ts\nvar TokenClient = class {\n  constructor(_settings, _metadataService) {\n    this._settings = _settings;\n    this._metadataService = _metadataService;\n    this._logger = new Logger(\"TokenClient\");\n    this._jsonService = new JsonService(\n      this._settings.revokeTokenAdditionalContentTypes,\n      null,\n      this._settings.extraHeaders\n    );\n  }\n  /**\n   * Exchange code.\n   *\n   * @see https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3\n   */\n  async exchangeCode({\n    grant_type = \"authorization_code\",\n    redirect_uri = this._settings.redirect_uri,\n    client_id = this._settings.client_id,\n    client_secret = this._settings.client_secret,\n    extraHeaders,\n    ...args\n  }) {\n    const logger2 = this._logger.create(\"exchangeCode\");\n    if (!client_id) {\n      logger2.throw(new Error(\"A client_id is required\"));\n    }\n    if (!redirect_uri) {\n      logger2.throw(new Error(\"A redirect_uri is required\"));\n    }\n    if (!args.code) {\n      logger2.throw(new Error(\"A code is required\"));\n    }\n    const params = new URLSearchParams({ grant_type, redirect_uri });\n    for (const [key, value] of Object.entries(args)) {\n      if (value != null) {\n        params.set(key, value);\n      }\n    }\n    let basicAuth;\n    switch (this._settings.client_authentication) {\n      case \"client_secret_basic\":\n        if (!client_secret) {\n          logger2.throw(new Error(\"A client_secret is required\"));\n          throw null;\n        }\n        basicAuth = CryptoUtils.generateBasicAuth(client_id, client_secret);\n        break;\n      case \"client_secret_post\":\n        params.append(\"client_id\", client_id);\n        if (client_secret) {\n          params.append(\"client_secret\", client_secret);\n        }\n        break;\n    }\n    const url = await this._metadataService.getTokenEndpoint(false);\n    logger2.debug(\"got token endpoint\");\n    const response = await this._jsonService.postForm(url, {\n      body: params,\n      basicAuth,\n      timeoutInSeconds: this._settings.requestTimeoutInSeconds,\n      initCredentials: this._settings.fetchRequestCredentials,\n      extraHeaders\n    });\n    logger2.debug(\"got response\");\n    return response;\n  }\n  /**\n   * Exchange credentials.\n   *\n   * @see https://www.rfc-editor.org/rfc/rfc6749#section-4.3.2\n   */\n  async exchangeCredentials({\n    grant_type = \"password\",\n    client_id = this._settings.client_id,\n    client_secret = this._settings.client_secret,\n    scope = this._settings.scope,\n    ...args\n  }) {\n    const logger2 = this._logger.create(\"exchangeCredentials\");\n    if (!client_id) {\n      logger2.throw(new Error(\"A client_id is required\"));\n    }\n    const params = new URLSearchParams({ grant_type });\n    if (!this._settings.omitScopeWhenRequesting) {\n      params.set(\"scope\", scope);\n    }\n    for (const [key, value] of Object.entries(args)) {\n      if (value != null) {\n        params.set(key, value);\n      }\n    }\n    let basicAuth;\n    switch (this._settings.client_authentication) {\n      case \"client_secret_basic\":\n        if (!client_secret) {\n          logger2.throw(new Error(\"A client_secret is required\"));\n          throw null;\n        }\n        basicAuth = CryptoUtils.generateBasicAuth(client_id, client_secret);\n        break;\n      case \"client_secret_post\":\n        params.append(\"client_id\", client_id);\n        if (client_secret) {\n          params.append(\"client_secret\", client_secret);\n        }\n        break;\n    }\n    const url = await this._metadataService.getTokenEndpoint(false);\n    logger2.debug(\"got token endpoint\");\n    const response = await this._jsonService.postForm(url, { body: params, basicAuth, timeoutInSeconds: this._settings.requestTimeoutInSeconds, initCredentials: this._settings.fetchRequestCredentials });\n    logger2.debug(\"got response\");\n    return response;\n  }\n  /**\n   * Exchange a refresh token.\n   *\n   * @see https://www.rfc-editor.org/rfc/rfc6749#section-6\n   */\n  async exchangeRefreshToken({\n    grant_type = \"refresh_token\",\n    client_id = this._settings.client_id,\n    client_secret = this._settings.client_secret,\n    timeoutInSeconds,\n    extraHeaders,\n    ...args\n  }) {\n    const logger2 = this._logger.create(\"exchangeRefreshToken\");\n    if (!client_id) {\n      logger2.throw(new Error(\"A client_id is required\"));\n    }\n    if (!args.refresh_token) {\n      logger2.throw(new Error(\"A refresh_token is required\"));\n    }\n    const params = new URLSearchParams({ grant_type });\n    for (const [key, value] of Object.entries(args)) {\n      if (Array.isArray(value)) {\n        value.forEach((param) => params.append(key, param));\n      } else if (value != null) {\n        params.set(key, value);\n      }\n    }\n    let basicAuth;\n    switch (this._settings.client_authentication) {\n      case \"client_secret_basic\":\n        if (!client_secret) {\n          logger2.throw(new Error(\"A client_secret is required\"));\n          throw null;\n        }\n        basicAuth = CryptoUtils.generateBasicAuth(client_id, client_secret);\n        break;\n      case \"client_secret_post\":\n        params.append(\"client_id\", client_id);\n        if (client_secret) {\n          params.append(\"client_secret\", client_secret);\n        }\n        break;\n    }\n    const url = await this._metadataService.getTokenEndpoint(false);\n    logger2.debug(\"got token endpoint\");\n    const response = await this._jsonService.postForm(url, { body: params, basicAuth, timeoutInSeconds, initCredentials: this._settings.fetchRequestCredentials, extraHeaders });\n    logger2.debug(\"got response\");\n    return response;\n  }\n  /**\n   * Revoke an access or refresh token.\n   *\n   * @see https://datatracker.ietf.org/doc/html/rfc7009#section-2.1\n   */\n  async revoke(args) {\n    var _a;\n    const logger2 = this._logger.create(\"revoke\");\n    if (!args.token) {\n      logger2.throw(new Error(\"A token is required\"));\n    }\n    const url = await this._metadataService.getRevocationEndpoint(false);\n    logger2.debug(`got revocation endpoint, revoking ${(_a = args.token_type_hint) != null ? _a : \"default token type\"}`);\n    const params = new URLSearchParams();\n    for (const [key, value] of Object.entries(args)) {\n      if (value != null) {\n        params.set(key, value);\n      }\n    }\n    params.set(\"client_id\", this._settings.client_id);\n    if (this._settings.client_secret) {\n      params.set(\"client_secret\", this._settings.client_secret);\n    }\n    await this._jsonService.postForm(url, { body: params, timeoutInSeconds: this._settings.requestTimeoutInSeconds });\n    logger2.debug(\"got response\");\n  }\n};\n\n// src/ResponseValidator.ts\nvar ResponseValidator = class {\n  constructor(_settings, _metadataService, _claimsService) {\n    this._settings = _settings;\n    this._metadataService = _metadataService;\n    this._claimsService = _claimsService;\n    this._logger = new Logger(\"ResponseValidator\");\n    this._userInfoService = new UserInfoService(this._settings, this._metadataService);\n    this._tokenClient = new TokenClient(this._settings, this._metadataService);\n  }\n  async validateSigninResponse(response, state, extraHeaders) {\n    const logger2 = this._logger.create(\"validateSigninResponse\");\n    this._processSigninState(response, state);\n    logger2.debug(\"state processed\");\n    await this._processCode(response, state, extraHeaders);\n    logger2.debug(\"code processed\");\n    if (response.isOpenId) {\n      this._validateIdTokenAttributes(response);\n    }\n    logger2.debug(\"tokens validated\");\n    await this._processClaims(response, state == null ? void 0 : state.skipUserInfo, response.isOpenId);\n    logger2.debug(\"claims processed\");\n  }\n  async validateCredentialsResponse(response, skipUserInfo) {\n    const logger2 = this._logger.create(\"validateCredentialsResponse\");\n    if (response.isOpenId && !!response.id_token) {\n      this._validateIdTokenAttributes(response);\n    }\n    logger2.debug(\"tokens validated\");\n    await this._processClaims(response, skipUserInfo, response.isOpenId);\n    logger2.debug(\"claims processed\");\n  }\n  async validateRefreshResponse(response, state) {\n    var _a, _b;\n    const logger2 = this._logger.create(\"validateRefreshResponse\");\n    response.userState = state.data;\n    (_a = response.session_state) != null ? _a : response.session_state = state.session_state;\n    (_b = response.scope) != null ? _b : response.scope = state.scope;\n    if (response.isOpenId && !!response.id_token) {\n      this._validateIdTokenAttributes(response, state.id_token);\n      logger2.debug(\"ID Token validated\");\n    }\n    if (!response.id_token) {\n      response.id_token = state.id_token;\n      response.profile = state.profile;\n    }\n    const hasIdToken = response.isOpenId && !!response.id_token;\n    await this._processClaims(response, false, hasIdToken);\n    logger2.debug(\"claims processed\");\n  }\n  validateSignoutResponse(response, state) {\n    const logger2 = this._logger.create(\"validateSignoutResponse\");\n    if (state.id !== response.state) {\n      logger2.throw(new Error(\"State does not match\"));\n    }\n    logger2.debug(\"state validated\");\n    response.userState = state.data;\n    if (response.error) {\n      logger2.warn(\"Response was error\", response.error);\n      throw new ErrorResponse(response);\n    }\n  }\n  _processSigninState(response, state) {\n    var _a;\n    const logger2 = this._logger.create(\"_processSigninState\");\n    if (state.id !== response.state) {\n      logger2.throw(new Error(\"State does not match\"));\n    }\n    if (!state.client_id) {\n      logger2.throw(new Error(\"No client_id on state\"));\n    }\n    if (!state.authority) {\n      logger2.throw(new Error(\"No authority on state\"));\n    }\n    if (this._settings.authority !== state.authority) {\n      logger2.throw(new Error(\"authority mismatch on settings vs. signin state\"));\n    }\n    if (this._settings.client_id && this._settings.client_id !== state.client_id) {\n      logger2.throw(new Error(\"client_id mismatch on settings vs. signin state\"));\n    }\n    logger2.debug(\"state validated\");\n    response.userState = state.data;\n    response.url_state = state.url_state;\n    (_a = response.scope) != null ? _a : response.scope = state.scope;\n    if (response.error) {\n      logger2.warn(\"Response was error\", response.error);\n      throw new ErrorResponse(response);\n    }\n    if (state.code_verifier && !response.code) {\n      logger2.throw(new Error(\"Expected code in response\"));\n    }\n  }\n  async _processClaims(response, skipUserInfo = false, validateSub = true) {\n    const logger2 = this._logger.create(\"_processClaims\");\n    response.profile = this._claimsService.filterProtocolClaims(response.profile);\n    if (skipUserInfo || !this._settings.loadUserInfo || !response.access_token) {\n      logger2.debug(\"not loading user info\");\n      return;\n    }\n    logger2.debug(\"loading user info\");\n    const claims = await this._userInfoService.getClaims(response.access_token);\n    logger2.debug(\"user info claims received from user info endpoint\");\n    if (validateSub && claims.sub !== response.profile.sub) {\n      logger2.throw(new Error(\"subject from UserInfo response does not match subject in ID Token\"));\n    }\n    response.profile = this._claimsService.mergeClaims(response.profile, this._claimsService.filterProtocolClaims(claims));\n    logger2.debug(\"user info claims received, updated profile:\", response.profile);\n  }\n  async _processCode(response, state, extraHeaders) {\n    const logger2 = this._logger.create(\"_processCode\");\n    if (response.code) {\n      logger2.debug(\"Validating code\");\n      const tokenResponse = await this._tokenClient.exchangeCode({\n        client_id: state.client_id,\n        client_secret: state.client_secret,\n        code: response.code,\n        redirect_uri: state.redirect_uri,\n        code_verifier: state.code_verifier,\n        extraHeaders,\n        ...state.extraTokenParams\n      });\n      Object.assign(response, tokenResponse);\n    } else {\n      logger2.debug(\"No code to process\");\n    }\n  }\n  _validateIdTokenAttributes(response, existingToken) {\n    var _a;\n    const logger2 = this._logger.create(\"_validateIdTokenAttributes\");\n    logger2.debug(\"decoding ID Token JWT\");\n    const incoming = JwtUtils.decode((_a = response.id_token) != null ? _a : \"\");\n    if (!incoming.sub) {\n      logger2.throw(new Error(\"ID Token is missing a subject claim\"));\n    }\n    if (existingToken) {\n      const existing = JwtUtils.decode(existingToken);\n      if (incoming.sub !== existing.sub) {\n        logger2.throw(new Error(\"sub in id_token does not match current sub\"));\n      }\n      if (incoming.auth_time && incoming.auth_time !== existing.auth_time) {\n        logger2.throw(new Error(\"auth_time in id_token does not match original auth_time\"));\n      }\n      if (incoming.azp && incoming.azp !== existing.azp) {\n        logger2.throw(new Error(\"azp in id_token does not match original azp\"));\n      }\n      if (!incoming.azp && existing.azp) {\n        logger2.throw(new Error(\"azp not in id_token, but present in original id_token\"));\n      }\n    }\n    response.profile = incoming;\n  }\n};\n\n// src/State.ts\nvar State = class _State {\n  constructor(args) {\n    this.id = args.id || CryptoUtils.generateUUIDv4();\n    this.data = args.data;\n    if (args.created && args.created > 0) {\n      this.created = args.created;\n    } else {\n      this.created = Timer.getEpochTime();\n    }\n    this.request_type = args.request_type;\n    this.url_state = args.url_state;\n  }\n  toStorageString() {\n    new Logger(\"State\").create(\"toStorageString\");\n    return JSON.stringify({\n      id: this.id,\n      data: this.data,\n      created: this.created,\n      request_type: this.request_type,\n      url_state: this.url_state\n    });\n  }\n  static fromStorageString(storageString) {\n    Logger.createStatic(\"State\", \"fromStorageString\");\n    return Promise.resolve(new _State(JSON.parse(storageString)));\n  }\n  static async clearStaleState(storage, age) {\n    const logger2 = Logger.createStatic(\"State\", \"clearStaleState\");\n    const cutoff = Timer.getEpochTime() - age;\n    const keys = await storage.getAllKeys();\n    logger2.debug(\"got keys\", keys);\n    for (let i = 0; i < keys.length; i++) {\n      const key = keys[i];\n      const item = await storage.get(key);\n      let remove = false;\n      if (item) {\n        try {\n          const state = await _State.fromStorageString(item);\n          logger2.debug(\"got item from key:\", key, state.created);\n          if (state.created <= cutoff) {\n            remove = true;\n          }\n        } catch (err) {\n          logger2.error(\"Error parsing state for key:\", key, err);\n          remove = true;\n        }\n      } else {\n        logger2.debug(\"no item in storage for key:\", key);\n        remove = true;\n      }\n      if (remove) {\n        logger2.debug(\"removed item for key:\", key);\n        void storage.remove(key);\n      }\n    }\n  }\n};\n\n// src/SigninState.ts\nvar SigninState = class _SigninState extends State {\n  constructor(args) {\n    super(args);\n    this.code_verifier = args.code_verifier;\n    this.code_challenge = args.code_challenge;\n    this.authority = args.authority;\n    this.client_id = args.client_id;\n    this.redirect_uri = args.redirect_uri;\n    this.scope = args.scope;\n    this.client_secret = args.client_secret;\n    this.extraTokenParams = args.extraTokenParams;\n    this.response_mode = args.response_mode;\n    this.skipUserInfo = args.skipUserInfo;\n  }\n  static async create(args) {\n    const code_verifier = args.code_verifier === true ? CryptoUtils.generateCodeVerifier() : args.code_verifier || void 0;\n    const code_challenge = code_verifier ? await CryptoUtils.generateCodeChallenge(code_verifier) : void 0;\n    return new _SigninState({\n      ...args,\n      code_verifier,\n      code_challenge\n    });\n  }\n  toStorageString() {\n    new Logger(\"SigninState\").create(\"toStorageString\");\n    return JSON.stringify({\n      id: this.id,\n      data: this.data,\n      created: this.created,\n      request_type: this.request_type,\n      url_state: this.url_state,\n      code_verifier: this.code_verifier,\n      authority: this.authority,\n      client_id: this.client_id,\n      redirect_uri: this.redirect_uri,\n      scope: this.scope,\n      client_secret: this.client_secret,\n      extraTokenParams: this.extraTokenParams,\n      response_mode: this.response_mode,\n      skipUserInfo: this.skipUserInfo\n    });\n  }\n  static fromStorageString(storageString) {\n    Logger.createStatic(\"SigninState\", \"fromStorageString\");\n    const data = JSON.parse(storageString);\n    return _SigninState.create(data);\n  }\n};\n\n// src/SigninRequest.ts\nvar _SigninRequest = class _SigninRequest {\n  constructor(args) {\n    this.url = args.url;\n    this.state = args.state;\n  }\n  static async create({\n    // mandatory\n    url,\n    authority,\n    client_id,\n    redirect_uri,\n    response_type,\n    scope,\n    // optional\n    state_data,\n    response_mode,\n    request_type,\n    client_secret,\n    nonce,\n    url_state,\n    resource,\n    skipUserInfo,\n    extraQueryParams,\n    extraTokenParams,\n    disablePKCE,\n    dpopJkt,\n    omitScopeWhenRequesting,\n    ...optionalParams\n  }) {\n    if (!url) {\n      this._logger.error(\"create: No url passed\");\n      throw new Error(\"url\");\n    }\n    if (!client_id) {\n      this._logger.error(\"create: No client_id passed\");\n      throw new Error(\"client_id\");\n    }\n    if (!redirect_uri) {\n      this._logger.error(\"create: No redirect_uri passed\");\n      throw new Error(\"redirect_uri\");\n    }\n    if (!response_type) {\n      this._logger.error(\"create: No response_type passed\");\n      throw new Error(\"response_type\");\n    }\n    if (!scope) {\n      this._logger.error(\"create: No scope passed\");\n      throw new Error(\"scope\");\n    }\n    if (!authority) {\n      this._logger.error(\"create: No authority passed\");\n      throw new Error(\"authority\");\n    }\n    const state = await SigninState.create({\n      data: state_data,\n      request_type,\n      url_state,\n      code_verifier: !disablePKCE,\n      client_id,\n      authority,\n      redirect_uri,\n      response_mode,\n      client_secret,\n      scope,\n      extraTokenParams,\n      skipUserInfo\n    });\n    const parsedUrl = new URL(url);\n    parsedUrl.searchParams.append(\"client_id\", client_id);\n    parsedUrl.searchParams.append(\"redirect_uri\", redirect_uri);\n    parsedUrl.searchParams.append(\"response_type\", response_type);\n    if (!omitScopeWhenRequesting) {\n      parsedUrl.searchParams.append(\"scope\", scope);\n    }\n    if (nonce) {\n      parsedUrl.searchParams.append(\"nonce\", nonce);\n    }\n    if (dpopJkt) {\n      parsedUrl.searchParams.append(\"dpop_jkt\", dpopJkt);\n    }\n    let stateParam = state.id;\n    if (url_state) {\n      stateParam = `${stateParam}${URL_STATE_DELIMITER}${url_state}`;\n    }\n    parsedUrl.searchParams.append(\"state\", stateParam);\n    if (state.code_challenge) {\n      parsedUrl.searchParams.append(\"code_challenge\", state.code_challenge);\n      parsedUrl.searchParams.append(\"code_challenge_method\", \"S256\");\n    }\n    if (resource) {\n      const resources = Array.isArray(resource) ? resource : [resource];\n      resources.forEach((r) => parsedUrl.searchParams.append(\"resource\", r));\n    }\n    for (const [key, value] of Object.entries({ response_mode, ...optionalParams, ...extraQueryParams })) {\n      if (value != null) {\n        parsedUrl.searchParams.append(key, value.toString());\n      }\n    }\n    return new _SigninRequest({\n      url: parsedUrl.href,\n      state\n    });\n  }\n};\n_SigninRequest._logger = new Logger(\"SigninRequest\");\nvar SigninRequest = _SigninRequest;\n\n// src/SigninResponse.ts\nvar OidcScope = \"openid\";\nvar SigninResponse = class {\n  constructor(params) {\n    /** @see {@link User.access_token} */\n    this.access_token = \"\";\n    /** @see {@link User.token_type} */\n    this.token_type = \"\";\n    /** @see {@link User.profile} */\n    this.profile = {};\n    this.state = params.get(\"state\");\n    this.session_state = params.get(\"session_state\");\n    if (this.state) {\n      const splitState = decodeURIComponent(this.state).split(URL_STATE_DELIMITER);\n      this.state = splitState[0];\n      if (splitState.length > 1) {\n        this.url_state = splitState.slice(1).join(URL_STATE_DELIMITER);\n      }\n    }\n    this.error = params.get(\"error\");\n    this.error_description = params.get(\"error_description\");\n    this.error_uri = params.get(\"error_uri\");\n    this.code = params.get(\"code\");\n  }\n  get expires_in() {\n    if (this.expires_at === void 0) {\n      return void 0;\n    }\n    return this.expires_at - Timer.getEpochTime();\n  }\n  set expires_in(value) {\n    if (typeof value === \"string\") value = Number(value);\n    if (value !== void 0 && value >= 0) {\n      this.expires_at = Math.floor(value) + Timer.getEpochTime();\n    }\n  }\n  get isOpenId() {\n    var _a;\n    return ((_a = this.scope) == null ? void 0 : _a.split(\" \").includes(OidcScope)) || !!this.id_token;\n  }\n};\n\n// src/SignoutRequest.ts\nvar SignoutRequest = class {\n  constructor({\n    url,\n    state_data,\n    id_token_hint,\n    post_logout_redirect_uri,\n    extraQueryParams,\n    request_type,\n    client_id\n  }) {\n    this._logger = new Logger(\"SignoutRequest\");\n    if (!url) {\n      this._logger.error(\"ctor: No url passed\");\n      throw new Error(\"url\");\n    }\n    const parsedUrl = new URL(url);\n    if (id_token_hint) {\n      parsedUrl.searchParams.append(\"id_token_hint\", id_token_hint);\n    }\n    if (client_id) {\n      parsedUrl.searchParams.append(\"client_id\", client_id);\n    }\n    if (post_logout_redirect_uri) {\n      parsedUrl.searchParams.append(\"post_logout_redirect_uri\", post_logout_redirect_uri);\n      if (state_data) {\n        this.state = new State({ data: state_data, request_type });\n        parsedUrl.searchParams.append(\"state\", this.state.id);\n      }\n    }\n    for (const [key, value] of Object.entries({ ...extraQueryParams })) {\n      if (value != null) {\n        parsedUrl.searchParams.append(key, value.toString());\n      }\n    }\n    this.url = parsedUrl.href;\n  }\n};\n\n// src/SignoutResponse.ts\nvar SignoutResponse = class {\n  constructor(params) {\n    this.state = params.get(\"state\");\n    this.error = params.get(\"error\");\n    this.error_description = params.get(\"error_description\");\n    this.error_uri = params.get(\"error_uri\");\n  }\n};\n\n// src/ClaimsService.ts\nvar DefaultProtocolClaims = [\n  \"nbf\",\n  \"jti\",\n  \"auth_time\",\n  \"nonce\",\n  \"acr\",\n  \"amr\",\n  \"azp\",\n  \"at_hash\"\n  // https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken\n];\nvar InternalRequiredProtocolClaims = [\"sub\", \"iss\", \"aud\", \"exp\", \"iat\"];\nvar ClaimsService = class {\n  constructor(_settings) {\n    this._settings = _settings;\n    this._logger = new Logger(\"ClaimsService\");\n  }\n  filterProtocolClaims(claims) {\n    const result = { ...claims };\n    if (this._settings.filterProtocolClaims) {\n      let protocolClaims;\n      if (Array.isArray(this._settings.filterProtocolClaims)) {\n        protocolClaims = this._settings.filterProtocolClaims;\n      } else {\n        protocolClaims = DefaultProtocolClaims;\n      }\n      for (const claim of protocolClaims) {\n        if (!InternalRequiredProtocolClaims.includes(claim)) {\n          delete result[claim];\n        }\n      }\n    }\n    return result;\n  }\n  mergeClaims(claims1, claims2) {\n    const result = { ...claims1 };\n    for (const [claim, values] of Object.entries(claims2)) {\n      if (result[claim] !== values) {\n        if (Array.isArray(result[claim]) || Array.isArray(values)) {\n          if (this._settings.mergeClaimsStrategy.array == \"replace\") {\n            result[claim] = values;\n          } else {\n            const mergedValues = Array.isArray(result[claim]) ? result[claim] : [result[claim]];\n            for (const value of Array.isArray(values) ? values : [values]) {\n              if (!mergedValues.includes(value)) {\n                mergedValues.push(value);\n              }\n            }\n            result[claim] = mergedValues;\n          }\n        } else if (typeof result[claim] === \"object\" && typeof values === \"object\") {\n          result[claim] = this.mergeClaims(result[claim], values);\n        } else {\n          result[claim] = values;\n        }\n      }\n    }\n    return result;\n  }\n};\n\n// src/DPoPStore.ts\nvar DPoPState = class {\n  constructor(keys, nonce) {\n    this.keys = keys;\n    this.nonce = nonce;\n  }\n};\n\n// src/OidcClient.ts\nvar OidcClient = class {\n  constructor(settings, metadataService) {\n    this._logger = new Logger(\"OidcClient\");\n    this.settings = settings instanceof OidcClientSettingsStore ? settings : new OidcClientSettingsStore(settings);\n    this.metadataService = metadataService != null ? metadataService : new MetadataService(this.settings);\n    this._claimsService = new ClaimsService(this.settings);\n    this._validator = new ResponseValidator(this.settings, this.metadataService, this._claimsService);\n    this._tokenClient = new TokenClient(this.settings, this.metadataService);\n  }\n  async createSigninRequest({\n    state,\n    request,\n    request_uri,\n    request_type,\n    id_token_hint,\n    login_hint,\n    skipUserInfo,\n    nonce,\n    url_state,\n    response_type = this.settings.response_type,\n    scope = this.settings.scope,\n    redirect_uri = this.settings.redirect_uri,\n    prompt = this.settings.prompt,\n    display = this.settings.display,\n    max_age = this.settings.max_age,\n    ui_locales = this.settings.ui_locales,\n    acr_values = this.settings.acr_values,\n    resource = this.settings.resource,\n    response_mode = this.settings.response_mode,\n    extraQueryParams = this.settings.extraQueryParams,\n    extraTokenParams = this.settings.extraTokenParams,\n    dpopJkt,\n    omitScopeWhenRequesting = this.settings.omitScopeWhenRequesting\n  }) {\n    const logger2 = this._logger.create(\"createSigninRequest\");\n    if (response_type !== \"code\") {\n      throw new Error(\"Only the Authorization Code flow (with PKCE) is supported\");\n    }\n    const url = await this.metadataService.getAuthorizationEndpoint();\n    logger2.debug(\"Received authorization endpoint\", url);\n    const signinRequest = await SigninRequest.create({\n      url,\n      authority: this.settings.authority,\n      client_id: this.settings.client_id,\n      redirect_uri,\n      response_type,\n      scope,\n      state_data: state,\n      url_state,\n      prompt,\n      display,\n      max_age,\n      ui_locales,\n      id_token_hint,\n      login_hint,\n      acr_values,\n      dpopJkt,\n      resource,\n      request,\n      request_uri,\n      extraQueryParams,\n      extraTokenParams,\n      request_type,\n      response_mode,\n      client_secret: this.settings.client_secret,\n      skipUserInfo,\n      nonce,\n      disablePKCE: this.settings.disablePKCE,\n      omitScopeWhenRequesting\n    });\n    await this.clearStaleState();\n    const signinState = signinRequest.state;\n    await this.settings.stateStore.set(signinState.id, signinState.toStorageString());\n    return signinRequest;\n  }\n  async readSigninResponseState(url, removeState = false) {\n    const logger2 = this._logger.create(\"readSigninResponseState\");\n    const response = new SigninResponse(UrlUtils.readParams(url, this.settings.response_mode));\n    if (!response.state) {\n      logger2.throw(new Error(\"No state in response\"));\n      throw null;\n    }\n    const storedStateString = await this.settings.stateStore[removeState ? \"remove\" : \"get\"](response.state);\n    if (!storedStateString) {\n      logger2.throw(new Error(\"No matching state found in storage\"));\n      throw null;\n    }\n    const state = await SigninState.fromStorageString(storedStateString);\n    return { state, response };\n  }\n  async processSigninResponse(url, extraHeaders) {\n    const logger2 = this._logger.create(\"processSigninResponse\");\n    const { state, response } = await this.readSigninResponseState(url, true);\n    logger2.debug(\"received state from storage; validating response\");\n    if (this.settings.dpop && this.settings.dpop.store) {\n      const dpopProof = await this.getDpopProof(this.settings.dpop.store);\n      extraHeaders = { ...extraHeaders, \"DPoP\": dpopProof };\n    }\n    try {\n      await this._validator.validateSigninResponse(response, state, extraHeaders);\n    } catch (err) {\n      if (err instanceof ErrorDPoPNonce && this.settings.dpop) {\n        const dpopProof = await this.getDpopProof(this.settings.dpop.store, err.nonce);\n        extraHeaders[\"DPoP\"] = dpopProof;\n        await this._validator.validateSigninResponse(response, state, extraHeaders);\n      } else {\n        throw err;\n      }\n    }\n    return response;\n  }\n  async getDpopProof(dpopStore, nonce) {\n    let keyPair;\n    let dpopState;\n    if (!(await dpopStore.getAllKeys()).includes(this.settings.client_id)) {\n      keyPair = await CryptoUtils.generateDPoPKeys();\n      dpopState = new DPoPState(keyPair, nonce);\n      await dpopStore.set(this.settings.client_id, dpopState);\n    } else {\n      dpopState = await dpopStore.get(this.settings.client_id);\n      if (dpopState.nonce !== nonce && nonce) {\n        dpopState.nonce = nonce;\n        await dpopStore.set(this.settings.client_id, dpopState);\n      }\n    }\n    return await CryptoUtils.generateDPoPProof({\n      url: await this.metadataService.getTokenEndpoint(false),\n      httpMethod: \"POST\",\n      keyPair: dpopState.keys,\n      nonce: dpopState.nonce\n    });\n  }\n  async processResourceOwnerPasswordCredentials({\n    username,\n    password,\n    skipUserInfo = false,\n    extraTokenParams = {}\n  }) {\n    const tokenResponse = await this._tokenClient.exchangeCredentials({ username, password, ...extraTokenParams });\n    const signinResponse = new SigninResponse(new URLSearchParams());\n    Object.assign(signinResponse, tokenResponse);\n    await this._validator.validateCredentialsResponse(signinResponse, skipUserInfo);\n    return signinResponse;\n  }\n  async useRefreshToken({\n    state,\n    redirect_uri,\n    resource,\n    timeoutInSeconds,\n    extraHeaders,\n    extraTokenParams\n  }) {\n    var _a;\n    const logger2 = this._logger.create(\"useRefreshToken\");\n    let scope;\n    if (this.settings.refreshTokenAllowedScope === void 0) {\n      scope = state.scope;\n    } else {\n      const allowableScopes = this.settings.refreshTokenAllowedScope.split(\" \");\n      const providedScopes = ((_a = state.scope) == null ? void 0 : _a.split(\" \")) || [];\n      scope = providedScopes.filter((s) => allowableScopes.includes(s)).join(\" \");\n    }\n    if (this.settings.dpop && this.settings.dpop.store) {\n      const dpopProof = await this.getDpopProof(this.settings.dpop.store);\n      extraHeaders = { ...extraHeaders, \"DPoP\": dpopProof };\n    }\n    let result;\n    try {\n      result = await this._tokenClient.exchangeRefreshToken({\n        refresh_token: state.refresh_token,\n        // provide the (possible filtered) scope list\n        scope,\n        redirect_uri,\n        resource,\n        timeoutInSeconds,\n        extraHeaders,\n        ...extraTokenParams\n      });\n    } catch (err) {\n      if (err instanceof ErrorDPoPNonce && this.settings.dpop) {\n        extraHeaders[\"DPoP\"] = await this.getDpopProof(this.settings.dpop.store, err.nonce);\n        result = await this._tokenClient.exchangeRefreshToken({\n          refresh_token: state.refresh_token,\n          // provide the (possible filtered) scope list\n          scope,\n          redirect_uri,\n          resource,\n          timeoutInSeconds,\n          extraHeaders,\n          ...extraTokenParams\n        });\n      } else {\n        throw err;\n      }\n    }\n    const response = new SigninResponse(new URLSearchParams());\n    Object.assign(response, result);\n    logger2.debug(\"validating response\", response);\n    await this._validator.validateRefreshResponse(response, {\n      ...state,\n      // override the scope in the state handed over to the validator\n      // so it can set the granted scope to the requested scope in case none is included in the response\n      scope\n    });\n    return response;\n  }\n  async createSignoutRequest({\n    state,\n    id_token_hint,\n    client_id,\n    request_type,\n    post_logout_redirect_uri = this.settings.post_logout_redirect_uri,\n    extraQueryParams = this.settings.extraQueryParams\n  } = {}) {\n    const logger2 = this._logger.create(\"createSignoutRequest\");\n    const url = await this.metadataService.getEndSessionEndpoint();\n    if (!url) {\n      logger2.throw(new Error(\"No end session endpoint\"));\n      throw null;\n    }\n    logger2.debug(\"Received end session endpoint\", url);\n    if (!client_id && post_logout_redirect_uri && !id_token_hint) {\n      client_id = this.settings.client_id;\n    }\n    const request = new SignoutRequest({\n      url,\n      id_token_hint,\n      client_id,\n      post_logout_redirect_uri,\n      state_data: state,\n      extraQueryParams,\n      request_type\n    });\n    await this.clearStaleState();\n    const signoutState = request.state;\n    if (signoutState) {\n      logger2.debug(\"Signout request has state to persist\");\n      await this.settings.stateStore.set(signoutState.id, signoutState.toStorageString());\n    }\n    return request;\n  }\n  async readSignoutResponseState(url, removeState = false) {\n    const logger2 = this._logger.create(\"readSignoutResponseState\");\n    const response = new SignoutResponse(UrlUtils.readParams(url, this.settings.response_mode));\n    if (!response.state) {\n      logger2.debug(\"No state in response\");\n      if (response.error) {\n        logger2.warn(\"Response was error:\", response.error);\n        throw new ErrorResponse(response);\n      }\n      return { state: void 0, response };\n    }\n    const storedStateString = await this.settings.stateStore[removeState ? \"remove\" : \"get\"](response.state);\n    if (!storedStateString) {\n      logger2.throw(new Error(\"No matching state found in storage\"));\n      throw null;\n    }\n    const state = await State.fromStorageString(storedStateString);\n    return { state, response };\n  }\n  async processSignoutResponse(url) {\n    const logger2 = this._logger.create(\"processSignoutResponse\");\n    const { state, response } = await this.readSignoutResponseState(url, true);\n    if (state) {\n      logger2.debug(\"Received state from storage; validating response\");\n      this._validator.validateSignoutResponse(response, state);\n    } else {\n      logger2.debug(\"No state from storage; skipping response validation\");\n    }\n    return response;\n  }\n  clearStaleState() {\n    this._logger.create(\"clearStaleState\");\n    return State.clearStaleState(this.settings.stateStore, this.settings.staleStateAgeInSeconds);\n  }\n  async revokeToken(token, type) {\n    this._logger.create(\"revokeToken\");\n    return await this._tokenClient.revoke({\n      token,\n      token_type_hint: type\n    });\n  }\n};\n\n// src/SessionMonitor.ts\nvar SessionMonitor = class {\n  constructor(_userManager) {\n    this._userManager = _userManager;\n    this._logger = new Logger(\"SessionMonitor\");\n    this._start = async (user) => {\n      const session_state = user.session_state;\n      if (!session_state) {\n        return;\n      }\n      const logger2 = this._logger.create(\"_start\");\n      if (user.profile) {\n        this._sub = user.profile.sub;\n        logger2.debug(\"session_state\", session_state, \", sub\", this._sub);\n      } else {\n        this._sub = void 0;\n        logger2.debug(\"session_state\", session_state, \", anonymous user\");\n      }\n      if (this._checkSessionIFrame) {\n        this._checkSessionIFrame.start(session_state);\n        return;\n      }\n      try {\n        const url = await this._userManager.metadataService.getCheckSessionIframe();\n        if (url) {\n          logger2.debug(\"initializing check session iframe\");\n          const client_id = this._userManager.settings.client_id;\n          const intervalInSeconds = this._userManager.settings.checkSessionIntervalInSeconds;\n          const stopOnError = this._userManager.settings.stopCheckSessionOnError;\n          const checkSessionIFrame = new CheckSessionIFrame(this._callback, client_id, url, intervalInSeconds, stopOnError);\n          await checkSessionIFrame.load();\n          this._checkSessionIFrame = checkSessionIFrame;\n          checkSessionIFrame.start(session_state);\n        } else {\n          logger2.warn(\"no check session iframe found in the metadata\");\n        }\n      } catch (err) {\n        logger2.error(\"Error from getCheckSessionIframe:\", err instanceof Error ? err.message : err);\n      }\n    };\n    this._stop = () => {\n      const logger2 = this._logger.create(\"_stop\");\n      this._sub = void 0;\n      if (this._checkSessionIFrame) {\n        this._checkSessionIFrame.stop();\n      }\n      if (this._userManager.settings.monitorAnonymousSession) {\n        const timerHandle = setInterval(async () => {\n          clearInterval(timerHandle);\n          try {\n            const session = await this._userManager.querySessionStatus();\n            if (session) {\n              const tmpUser = {\n                session_state: session.session_state,\n                profile: session.sub ? {\n                  sub: session.sub\n                } : null\n              };\n              void this._start(tmpUser);\n            }\n          } catch (err) {\n            logger2.error(\"error from querySessionStatus\", err instanceof Error ? err.message : err);\n          }\n        }, 1e3);\n      }\n    };\n    this._callback = async () => {\n      const logger2 = this._logger.create(\"_callback\");\n      try {\n        const session = await this._userManager.querySessionStatus();\n        let raiseEvent = true;\n        if (session && this._checkSessionIFrame) {\n          if (session.sub === this._sub) {\n            raiseEvent = false;\n            this._checkSessionIFrame.start(session.session_state);\n            logger2.debug(\"same sub still logged in at OP, session state has changed, restarting check session iframe; session_state\", session.session_state);\n            await this._userManager.events._raiseUserSessionChanged();\n          } else {\n            logger2.debug(\"different subject signed into OP\", session.sub);\n          }\n        } else {\n          logger2.debug(\"subject no longer signed into OP\");\n        }\n        if (raiseEvent) {\n          if (this._sub) {\n            await this._userManager.events._raiseUserSignedOut();\n          } else {\n            await this._userManager.events._raiseUserSignedIn();\n          }\n        } else {\n          logger2.debug(\"no change in session detected, no event to raise\");\n        }\n      } catch (err) {\n        if (this._sub) {\n          logger2.debug(\"Error calling queryCurrentSigninSession; raising signed out event\", err);\n          await this._userManager.events._raiseUserSignedOut();\n        }\n      }\n    };\n    if (!_userManager) {\n      this._logger.throw(new Error(\"No user manager passed\"));\n    }\n    this._userManager.events.addUserLoaded(this._start);\n    this._userManager.events.addUserUnloaded(this._stop);\n    this._init().catch((err) => {\n      this._logger.error(err);\n    });\n  }\n  async _init() {\n    this._logger.create(\"_init\");\n    const user = await this._userManager.getUser();\n    if (user) {\n      void this._start(user);\n    } else if (this._userManager.settings.monitorAnonymousSession) {\n      const session = await this._userManager.querySessionStatus();\n      if (session) {\n        const tmpUser = {\n          session_state: session.session_state,\n          profile: session.sub ? {\n            sub: session.sub\n          } : null\n        };\n        void this._start(tmpUser);\n      }\n    }\n  }\n};\n\n// src/User.ts\nvar User = class _User {\n  constructor(args) {\n    var _a;\n    this.id_token = args.id_token;\n    this.session_state = (_a = args.session_state) != null ? _a : null;\n    this.access_token = args.access_token;\n    this.refresh_token = args.refresh_token;\n    this.token_type = args.token_type;\n    this.scope = args.scope;\n    this.profile = args.profile;\n    this.expires_at = args.expires_at;\n    this.state = args.userState;\n    this.url_state = args.url_state;\n  }\n  /** Computed number of seconds the access token has remaining. */\n  get expires_in() {\n    if (this.expires_at === void 0) {\n      return void 0;\n    }\n    return this.expires_at - Timer.getEpochTime();\n  }\n  set expires_in(value) {\n    if (value !== void 0) {\n      this.expires_at = Math.floor(value) + Timer.getEpochTime();\n    }\n  }\n  /** Computed value indicating if the access token is expired. */\n  get expired() {\n    const expires_in = this.expires_in;\n    if (expires_in === void 0) {\n      return void 0;\n    }\n    return expires_in <= 0;\n  }\n  /** Array representing the parsed values from the `scope`. */\n  get scopes() {\n    var _a, _b;\n    return (_b = (_a = this.scope) == null ? void 0 : _a.split(\" \")) != null ? _b : [];\n  }\n  toStorageString() {\n    new Logger(\"User\").create(\"toStorageString\");\n    return JSON.stringify({\n      id_token: this.id_token,\n      session_state: this.session_state,\n      access_token: this.access_token,\n      refresh_token: this.refresh_token,\n      token_type: this.token_type,\n      scope: this.scope,\n      profile: this.profile,\n      expires_at: this.expires_at\n    });\n  }\n  static fromStorageString(storageString) {\n    Logger.createStatic(\"User\", \"fromStorageString\");\n    return new _User(JSON.parse(storageString));\n  }\n};\n\n// src/navigators/AbstractChildWindow.ts\nvar messageSource = \"oidc-client\";\nvar AbstractChildWindow = class {\n  constructor() {\n    this._abort = new Event(\"Window navigation aborted\");\n    this._disposeHandlers = /* @__PURE__ */ new Set();\n    this._window = null;\n  }\n  async navigate(params) {\n    const logger2 = this._logger.create(\"navigate\");\n    if (!this._window) {\n      throw new Error(\"Attempted to navigate on a disposed window\");\n    }\n    logger2.debug(\"setting URL in window\");\n    this._window.location.replace(params.url);\n    const { url, keepOpen } = await new Promise((resolve, reject) => {\n      const listener = (e) => {\n        var _a;\n        const data = e.data;\n        const origin = (_a = params.scriptOrigin) != null ? _a : window.location.origin;\n        if (e.origin !== origin || (data == null ? void 0 : data.source) !== messageSource) {\n          return;\n        }\n        try {\n          const state = UrlUtils.readParams(data.url, params.response_mode).get(\"state\");\n          if (!state) {\n            logger2.warn(\"no state found in response url\");\n          }\n          if (e.source !== this._window && state !== params.state) {\n            return;\n          }\n        } catch (err) {\n          this._dispose();\n          reject(new Error(\"Invalid response from window\"));\n        }\n        resolve(data);\n      };\n      window.addEventListener(\"message\", listener, false);\n      this._disposeHandlers.add(() => window.removeEventListener(\"message\", listener, false));\n      this._disposeHandlers.add(this._abort.addHandler((reason) => {\n        this._dispose();\n        reject(reason);\n      }));\n    });\n    logger2.debug(\"got response from window\");\n    this._dispose();\n    if (!keepOpen) {\n      this.close();\n    }\n    return { url };\n  }\n  _dispose() {\n    this._logger.create(\"_dispose\");\n    for (const dispose of this._disposeHandlers) {\n      dispose();\n    }\n    this._disposeHandlers.clear();\n  }\n  static _notifyParent(parent, url, keepOpen = false, targetOrigin = window.location.origin) {\n    parent.postMessage({\n      source: messageSource,\n      url,\n      keepOpen\n    }, targetOrigin);\n  }\n};\n\n// src/UserManagerSettings.ts\nvar DefaultPopupWindowFeatures = {\n  location: false,\n  toolbar: false,\n  height: 640,\n  closePopupWindowAfterInSeconds: -1\n};\nvar DefaultPopupTarget = \"_blank\";\nvar DefaultAccessTokenExpiringNotificationTimeInSeconds = 60;\nvar DefaultCheckSessionIntervalInSeconds = 2;\nvar DefaultSilentRequestTimeoutInSeconds = 10;\nvar UserManagerSettingsStore = class extends OidcClientSettingsStore {\n  constructor(args) {\n    const {\n      popup_redirect_uri = args.redirect_uri,\n      popup_post_logout_redirect_uri = args.post_logout_redirect_uri,\n      popupWindowFeatures = DefaultPopupWindowFeatures,\n      popupWindowTarget = DefaultPopupTarget,\n      redirectMethod = \"assign\",\n      redirectTarget = \"self\",\n      iframeNotifyParentOrigin = args.iframeNotifyParentOrigin,\n      iframeScriptOrigin = args.iframeScriptOrigin,\n      requestTimeoutInSeconds,\n      silent_redirect_uri = args.redirect_uri,\n      silentRequestTimeoutInSeconds,\n      automaticSilentRenew = true,\n      validateSubOnSilentRenew = true,\n      includeIdTokenInSilentRenew = false,\n      monitorSession = false,\n      monitorAnonymousSession = false,\n      checkSessionIntervalInSeconds = DefaultCheckSessionIntervalInSeconds,\n      query_status_response_type = \"code\",\n      stopCheckSessionOnError = true,\n      revokeTokenTypes = [\"access_token\", \"refresh_token\"],\n      revokeTokensOnSignout = false,\n      includeIdTokenInSilentSignout = false,\n      accessTokenExpiringNotificationTimeInSeconds = DefaultAccessTokenExpiringNotificationTimeInSeconds,\n      userStore\n    } = args;\n    super(args);\n    this.popup_redirect_uri = popup_redirect_uri;\n    this.popup_post_logout_redirect_uri = popup_post_logout_redirect_uri;\n    this.popupWindowFeatures = popupWindowFeatures;\n    this.popupWindowTarget = popupWindowTarget;\n    this.redirectMethod = redirectMethod;\n    this.redirectTarget = redirectTarget;\n    this.iframeNotifyParentOrigin = iframeNotifyParentOrigin;\n    this.iframeScriptOrigin = iframeScriptOrigin;\n    this.silent_redirect_uri = silent_redirect_uri;\n    this.silentRequestTimeoutInSeconds = silentRequestTimeoutInSeconds || requestTimeoutInSeconds || DefaultSilentRequestTimeoutInSeconds;\n    this.automaticSilentRenew = automaticSilentRenew;\n    this.validateSubOnSilentRenew = validateSubOnSilentRenew;\n    this.includeIdTokenInSilentRenew = includeIdTokenInSilentRenew;\n    this.monitorSession = monitorSession;\n    this.monitorAnonymousSession = monitorAnonymousSession;\n    this.checkSessionIntervalInSeconds = checkSessionIntervalInSeconds;\n    this.stopCheckSessionOnError = stopCheckSessionOnError;\n    this.query_status_response_type = query_status_response_type;\n    this.revokeTokenTypes = revokeTokenTypes;\n    this.revokeTokensOnSignout = revokeTokensOnSignout;\n    this.includeIdTokenInSilentSignout = includeIdTokenInSilentSignout;\n    this.accessTokenExpiringNotificationTimeInSeconds = accessTokenExpiringNotificationTimeInSeconds;\n    if (userStore) {\n      this.userStore = userStore;\n    } else {\n      const store = typeof window !== \"undefined\" ? window.sessionStorage : new InMemoryWebStorage();\n      this.userStore = new WebStorageStateStore({ store });\n    }\n  }\n};\n\n// src/navigators/IFrameWindow.ts\nvar IFrameWindow = class _IFrameWindow extends AbstractChildWindow {\n  constructor({\n    silentRequestTimeoutInSeconds = DefaultSilentRequestTimeoutInSeconds\n  }) {\n    super();\n    this._logger = new Logger(\"IFrameWindow\");\n    this._timeoutInSeconds = silentRequestTimeoutInSeconds;\n    this._frame = _IFrameWindow.createHiddenIframe();\n    this._window = this._frame.contentWindow;\n  }\n  static createHiddenIframe() {\n    const iframe = window.document.createElement(\"iframe\");\n    iframe.style.visibility = \"hidden\";\n    iframe.style.position = \"fixed\";\n    iframe.style.left = \"-1000px\";\n    iframe.style.top = \"0\";\n    iframe.width = \"0\";\n    iframe.height = \"0\";\n    window.document.body.appendChild(iframe);\n    return iframe;\n  }\n  async navigate(params) {\n    this._logger.debug(\"navigate: Using timeout of:\", this._timeoutInSeconds);\n    const timer = setTimeout(() => void this._abort.raise(new ErrorTimeout(\"IFrame timed out without a response\")), this._timeoutInSeconds * 1e3);\n    this._disposeHandlers.add(() => clearTimeout(timer));\n    return await super.navigate(params);\n  }\n  close() {\n    var _a;\n    if (this._frame) {\n      if (this._frame.parentNode) {\n        this._frame.addEventListener(\"load\", (ev) => {\n          var _a2;\n          const frame = ev.target;\n          (_a2 = frame.parentNode) == null ? void 0 : _a2.removeChild(frame);\n          void this._abort.raise(new Error(\"IFrame removed from DOM\"));\n        }, true);\n        (_a = this._frame.contentWindow) == null ? void 0 : _a.location.replace(\"about:blank\");\n      }\n      this._frame = null;\n    }\n    this._window = null;\n  }\n  static notifyParent(url, targetOrigin) {\n    return super._notifyParent(window.parent, url, false, targetOrigin);\n  }\n};\n\n// src/navigators/IFrameNavigator.ts\nvar IFrameNavigator = class {\n  constructor(_settings) {\n    this._settings = _settings;\n    this._logger = new Logger(\"IFrameNavigator\");\n  }\n  async prepare({\n    silentRequestTimeoutInSeconds = this._settings.silentRequestTimeoutInSeconds\n  }) {\n    return new IFrameWindow({ silentRequestTimeoutInSeconds });\n  }\n  async callback(url) {\n    this._logger.create(\"callback\");\n    IFrameWindow.notifyParent(url, this._settings.iframeNotifyParentOrigin);\n  }\n};\n\n// src/navigators/PopupWindow.ts\nvar checkForPopupClosedInterval = 500;\nvar second = 1e3;\nvar PopupWindow = class extends AbstractChildWindow {\n  constructor({\n    popupWindowTarget = DefaultPopupTarget,\n    popupWindowFeatures = {},\n    popupSignal\n  }) {\n    super();\n    this._logger = new Logger(\"PopupWindow\");\n    const centeredPopup = PopupUtils.center({ ...DefaultPopupWindowFeatures, ...popupWindowFeatures });\n    this._window = window.open(void 0, popupWindowTarget, PopupUtils.serialize(centeredPopup));\n    if (popupSignal) {\n      popupSignal.addEventListener(\"abort\", () => {\n        var _a;\n        void this._abort.raise(new Error((_a = popupSignal.reason) != null ? _a : \"Popup aborted\"));\n      });\n    }\n    if (popupWindowFeatures.closePopupWindowAfterInSeconds && popupWindowFeatures.closePopupWindowAfterInSeconds > 0) {\n      setTimeout(() => {\n        if (!this._window || typeof this._window.closed !== \"boolean\" || this._window.closed) {\n          void this._abort.raise(new Error(\"Popup blocked by user\"));\n          return;\n        }\n        this.close();\n      }, popupWindowFeatures.closePopupWindowAfterInSeconds * second);\n    }\n  }\n  async navigate(params) {\n    var _a;\n    (_a = this._window) == null ? void 0 : _a.focus();\n    const popupClosedInterval = setInterval(() => {\n      if (!this._window || this._window.closed) {\n        void this._abort.raise(new Error(\"Popup closed by user\"));\n      }\n    }, checkForPopupClosedInterval);\n    this._disposeHandlers.add(() => clearInterval(popupClosedInterval));\n    return await super.navigate(params);\n  }\n  close() {\n    if (this._window) {\n      if (!this._window.closed) {\n        this._window.close();\n        void this._abort.raise(new Error(\"Popup closed\"));\n      }\n    }\n    this._window = null;\n  }\n  static notifyOpener(url, keepOpen) {\n    if (!window.opener) {\n      throw new Error(\"No window.opener. Can't complete notification.\");\n    }\n    return super._notifyParent(window.opener, url, keepOpen);\n  }\n};\n\n// src/navigators/PopupNavigator.ts\nvar PopupNavigator = class {\n  constructor(_settings) {\n    this._settings = _settings;\n    this._logger = new Logger(\"PopupNavigator\");\n  }\n  async prepare({\n    popupWindowFeatures = this._settings.popupWindowFeatures,\n    popupWindowTarget = this._settings.popupWindowTarget,\n    popupSignal\n  }) {\n    return new PopupWindow({ popupWindowFeatures, popupWindowTarget, popupSignal });\n  }\n  async callback(url, { keepOpen = false }) {\n    this._logger.create(\"callback\");\n    PopupWindow.notifyOpener(url, keepOpen);\n  }\n};\n\n// src/navigators/RedirectNavigator.ts\nvar RedirectNavigator = class {\n  constructor(_settings) {\n    this._settings = _settings;\n    this._logger = new Logger(\"RedirectNavigator\");\n  }\n  async prepare({\n    redirectMethod = this._settings.redirectMethod,\n    redirectTarget = this._settings.redirectTarget\n  }) {\n    var _a;\n    this._logger.create(\"prepare\");\n    let targetWindow = window.self;\n    if (redirectTarget === \"top\") {\n      targetWindow = (_a = window.top) != null ? _a : window.self;\n    }\n    const redirect = targetWindow.location[redirectMethod].bind(targetWindow.location);\n    let abort;\n    return {\n      navigate: async (params) => {\n        this._logger.create(\"navigate\");\n        const promise = new Promise((resolve, reject) => {\n          abort = reject;\n        });\n        redirect(params.url);\n        return await promise;\n      },\n      close: () => {\n        this._logger.create(\"close\");\n        abort == null ? void 0 : abort(new Error(\"Redirect aborted\"));\n        targetWindow.stop();\n      }\n    };\n  }\n  async callback() {\n    return;\n  }\n};\n\n// src/UserManagerEvents.ts\nvar UserManagerEvents = class extends AccessTokenEvents {\n  constructor(settings) {\n    super({ expiringNotificationTimeInSeconds: settings.accessTokenExpiringNotificationTimeInSeconds });\n    this._logger = new Logger(\"UserManagerEvents\");\n    this._userLoaded = new Event(\"User loaded\");\n    this._userUnloaded = new Event(\"User unloaded\");\n    this._silentRenewError = new Event(\"Silent renew error\");\n    this._userSignedIn = new Event(\"User signed in\");\n    this._userSignedOut = new Event(\"User signed out\");\n    this._userSessionChanged = new Event(\"User session changed\");\n  }\n  async load(user, raiseEvent = true) {\n    super.load(user);\n    if (raiseEvent) {\n      await this._userLoaded.raise(user);\n    }\n  }\n  async unload() {\n    super.unload();\n    await this._userUnloaded.raise();\n  }\n  /**\n   * Add callback: Raised when a user session has been established (or re-established).\n   */\n  addUserLoaded(cb) {\n    return this._userLoaded.addHandler(cb);\n  }\n  /**\n   * Remove callback: Raised when a user session has been established (or re-established).\n   */\n  removeUserLoaded(cb) {\n    return this._userLoaded.removeHandler(cb);\n  }\n  /**\n   * Add callback: Raised when a user session has been terminated.\n   */\n  addUserUnloaded(cb) {\n    return this._userUnloaded.addHandler(cb);\n  }\n  /**\n   * Remove callback: Raised when a user session has been terminated.\n   */\n  removeUserUnloaded(cb) {\n    return this._userUnloaded.removeHandler(cb);\n  }\n  /**\n   * Add callback: Raised when the automatic silent renew has failed.\n   */\n  addSilentRenewError(cb) {\n    return this._silentRenewError.addHandler(cb);\n  }\n  /**\n   * Remove callback: Raised when the automatic silent renew has failed.\n   */\n  removeSilentRenewError(cb) {\n    return this._silentRenewError.removeHandler(cb);\n  }\n  /**\n   * @internal\n   */\n  async _raiseSilentRenewError(e) {\n    await this._silentRenewError.raise(e);\n  }\n  /**\n   * Add callback: Raised when the user is signed in (when `monitorSession` is set).\n   * @see {@link UserManagerSettings.monitorSession}\n   */\n  addUserSignedIn(cb) {\n    return this._userSignedIn.addHandler(cb);\n  }\n  /**\n   * Remove callback: Raised when the user is signed in (when `monitorSession` is set).\n   */\n  removeUserSignedIn(cb) {\n    this._userSignedIn.removeHandler(cb);\n  }\n  /**\n   * @internal\n   */\n  async _raiseUserSignedIn() {\n    await this._userSignedIn.raise();\n  }\n  /**\n   * Add callback: Raised when the user's sign-in status at the OP has changed (when `monitorSession` is set).\n   * @see {@link UserManagerSettings.monitorSession}\n   */\n  addUserSignedOut(cb) {\n    return this._userSignedOut.addHandler(cb);\n  }\n  /**\n   * Remove callback: Raised when the user's sign-in status at the OP has changed (when `monitorSession` is set).\n   */\n  removeUserSignedOut(cb) {\n    this._userSignedOut.removeHandler(cb);\n  }\n  /**\n   * @internal\n   */\n  async _raiseUserSignedOut() {\n    await this._userSignedOut.raise();\n  }\n  /**\n   * Add callback: Raised when the user session changed (when `monitorSession` is set).\n   * @see {@link UserManagerSettings.monitorSession}\n   */\n  addUserSessionChanged(cb) {\n    return this._userSessionChanged.addHandler(cb);\n  }\n  /**\n   * Remove callback: Raised when the user session changed (when `monitorSession` is set).\n   */\n  removeUserSessionChanged(cb) {\n    this._userSessionChanged.removeHandler(cb);\n  }\n  /**\n   * @internal\n   */\n  async _raiseUserSessionChanged() {\n    await this._userSessionChanged.raise();\n  }\n};\n\n// src/SilentRenewService.ts\nvar SilentRenewService = class {\n  constructor(_userManager) {\n    this._userManager = _userManager;\n    this._logger = new Logger(\"SilentRenewService\");\n    this._isStarted = false;\n    this._retryTimer = new Timer(\"Retry Silent Renew\");\n    this._tokenExpiring = async () => {\n      const logger2 = this._logger.create(\"_tokenExpiring\");\n      try {\n        await this._userManager.signinSilent();\n        logger2.debug(\"silent token renewal successful\");\n      } catch (err) {\n        if (err instanceof ErrorTimeout) {\n          logger2.warn(\"ErrorTimeout from signinSilent:\", err, \"retry in 5s\");\n          this._retryTimer.init(5);\n          return;\n        }\n        logger2.error(\"Error from signinSilent:\", err);\n        await this._userManager.events._raiseSilentRenewError(err);\n      }\n    };\n  }\n  async start() {\n    const logger2 = this._logger.create(\"start\");\n    if (!this._isStarted) {\n      this._isStarted = true;\n      this._userManager.events.addAccessTokenExpiring(this._tokenExpiring);\n      this._retryTimer.addHandler(this._tokenExpiring);\n      try {\n        await this._userManager.getUser();\n      } catch (err) {\n        logger2.error(\"getUser error\", err);\n      }\n    }\n  }\n  stop() {\n    if (this._isStarted) {\n      this._retryTimer.cancel();\n      this._retryTimer.removeHandler(this._tokenExpiring);\n      this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring);\n      this._isStarted = false;\n    }\n  }\n};\n\n// src/RefreshState.ts\nvar RefreshState = class {\n  constructor(args) {\n    this.refresh_token = args.refresh_token;\n    this.id_token = args.id_token;\n    this.session_state = args.session_state;\n    this.scope = args.scope;\n    this.profile = args.profile;\n    this.data = args.state;\n  }\n};\n\n// src/UserManager.ts\nvar UserManager = class {\n  constructor(settings, redirectNavigator, popupNavigator, iframeNavigator) {\n    this._logger = new Logger(\"UserManager\");\n    this.settings = new UserManagerSettingsStore(settings);\n    this._client = new OidcClient(settings);\n    this._redirectNavigator = redirectNavigator != null ? redirectNavigator : new RedirectNavigator(this.settings);\n    this._popupNavigator = popupNavigator != null ? popupNavigator : new PopupNavigator(this.settings);\n    this._iframeNavigator = iframeNavigator != null ? iframeNavigator : new IFrameNavigator(this.settings);\n    this._events = new UserManagerEvents(this.settings);\n    this._silentRenewService = new SilentRenewService(this);\n    if (this.settings.automaticSilentRenew) {\n      this.startSilentRenew();\n    }\n    this._sessionMonitor = null;\n    if (this.settings.monitorSession) {\n      this._sessionMonitor = new SessionMonitor(this);\n    }\n  }\n  /**\n   * Get object used to register for events raised by the `UserManager`.\n   */\n  get events() {\n    return this._events;\n  }\n  /**\n   * Get object used to access the metadata configuration of the identity provider.\n   */\n  get metadataService() {\n    return this._client.metadataService;\n  }\n  /**\n   * Load the `User` object for the currently authenticated user.\n   *\n   * @returns A promise\n   */\n  async getUser() {\n    const logger2 = this._logger.create(\"getUser\");\n    const user = await this._loadUser();\n    if (user) {\n      logger2.info(\"user loaded\");\n      await this._events.load(user, false);\n      return user;\n    }\n    logger2.info(\"user not found in storage\");\n    return null;\n  }\n  /**\n   * Remove from any storage the currently authenticated user.\n   *\n   * @returns A promise\n   */\n  async removeUser() {\n    const logger2 = this._logger.create(\"removeUser\");\n    await this.storeUser(null);\n    logger2.info(\"user removed from storage\");\n    await this._events.unload();\n  }\n  /**\n   * Trigger a redirect of the current window to the authorization endpoint.\n   *\n   * @returns A promise\n   *\n   * @throws `Error` In cases of wrong authentication.\n   */\n  async signinRedirect(args = {}) {\n    var _a;\n    this._logger.create(\"signinRedirect\");\n    const {\n      redirectMethod,\n      ...requestArgs\n    } = args;\n    let dpopJkt;\n    if ((_a = this.settings.dpop) == null ? void 0 : _a.bind_authorization_code) {\n      dpopJkt = await this.generateDPoPJkt(this.settings.dpop);\n    }\n    const handle = await this._redirectNavigator.prepare({ redirectMethod });\n    await this._signinStart({\n      request_type: \"si:r\",\n      dpopJkt,\n      ...requestArgs\n    }, handle);\n  }\n  /**\n   * Process the response (callback) from the authorization endpoint.\n   * It is recommended to use {@link UserManager.signinCallback} instead.\n   *\n   * @returns A promise containing the authenticated `User`.\n   *\n   * @see {@link UserManager.signinCallback}\n   */\n  async signinRedirectCallback(url = window.location.href) {\n    const logger2 = this._logger.create(\"signinRedirectCallback\");\n    const user = await this._signinEnd(url);\n    if (user.profile && user.profile.sub) {\n      logger2.info(\"success, signed in subject\", user.profile.sub);\n    } else {\n      logger2.info(\"no subject\");\n    }\n    return user;\n  }\n  /**\n   * Trigger the signin with user/password.\n   *\n   * @returns A promise containing the authenticated `User`.\n   * @throws {@link ErrorResponse} In cases of wrong authentication.\n   */\n  async signinResourceOwnerCredentials({\n    username,\n    password,\n    skipUserInfo = false\n  }) {\n    const logger2 = this._logger.create(\"signinResourceOwnerCredential\");\n    const signinResponse = await this._client.processResourceOwnerPasswordCredentials({\n      username,\n      password,\n      skipUserInfo,\n      extraTokenParams: this.settings.extraTokenParams\n    });\n    logger2.debug(\"got signin response\");\n    const user = await this._buildUser(signinResponse);\n    if (user.profile && user.profile.sub) {\n      logger2.info(\"success, signed in subject\", user.profile.sub);\n    } else {\n      logger2.info(\"no subject\");\n    }\n    return user;\n  }\n  /**\n   * Trigger a request (via a popup window) to the authorization endpoint.\n   *\n   * @returns A promise containing the authenticated `User`.\n   * @throws `Error` In cases of wrong authentication.\n   */\n  async signinPopup(args = {}) {\n    var _a;\n    const logger2 = this._logger.create(\"signinPopup\");\n    let dpopJkt;\n    if ((_a = this.settings.dpop) == null ? void 0 : _a.bind_authorization_code) {\n      dpopJkt = await this.generateDPoPJkt(this.settings.dpop);\n    }\n    const {\n      popupWindowFeatures,\n      popupWindowTarget,\n      popupSignal,\n      ...requestArgs\n    } = args;\n    const url = this.settings.popup_redirect_uri;\n    if (!url) {\n      logger2.throw(new Error(\"No popup_redirect_uri configured\"));\n    }\n    const handle = await this._popupNavigator.prepare({ popupWindowFeatures, popupWindowTarget, popupSignal });\n    const user = await this._signin({\n      request_type: \"si:p\",\n      redirect_uri: url,\n      display: \"popup\",\n      dpopJkt,\n      ...requestArgs\n    }, handle);\n    if (user) {\n      if (user.profile && user.profile.sub) {\n        logger2.info(\"success, signed in subject\", user.profile.sub);\n      } else {\n        logger2.info(\"no subject\");\n      }\n    }\n    return user;\n  }\n  /**\n   * Notify the opening window of response (callback) from the authorization endpoint.\n   * It is recommended to use {@link UserManager.signinCallback} instead.\n   *\n   * @returns A promise\n   *\n   * @see {@link UserManager.signinCallback}\n   */\n  async signinPopupCallback(url = window.location.href, keepOpen = false) {\n    const logger2 = this._logger.create(\"signinPopupCallback\");\n    await this._popupNavigator.callback(url, { keepOpen });\n    logger2.info(\"success\");\n  }\n  /**\n   * Trigger a silent request (via refresh token or an iframe) to the authorization endpoint.\n   *\n   * @returns A promise that contains the authenticated `User`.\n   */\n  async signinSilent(args = {}) {\n    var _a, _b;\n    const logger2 = this._logger.create(\"signinSilent\");\n    const {\n      silentRequestTimeoutInSeconds,\n      ...requestArgs\n    } = args;\n    let user = await this._loadUser();\n    if (user == null ? void 0 : user.refresh_token) {\n      logger2.debug(\"using refresh token\");\n      const state = new RefreshState(user);\n      return await this._useRefreshToken({\n        state,\n        redirect_uri: requestArgs.redirect_uri,\n        resource: requestArgs.resource,\n        extraTokenParams: requestArgs.extraTokenParams,\n        timeoutInSeconds: silentRequestTimeoutInSeconds\n      });\n    }\n    let dpopJkt;\n    if ((_a = this.settings.dpop) == null ? void 0 : _a.bind_authorization_code) {\n      dpopJkt = await this.generateDPoPJkt(this.settings.dpop);\n    }\n    const url = this.settings.silent_redirect_uri;\n    if (!url) {\n      logger2.throw(new Error(\"No silent_redirect_uri configured\"));\n    }\n    let verifySub;\n    if (user && this.settings.validateSubOnSilentRenew) {\n      logger2.debug(\"subject prior to silent renew:\", user.profile.sub);\n      verifySub = user.profile.sub;\n    }\n    const handle = await this._iframeNavigator.prepare({ silentRequestTimeoutInSeconds });\n    user = await this._signin({\n      request_type: \"si:s\",\n      redirect_uri: url,\n      prompt: \"none\",\n      id_token_hint: this.settings.includeIdTokenInSilentRenew ? user == null ? void 0 : user.id_token : void 0,\n      dpopJkt,\n      ...requestArgs\n    }, handle, verifySub);\n    if (user) {\n      if ((_b = user.profile) == null ? void 0 : _b.sub) {\n        logger2.info(\"success, signed in subject\", user.profile.sub);\n      } else {\n        logger2.info(\"no subject\");\n      }\n    }\n    return user;\n  }\n  async _useRefreshToken(args) {\n    const response = await this._client.useRefreshToken({\n      timeoutInSeconds: this.settings.silentRequestTimeoutInSeconds,\n      ...args\n    });\n    const user = new User({ ...args.state, ...response });\n    await this.storeUser(user);\n    await this._events.load(user);\n    return user;\n  }\n  /**\n   *\n   * Notify the parent window of response (callback) from the authorization endpoint.\n   * It is recommended to use {@link UserManager.signinCallback} instead.\n   *\n   * @returns A promise\n   *\n   * @see {@link UserManager.signinCallback}\n   */\n  async signinSilentCallback(url = window.location.href) {\n    const logger2 = this._logger.create(\"signinSilentCallback\");\n    await this._iframeNavigator.callback(url);\n    logger2.info(\"success\");\n  }\n  /**\n   * Process any response (callback) from the authorization endpoint, by dispatching the request_type\n   * and executing one of the following functions:\n   * - {@link UserManager.signinRedirectCallback}\n   * - {@link UserManager.signinPopupCallback}\n   * - {@link UserManager.signinSilentCallback}\n   *\n   * @throws `Error` If request_type is unknown or signin cannot be processed.\n   */\n  async signinCallback(url = window.location.href) {\n    const { state } = await this._client.readSigninResponseState(url);\n    switch (state.request_type) {\n      case \"si:r\":\n        return await this.signinRedirectCallback(url);\n      case \"si:p\":\n        await this.signinPopupCallback(url);\n        break;\n      case \"si:s\":\n        await this.signinSilentCallback(url);\n        break;\n      default:\n        throw new Error(\"invalid response_type in state\");\n    }\n    return void 0;\n  }\n  /**\n   * Process any response (callback) from the end session endpoint, by dispatching the request_type\n   * and executing one of the following functions:\n   * - {@link UserManager.signoutRedirectCallback}\n   * - {@link UserManager.signoutPopupCallback}\n   * - {@link UserManager.signoutSilentCallback}\n   *\n   * @throws `Error` If request_type is unknown or signout cannot be processed.\n   */\n  async signoutCallback(url = window.location.href, keepOpen = false) {\n    const { state } = await this._client.readSignoutResponseState(url);\n    if (!state) {\n      return void 0;\n    }\n    switch (state.request_type) {\n      case \"so:r\":\n        return await this.signoutRedirectCallback(url);\n      case \"so:p\":\n        await this.signoutPopupCallback(url, keepOpen);\n        break;\n      case \"so:s\":\n        await this.signoutSilentCallback(url);\n        break;\n      default:\n        throw new Error(\"invalid response_type in state\");\n    }\n    return void 0;\n  }\n  /**\n   * Query OP for user's current signin status.\n   *\n   * @returns A promise object with session_state and subject identifier.\n   */\n  async querySessionStatus(args = {}) {\n    const logger2 = this._logger.create(\"querySessionStatus\");\n    const {\n      silentRequestTimeoutInSeconds,\n      ...requestArgs\n    } = args;\n    const url = this.settings.silent_redirect_uri;\n    if (!url) {\n      logger2.throw(new Error(\"No silent_redirect_uri configured\"));\n    }\n    const user = await this._loadUser();\n    const handle = await this._iframeNavigator.prepare({ silentRequestTimeoutInSeconds });\n    const navResponse = await this._signinStart({\n      request_type: \"si:s\",\n      // this acts like a signin silent\n      redirect_uri: url,\n      prompt: \"none\",\n      id_token_hint: this.settings.includeIdTokenInSilentRenew ? user == null ? void 0 : user.id_token : void 0,\n      response_type: this.settings.query_status_response_type,\n      scope: \"openid\",\n      skipUserInfo: true,\n      ...requestArgs\n    }, handle);\n    try {\n      const extraHeaders = {};\n      const signinResponse = await this._client.processSigninResponse(navResponse.url, extraHeaders);\n      logger2.debug(\"got signin response\");\n      if (signinResponse.session_state && signinResponse.profile.sub) {\n        logger2.info(\"success for subject\", signinResponse.profile.sub);\n        return {\n          session_state: signinResponse.session_state,\n          sub: signinResponse.profile.sub\n        };\n      }\n      logger2.info(\"success, user not authenticated\");\n      return null;\n    } catch (err) {\n      if (this.settings.monitorAnonymousSession && err instanceof ErrorResponse) {\n        switch (err.error) {\n          case \"login_required\":\n          case \"consent_required\":\n          case \"interaction_required\":\n          case \"account_selection_required\":\n            logger2.info(\"success for anonymous user\");\n            return {\n              // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n              session_state: err.session_state\n            };\n        }\n      }\n      throw err;\n    }\n  }\n  async _signin(args, handle, verifySub) {\n    const navResponse = await this._signinStart(args, handle);\n    return await this._signinEnd(navResponse.url, verifySub);\n  }\n  async _signinStart(args, handle) {\n    const logger2 = this._logger.create(\"_signinStart\");\n    try {\n      const signinRequest = await this._client.createSigninRequest(args);\n      logger2.debug(\"got signin request\");\n      return await handle.navigate({\n        url: signinRequest.url,\n        state: signinRequest.state.id,\n        response_mode: signinRequest.state.response_mode,\n        scriptOrigin: this.settings.iframeScriptOrigin\n      });\n    } catch (err) {\n      logger2.debug(\"error after preparing navigator, closing navigator window\");\n      handle.close();\n      throw err;\n    }\n  }\n  async _signinEnd(url, verifySub) {\n    const logger2 = this._logger.create(\"_signinEnd\");\n    const extraHeaders = {};\n    const signinResponse = await this._client.processSigninResponse(url, extraHeaders);\n    logger2.debug(\"got signin response\");\n    const user = await this._buildUser(signinResponse, verifySub);\n    return user;\n  }\n  async _buildUser(signinResponse, verifySub) {\n    const logger2 = this._logger.create(\"_buildUser\");\n    const user = new User(signinResponse);\n    if (verifySub) {\n      if (verifySub !== user.profile.sub) {\n        logger2.debug(\"current user does not match user returned from signin. sub from signin:\", user.profile.sub);\n        throw new ErrorResponse({ ...signinResponse, error: \"login_required\" });\n      }\n      logger2.debug(\"current user matches user returned from signin\");\n    }\n    await this.storeUser(user);\n    logger2.debug(\"user stored\");\n    await this._events.load(user);\n    return user;\n  }\n  /**\n   * Trigger a redirect of the current window to the end session endpoint.\n   *\n   * @returns A promise\n   */\n  async signoutRedirect(args = {}) {\n    const logger2 = this._logger.create(\"signoutRedirect\");\n    const {\n      redirectMethod,\n      ...requestArgs\n    } = args;\n    const handle = await this._redirectNavigator.prepare({ redirectMethod });\n    await this._signoutStart({\n      request_type: \"so:r\",\n      post_logout_redirect_uri: this.settings.post_logout_redirect_uri,\n      ...requestArgs\n    }, handle);\n    logger2.info(\"success\");\n  }\n  /**\n   * Process response (callback) from the end session endpoint.\n   * It is recommended to use {@link UserManager.signoutCallback} instead.\n   *\n   * @returns A promise containing signout response\n   *\n   * @see {@link UserManager.signoutCallback}\n   */\n  async signoutRedirectCallback(url = window.location.href) {\n    const logger2 = this._logger.create(\"signoutRedirectCallback\");\n    const response = await this._signoutEnd(url);\n    logger2.info(\"success\");\n    return response;\n  }\n  /**\n   * Trigger a redirect of a popup window to the end session endpoint.\n   *\n   * @returns A promise\n   */\n  async signoutPopup(args = {}) {\n    const logger2 = this._logger.create(\"signoutPopup\");\n    const {\n      popupWindowFeatures,\n      popupWindowTarget,\n      popupSignal,\n      ...requestArgs\n    } = args;\n    const url = this.settings.popup_post_logout_redirect_uri;\n    const handle = await this._popupNavigator.prepare({ popupWindowFeatures, popupWindowTarget, popupSignal });\n    await this._signout({\n      request_type: \"so:p\",\n      post_logout_redirect_uri: url,\n      // we're putting a dummy entry in here because we\n      // need a unique id from the state for notification\n      // to the parent window, which is necessary if we\n      // plan to return back to the client after signout\n      // and so we can close the popup after signout\n      state: url == null ? void 0 : {},\n      ...requestArgs\n    }, handle);\n    logger2.info(\"success\");\n  }\n  /**\n   * Process response (callback) from the end session endpoint from a popup window.\n   * It is recommended to use {@link UserManager.signoutCallback} instead.\n   *\n   * @returns A promise\n   *\n   * @see {@link UserManager.signoutCallback}\n   */\n  async signoutPopupCallback(url = window.location.href, keepOpen = false) {\n    const logger2 = this._logger.create(\"signoutPopupCallback\");\n    await this._popupNavigator.callback(url, { keepOpen });\n    logger2.info(\"success\");\n  }\n  async _signout(args, handle) {\n    const navResponse = await this._signoutStart(args, handle);\n    return await this._signoutEnd(navResponse.url);\n  }\n  async _signoutStart(args = {}, handle) {\n    var _a;\n    const logger2 = this._logger.create(\"_signoutStart\");\n    try {\n      const user = await this._loadUser();\n      logger2.debug(\"loaded current user from storage\");\n      if (this.settings.revokeTokensOnSignout) {\n        await this._revokeInternal(user);\n      }\n      const id_token = args.id_token_hint || user && user.id_token;\n      if (id_token) {\n        logger2.debug(\"setting id_token_hint in signout request\");\n        args.id_token_hint = id_token;\n      }\n      await this.removeUser();\n      logger2.debug(\"user removed, creating signout request\");\n      const signoutRequest = await this._client.createSignoutRequest(args);\n      logger2.debug(\"got signout request\");\n      return await handle.navigate({\n        url: signoutRequest.url,\n        state: (_a = signoutRequest.state) == null ? void 0 : _a.id,\n        scriptOrigin: this.settings.iframeScriptOrigin\n      });\n    } catch (err) {\n      logger2.debug(\"error after preparing navigator, closing navigator window\");\n      handle.close();\n      throw err;\n    }\n  }\n  async _signoutEnd(url) {\n    const logger2 = this._logger.create(\"_signoutEnd\");\n    const signoutResponse = await this._client.processSignoutResponse(url);\n    logger2.debug(\"got signout response\");\n    return signoutResponse;\n  }\n  /**\n   * Trigger a silent request (via an iframe) to the end session endpoint.\n   *\n   * @returns A promise\n   */\n  async signoutSilent(args = {}) {\n    var _a;\n    const logger2 = this._logger.create(\"signoutSilent\");\n    const {\n      silentRequestTimeoutInSeconds,\n      ...requestArgs\n    } = args;\n    const id_token_hint = this.settings.includeIdTokenInSilentSignout ? (_a = await this._loadUser()) == null ? void 0 : _a.id_token : void 0;\n    const url = this.settings.popup_post_logout_redirect_uri;\n    const handle = await this._iframeNavigator.prepare({ silentRequestTimeoutInSeconds });\n    await this._signout({\n      request_type: \"so:s\",\n      post_logout_redirect_uri: url,\n      id_token_hint,\n      ...requestArgs\n    }, handle);\n    logger2.info(\"success\");\n  }\n  /**\n   * Notify the parent window of response (callback) from the end session endpoint.\n   * It is recommended to use {@link UserManager.signoutCallback} instead.\n   *\n   * @returns A promise\n   *\n   * @see {@link UserManager.signoutCallback}\n   */\n  async signoutSilentCallback(url = window.location.href) {\n    const logger2 = this._logger.create(\"signoutSilentCallback\");\n    await this._iframeNavigator.callback(url);\n    logger2.info(\"success\");\n  }\n  async revokeTokens(types) {\n    const user = await this._loadUser();\n    await this._revokeInternal(user, types);\n  }\n  async _revokeInternal(user, types = this.settings.revokeTokenTypes) {\n    const logger2 = this._logger.create(\"_revokeInternal\");\n    if (!user) return;\n    const typesPresent = types.filter((type) => typeof user[type] === \"string\");\n    if (!typesPresent.length) {\n      logger2.debug(\"no need to revoke due to no token(s)\");\n      return;\n    }\n    for (const type of typesPresent) {\n      await this._client.revokeToken(\n        user[type],\n        // eslint-disable-line @typescript-eslint/no-non-null-assertion\n        type\n      );\n      logger2.info(`${type} revoked successfully`);\n      if (type !== \"access_token\") {\n        user[type] = null;\n      }\n    }\n    await this.storeUser(user);\n    logger2.debug(\"user stored\");\n    await this._events.load(user);\n  }\n  /**\n   * Enables silent renew for the `UserManager`.\n   */\n  startSilentRenew() {\n    this._logger.create(\"startSilentRenew\");\n    void this._silentRenewService.start();\n  }\n  /**\n   * Disables silent renew for the `UserManager`.\n   */\n  stopSilentRenew() {\n    this._silentRenewService.stop();\n  }\n  get _userStoreKey() {\n    return `user:${this.settings.authority}:${this.settings.client_id}`;\n  }\n  async _loadUser() {\n    const logger2 = this._logger.create(\"_loadUser\");\n    const storageString = await this.settings.userStore.get(this._userStoreKey);\n    if (storageString) {\n      logger2.debug(\"user storageString loaded\");\n      return User.fromStorageString(storageString);\n    }\n    logger2.debug(\"no user storageString\");\n    return null;\n  }\n  async storeUser(user) {\n    const logger2 = this._logger.create(\"storeUser\");\n    if (user) {\n      logger2.debug(\"storing user\");\n      const storageString = user.toStorageString();\n      await this.settings.userStore.set(this._userStoreKey, storageString);\n    } else {\n      this._logger.debug(\"removing user\");\n      await this.settings.userStore.remove(this._userStoreKey);\n      if (this.settings.dpop) {\n        await this.settings.dpop.store.remove(this.settings.client_id);\n      }\n    }\n  }\n  /**\n   * Removes stale state entries in storage for incomplete authorize requests.\n   */\n  async clearStaleState() {\n    await this._client.clearStaleState();\n  }\n  /**\n   * Dynamically generates a DPoP proof for a given user, URL and optional Http method.\n   * This method is useful when you need to make a request to a resource server\n   * with fetch or similar, and you need to include a DPoP proof in a DPoP header.\n   * @param url - The URL to generate the DPoP proof for\n   * @param user - The user to generate the DPoP proof for\n   * @param httpMethod - Optional, defaults to \"GET\"\n   * @param nonce - Optional nonce provided by the resource server\n   *\n   * @returns A promise containing the DPoP proof or undefined if DPoP is not enabled/no user is found.\n   */\n  async dpopProof(url, user, httpMethod, nonce) {\n    var _a, _b;\n    const dpopState = await ((_b = (_a = this.settings.dpop) == null ? void 0 : _a.store) == null ? void 0 : _b.get(this.settings.client_id));\n    if (dpopState) {\n      return await CryptoUtils.generateDPoPProof({\n        url,\n        accessToken: user == null ? void 0 : user.access_token,\n        httpMethod,\n        keyPair: dpopState.keys,\n        nonce\n      });\n    }\n    return void 0;\n  }\n  async generateDPoPJkt(dpopSettings) {\n    let dpopState = await dpopSettings.store.get(this.settings.client_id);\n    if (!dpopState) {\n      const dpopKeys = await CryptoUtils.generateDPoPKeys();\n      dpopState = new DPoPState(dpopKeys);\n      await dpopSettings.store.set(this.settings.client_id, dpopState);\n    }\n    return await CryptoUtils.generateDPoPJkt(dpopState.keys);\n  }\n};\n\n// package.json\nvar version = \"3.1.0\";\n\n// src/Version.ts\nvar Version = version;\n\n// src/IndexedDbDPoPStore.ts\nvar IndexedDbDPoPStore = class {\n  constructor() {\n    this._dbName = \"oidc\";\n    this._storeName = \"dpop\";\n  }\n  async set(key, value) {\n    const store = await this.createStore(this._dbName, this._storeName);\n    await store(\"readwrite\", (str) => {\n      str.put(value, key);\n      return this.promisifyRequest(str.transaction);\n    });\n  }\n  async get(key) {\n    const store = await this.createStore(this._dbName, this._storeName);\n    return await store(\"readonly\", (str) => {\n      return this.promisifyRequest(str.get(key));\n    });\n  }\n  async remove(key) {\n    const item = await this.get(key);\n    const store = await this.createStore(this._dbName, this._storeName);\n    await store(\"readwrite\", (str) => {\n      return this.promisifyRequest(str.delete(key));\n    });\n    return item;\n  }\n  async getAllKeys() {\n    const store = await this.createStore(this._dbName, this._storeName);\n    return await store(\"readonly\", (str) => {\n      return this.promisifyRequest(str.getAllKeys());\n    });\n  }\n  promisifyRequest(request) {\n    return new Promise((resolve, reject) => {\n      request.oncomplete = request.onsuccess = () => resolve(request.result);\n      request.onabort = request.onerror = () => reject(request.error);\n    });\n  }\n  async createStore(dbName, storeName) {\n    const request = indexedDB.open(dbName);\n    request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n    const db = await this.promisifyRequest(request);\n    return async (txMode, callback) => {\n      const tx = db.transaction(storeName, txMode);\n      const store = tx.objectStore(storeName);\n      return await callback(store);\n    };\n  }\n};\nexport {\n  AccessTokenEvents,\n  CheckSessionIFrame,\n  DPoPState,\n  ErrorResponse,\n  ErrorTimeout,\n  InMemoryWebStorage,\n  IndexedDbDPoPStore,\n  Log,\n  Logger,\n  MetadataService,\n  OidcClient,\n  OidcClientSettingsStore,\n  SessionMonitor,\n  SigninResponse,\n  SigninState,\n  SignoutResponse,\n  State,\n  User,\n  UserManager,\n  UserManagerSettingsStore,\n  Version,\n  WebStorageStateStore\n};\n//# sourceMappingURL=oidc-client-ts.js.map\n","/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Errors expected to be encountered during OIDC discovery, client registration, and authentication.\n * Not intended to be displayed directly to the user.\n */\nexport var OidcError = /*#__PURE__*/function (OidcError) {\n  OidcError[\"NotSupported\"] = \"OIDC authentication not supported\";\n  OidcError[\"Misconfigured\"] = \"OIDC is misconfigured\";\n  OidcError[\"General\"] = \"Something went wrong with OIDC discovery\";\n  OidcError[\"OpSupport\"] = \"Configured OIDC OP does not support required functions\";\n  OidcError[\"DynamicRegistrationNotSupported\"] = \"Dynamic registration not supported\";\n  OidcError[\"DynamicRegistrationFailed\"] = \"Dynamic registration failed\";\n  OidcError[\"DynamicRegistrationInvalid\"] = \"Dynamic registration invalid response\";\n  OidcError[\"CodeExchangeFailed\"] = \"Failed to exchange code for token\";\n  OidcError[\"InvalidBearerTokenResponse\"] = \"Invalid bearer token response\";\n  OidcError[\"InvalidIdToken\"] = \"Invalid ID token\";\n  OidcError[\"MissingOrInvalidStoredState\"] = \"State required to finish logging in is not found in storage.\";\n  return OidcError;\n}({});\n//# sourceMappingURL=error.js.map","/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { jwtDecode } from \"jwt-decode\";\nimport { logger } from \"../logger.js\";\nimport { OidcError } from \"./error.js\";\nimport { OAuthGrantType } from \"./index.js\";\n\n/**\n * Metadata from OAuth 2.0 client authentication API as per\n * https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata\n * With validated properties required in type\n */\n\nvar isRecord = value => !!value && typeof value === \"object\" && !Array.isArray(value);\nvar requiredStringProperty = (wellKnown, key) => {\n  if (!wellKnown[key] || !optionalStringProperty(wellKnown, key)) {\n    logger.error(\"Missing or invalid property: \".concat(key));\n    return false;\n  }\n  return true;\n};\nvar optionalStringProperty = (wellKnown, key) => {\n  if (!!wellKnown[key] && typeof wellKnown[key] !== \"string\") {\n    logger.error(\"Invalid property: \".concat(key));\n    return false;\n  }\n  return true;\n};\nvar optionalStringArrayProperty = (wellKnown, key) => {\n  if (!!wellKnown[key] && (!Array.isArray(wellKnown[key]) || !wellKnown[key].every(v => typeof v === \"string\"))) {\n    logger.error(\"Invalid property: \".concat(key));\n    return false;\n  }\n  return true;\n};\nvar requiredArrayValue = (wellKnown, key, value) => {\n  var array = wellKnown[key];\n  if (!array || !Array.isArray(array) || !array.includes(value)) {\n    logger.error(\"Invalid property: \".concat(key, \". \").concat(value, \" is required.\"));\n    return false;\n  }\n  return true;\n};\n\n/**\n * Validates OAuth 2.0 auth metadata as defined by\n * https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata\n * is compatible with Element's OAuth/OIDC flow\n * @param authMetadata - json object\n * @returns valid issuer config\n * @throws Error - when issuer config is not found or is invalid\n */\nexport var validateAuthMetadata = authMetadata => {\n  if (!isRecord(authMetadata)) {\n    logger.error(\"Issuer configuration not found or malformed\");\n    throw new Error(OidcError.OpSupport);\n  }\n  var isInvalid = [requiredStringProperty(authMetadata, \"issuer\"), requiredStringProperty(authMetadata, \"authorization_endpoint\"), requiredStringProperty(authMetadata, \"token_endpoint\"), requiredStringProperty(authMetadata, \"revocation_endpoint\"), optionalStringProperty(authMetadata, \"registration_endpoint\"), optionalStringProperty(authMetadata, \"account_management_uri\"), optionalStringProperty(authMetadata, \"device_authorization_endpoint\"), optionalStringArrayProperty(authMetadata, \"account_management_actions_supported\"), requiredArrayValue(authMetadata, \"response_types_supported\", \"code\"), requiredArrayValue(authMetadata, \"grant_types_supported\", OAuthGrantType.AuthorizationCode), requiredArrayValue(authMetadata, \"code_challenge_methods_supported\", \"S256\"), optionalStringArrayProperty(authMetadata, \"prompt_values_supported\")].some(isValid => !isValid);\n  if (!isInvalid) {\n    return authMetadata;\n  }\n  logger.error(\"Issuer configuration not valid\");\n  throw new Error(OidcError.OpSupport);\n};\nexport var decodeIdToken = token => {\n  try {\n    return jwtDecode(token);\n  } catch (error) {\n    logger.error(\"Could not decode id_token\", error);\n    throw error;\n  }\n};\n\n/**\n * Validate idToken\n * https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation\n * @param idToken - id token from token endpoint\n * @param issuer - issuer for the OP as found during discovery\n * @param clientId - this client's id as registered with the OP\n * @param nonce - nonce used in the authentication request\n * @throws when id token is invalid\n */\nexport var validateIdToken = (idToken, issuer, clientId, nonce) => {\n  try {\n    if (!idToken) {\n      throw new Error(\"No ID token\");\n    }\n    var claims = decodeIdToken(idToken);\n\n    // The Issuer Identifier for the OpenID Provider MUST exactly match the value of the iss (issuer) Claim.\n    if (claims.iss !== issuer) {\n      throw new Error(\"Invalid issuer\");\n    }\n    /**\n     * The Client MUST validate that the aud (audience) Claim contains its client_id value registered at the Issuer identified by the iss (issuer) Claim as an audience.\n     * The aud (audience) Claim MAY contain an array with more than one element.\n     * The ID Token MUST be rejected if the ID Token does not list the Client as a valid audience, or if it contains additional audiences not trusted by the Client.\n     * EW: Don't accept tokens with other untrusted audiences\n     * */\n    var sanitisedAuds = typeof claims.aud === \"string\" ? [claims.aud] : claims.aud;\n    if (!sanitisedAuds.includes(clientId)) {\n      throw new Error(\"Invalid audience\");\n    }\n\n    /**\n     * If a nonce value was sent in the Authentication Request, a nonce Claim MUST be present and its value checked\n     * to verify that it is the same value as the one that was sent in the Authentication Request.\n     */\n    if (nonce !== undefined && claims.nonce !== nonce) {\n      throw new Error(\"Invalid nonce\");\n    }\n\n    /**\n     * The current time MUST be before the time represented by the exp Claim.\n     *  exp is an epoch timestamp in seconds\n     * */\n    if (!claims.exp || Date.now() > claims.exp * 1000) {\n      throw new Error(\"Invalid expiry\");\n    }\n  } catch (error) {\n    logger.error(\"Invalid ID token\", error);\n    throw new Error(OidcError.InvalidIdToken);\n  }\n};\n\n/**\n * State we ask OidcClient to store when starting oidc authorization flow (in `generateOidcAuthorizationUrl`)\n * so that we can access it on return from the OP and complete login\n */\n\n/**\n * Validate stored user state exists and is valid\n * @param userState - userState returned by oidcClient.processSigninResponse\n * @throws when userState is invalid\n */\nexport function validateStoredUserState(userState) {\n  if (!isRecord(userState)) {\n    logger.error(\"Stored user state not found\");\n    throw new Error(OidcError.MissingOrInvalidStoredState);\n  }\n  var isInvalid = [requiredStringProperty(userState, \"homeserverUrl\"), requiredStringProperty(userState, \"nonce\"), optionalStringProperty(userState, \"identityServerUrl\")].some(isValid => !isValid);\n  if (isInvalid) {\n    throw new Error(OidcError.MissingOrInvalidStoredState);\n  }\n}\n\n/**\n * The expected response type from the token endpoint during authorization code flow\n * Normalized to always use capitalized 'Bearer' for token_type\n *\n * See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4,\n * https://openid.net/specs/openid-connect-basic-1_0.html#TokenOK.\n */\n\n/**\n * Make required properties required in type\n */\n\nvar isValidBearerTokenResponse = response => isRecord(response) && requiredStringProperty(response, \"token_type\") &&\n// token_type is case insensitive, some OPs return `token_type: \"bearer\"`\nresponse[\"token_type\"].toLowerCase() === \"bearer\" && requiredStringProperty(response, \"access_token\") && requiredStringProperty(response, \"refresh_token\") && (!(\"expires_in\" in response) || typeof response[\"expires_in\"] === \"number\");\nexport function validateBearerTokenResponse(response) {\n  if (!isValidBearerTokenResponse(response)) {\n    throw new Error(OidcError.InvalidBearerTokenResponse);\n  }\n}\n//# sourceMappingURL=validate.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nimport _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MetadataService, OidcClientSettingsStore } from \"oidc-client-ts\";\nimport { validateAuthMetadata } from \"./validate.js\";\nimport { Method, timeoutSignal } from \"../http-api/index.js\";\n/**\n * @experimental\n * Discover and validate delegated auth configuration\n * - delegated auth issuer openid-configuration is reachable\n * - delegated auth issuer openid-configuration is configured correctly for us\n * Fetches https://oidc-issuer.example.com/.well-known/openid-configuration and other files linked therein.\n * When successful, validated metadata is returned\n * @param issuer - the OIDC issuer as returned by the /auth_issuer API\n * @returns validated authentication metadata and optionally signing keys\n * @throws when delegated auth config is invalid or unreachable\n * @deprecated in favour of {@link MatrixClient#getAuthMetadata}\n */\nexport var discoverAndValidateOIDCIssuerWellKnown = /*#__PURE__*/function () {\n  var _ref = _asyncToGenerator(function* (issuer) {\n    var issuerOpenIdConfigUrl = new URL(\".well-known/openid-configuration\", issuer);\n    var issuerWellKnownResponse = yield fetch(issuerOpenIdConfigUrl, {\n      method: Method.Get,\n      signal: timeoutSignal(5000)\n    });\n    var issuerWellKnown = yield issuerWellKnownResponse.json();\n    return validateAuthMetadataAndKeys(issuerWellKnown);\n  });\n  return function discoverAndValidateOIDCIssuerWellKnown(_x) {\n    return _ref.apply(this, arguments);\n  };\n}();\n\n/**\n * @experimental\n * Validate the authentication metadata and fetch the signing keys from the jwks_uri in the metadata\n * @param authMetadata - the authentication metadata to validate\n * @returns validated authentication metadata and signing keys\n */\nexport var validateAuthMetadataAndKeys = /*#__PURE__*/function () {\n  var _ref2 = _asyncToGenerator(function* (authMetadata) {\n    var validatedIssuerConfig = validateAuthMetadata(authMetadata);\n\n    // create a temporary settings store, so we can use metadata service for discovery\n    var settings = new OidcClientSettingsStore({\n      authority: validatedIssuerConfig.issuer,\n      metadata: validatedIssuerConfig,\n      redirect_uri: \"\",\n      // Not known yet, this is here to make the type checker happy\n      client_id: \"\" // Not known yet, this is here to make the type checker happy\n    });\n    var metadataService = new MetadataService(settings);\n    return _objectSpread(_objectSpread({}, validatedIssuerConfig), {}, {\n      signingKeys: yield metadataService.getSigningKeys()\n    });\n  });\n  return function validateAuthMetadataAndKeys(_x2) {\n    return _ref2.apply(this, arguments);\n  };\n}();\n//# sourceMappingURL=discovery.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { OidcError } from \"./error.js\";\nimport { Method } from \"../http-api/index.js\";\nimport { logger } from \"../logger.js\";\n\n/**\n * Client metadata passed to registration endpoint\n */\n\n/**\n * Request body for dynamic registration as defined by https://github.com/matrix-org/matrix-spec-proposals/pull/2966\n */\n\n/**\n * The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types\n */\nexport var OAuthGrantType = /*#__PURE__*/function (OAuthGrantType) {\n  /**\n   * See https://spec.matrix.org/v1.17/client-server-api/#authorization-code-grant\n   */\n  OAuthGrantType[\"AuthorizationCode\"] = \"authorization_code\";\n  /**\n   * https://spec.matrix.org/v1.17/client-server-api/#refresh-token-grant\n   */\n  OAuthGrantType[\"RefreshToken\"] = \"refresh_token\";\n  /**\n   * The OAuth 2.0 Device Authorization Grant type identifier as per\n   * https://www.rfc-editor.org/rfc/rfc8628.html#section-7.2 from\n   * [MSC4341](https://github.com/matrix-org/matrix-spec-proposals/pull/4341).\n   *\n   * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n   */\n  OAuthGrantType[\"DeviceAuthorization\"] = \"urn:ietf:params:oauth:grant-type:device_code\";\n  return OAuthGrantType;\n}({});\n\n/**\n * The name \"scope\" is a misnomer here as it is actually a \"grant type\".\n *\n * @deprecated use `OAuthGrantType.DeviceAuthorization` instead\n */\nexport var DEVICE_CODE_SCOPE = OAuthGrantType.DeviceAuthorization;\n\n// Check that URIs have a common base, as per the MSC2966 definition\nvar urlHasCommonBase = (base, urlStr) => {\n  if (!urlStr) return false;\n  var url = new URL(urlStr);\n  if (url.protocol !== base.protocol) return false;\n  if (url.hostname !== base.hostname && !url.hostname.endsWith(\".\".concat(base.hostname))) return false;\n  return true;\n};\n\n/**\n * Attempts dynamic registration against the configured registration endpoint.\n * Will ignore any URIs that do not use client_uri as a common base as per the spec.\n * @param delegatedAuthConfig - Auth config from {@link discoverAndValidateOIDCIssuerWellKnown}\n * @param clientMetadata - The metadata for the client which to register\n * @returns Promise<string> resolved with registered clientId\n * @throws when registration is not supported, on failed request or invalid response\n */\nexport var registerOidcClient = /*#__PURE__*/function () {\n  var _ref = _asyncToGenerator(function* (delegatedAuthConfig, clientMetadata) {\n    if (!delegatedAuthConfig.registration_endpoint) {\n      throw new Error(OidcError.DynamicRegistrationNotSupported);\n    }\n    var grantTypes = [OAuthGrantType.AuthorizationCode, OAuthGrantType.RefreshToken];\n    if (grantTypes.some(scope => !delegatedAuthConfig.grant_types_supported.includes(scope))) {\n      throw new Error(OidcError.DynamicRegistrationNotSupported);\n    }\n    var commonBase = new URL(clientMetadata.clientUri);\n\n    // https://openid.net/specs/openid-connect-registration-1_0.html\n    var metadata = {\n      client_name: clientMetadata.clientName,\n      client_uri: clientMetadata.clientUri,\n      response_types: [\"code\"],\n      grant_types: grantTypes,\n      redirect_uris: clientMetadata.redirectUris,\n      id_token_signed_response_alg: \"RS256\",\n      token_endpoint_auth_method: \"none\",\n      application_type: clientMetadata.applicationType,\n      contacts: clientMetadata.contacts,\n      logo_uri: urlHasCommonBase(commonBase, clientMetadata.logoUri) ? clientMetadata.logoUri : undefined,\n      policy_uri: urlHasCommonBase(commonBase, clientMetadata.policyUri) ? clientMetadata.policyUri : undefined,\n      tos_uri: urlHasCommonBase(commonBase, clientMetadata.tosUri) ? clientMetadata.tosUri : undefined\n    };\n    var headers = {\n      \"Accept\": \"application/json\",\n      \"Content-Type\": \"application/json\"\n    };\n    try {\n      var response = yield fetch(delegatedAuthConfig.registration_endpoint, {\n        method: Method.Post,\n        headers,\n        body: JSON.stringify(metadata)\n      });\n      if (response.status >= 400) {\n        throw new Error(OidcError.DynamicRegistrationFailed);\n      }\n      var body = yield response.json();\n      var clientId = body[\"client_id\"];\n      if (!clientId || typeof clientId !== \"string\") {\n        throw new Error(OidcError.DynamicRegistrationInvalid);\n      }\n      return clientId;\n    } catch (error) {\n      if (Object.values(OidcError).includes(error.message)) {\n        throw error;\n      } else {\n        logger.error(\"Dynamic registration request failed\", error);\n        throw new Error(OidcError.DynamicRegistrationFailed);\n      }\n    }\n  });\n  return function registerOidcClient(_x, _x2) {\n    return _ref.apply(this, arguments);\n  };\n}();\n//# sourceMappingURL=register.js.map","import _objectWithoutProperties from \"@babel/runtime/helpers/objectWithoutProperties\";\nimport _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nvar _excluded = [\"server\", \"limit\", \"since\"];\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2015-2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixClient} for the public class.\n */\n\nimport { SyncApi, SyncState } from \"./sync.js\";\nimport { EventStatus, MatrixEvent, MatrixEventEvent } from \"./models/event.js\";\nimport { StubStore } from \"./store/stub.js\";\nimport { createNewMatrixCall, supportsMatrixCall } from \"./webrtc/call.js\";\nimport { Filter } from \"./filter.js\";\nimport { CallEventHandler } from \"./webrtc/callEventHandler.js\";\nimport { GroupCallEventHandler } from \"./webrtc/groupCallEventHandler.js\";\nimport * as utils from \"./utils.js\";\nimport { deepCompare, noUnsafeEventProps, replaceParam, safeSet, sleep } from \"./utils.js\";\nimport { Direction, EventTimeline } from \"./models/event-timeline.js\";\nimport { PushProcessor } from \"./pushprocessor.js\";\nimport { AutoDiscovery } from \"./autodiscovery.js\";\nimport { encodeUnpaddedBase64Url } from \"./base64.js\";\nimport { TypedReEmitter } from \"./ReEmitter.js\";\nimport { logger } from \"./logger.js\";\nimport { SERVICE_TYPES } from \"./service-types.js\";\nimport { ClientPrefix, IdentityPrefix, MatrixError, MatrixHttpApi, MediaPrefix, Method, retryNetworkOperation } from \"./http-api/index.js\";\nimport { User, UserEvent } from \"./models/user.js\";\nimport { getHttpUriForMxc } from \"./content-repo.js\";\nimport { SearchResult } from \"./models/search-result.js\";\nimport * as ContentHelpers from \"./content-helpers.js\";\nimport { NotificationCountType } from \"./models/room.js\";\nimport { RoomMemberEvent } from \"./models/room-member.js\";\nimport { isSendDelayedEventRequestOpts, UpdateDelayedEventAction } from \"./@types/requests.js\";\nimport { EventType, LOCAL_NOTIFICATION_SETTINGS_PREFIX, MSC3912_RELATION_BASED_REDACTIONS_PROP, MsgType, PUSHER_ENABLED, RelationType, RoomCreateTypeField, RoomType, UNSTABLE_MSC3088_ENABLED, UNSTABLE_MSC3088_PURPOSE, UNSTABLE_MSC3089_TREE_SUBTYPE } from \"./@types/event.js\";\nimport { GuestAccess, HistoryVisibility, Preset } from \"./@types/partials.js\";\nimport { eventMapperFor } from \"./event-mapper.js\";\nimport { secureRandomString } from \"./randomstring.js\";\nimport { DEFAULT_TREE_POWER_LEVELS_TEMPLATE, MSC3089TreeSpace } from \"./models/MSC3089TreeSpace.js\";\nimport { SearchOrderBy } from \"./@types/search.js\";\nimport { PushRuleActionName, PushRuleKind } from \"./@types/PushRules.js\";\nimport { GroupCall } from \"./webrtc/groupCall.js\";\nimport { MediaHandler } from \"./webrtc/mediaHandler.js\";\nimport { TypedEventEmitter } from \"./models/typed-event-emitter.js\";\nimport { MAIN_ROOM_TIMELINE, ReceiptType } from \"./@types/read_receipts.js\";\nimport { SlidingSyncSdk } from \"./sliding-sync-sdk.js\";\nimport { determineFeatureSupport, FeatureSupport, Thread, THREAD_RELATION_TYPE, ThreadFilterType, threadFilterTypeToFilter } from \"./models/thread.js\";\nimport { M_BEACON_INFO } from \"./@types/beacon.js\";\nimport { NamespacedValue, UnstableValue } from \"./NamespacedValue.js\";\nimport { ToDeviceMessageQueue } from \"./ToDeviceMessageQueue.js\";\nimport { IgnoredInvites } from \"./models/invites-ignorer.js\";\nimport { buildFeatureSupportMap, Feature, ServerSupport } from \"./feature.js\";\nimport { RUST_SDK_STORE_PREFIX } from \"./rust-crypto/constants.js\";\nimport { CryptoEvent } from \"./crypto-api/index.js\";\nimport { ServerSideSecretStorageImpl } from \"./secret-storage.js\";\nimport { MatrixRTCSessionManager } from \"./matrixrtc/MatrixRTCSessionManager.js\";\nimport { getRelationsThreadFilter } from \"./thread-utils.js\";\nimport { KnownMembership } from \"./@types/membership.js\";\nimport { ServerCapabilities } from \"./serverCapabilities.js\";\nimport { sha256 } from \"./digest.js\";\nimport { discoverAndValidateOIDCIssuerWellKnown, validateAuthMetadataAndKeys } from \"./oidc/index.js\";\nimport { UnsupportedDelayedEventsEndpointError, UnsupportedStickyEventsEndpointError } from \"./errors.js\";\nvar SCROLLBACK_DELAY_MS = 3000;\nvar TURN_CHECK_INTERVAL = 10 * 60 * 1000; // poll for turn credentials every 10 minutes\n\nexport var UNSTABLE_MSC3852_LAST_SEEN_UA = new UnstableValue(\"last_seen_user_agent\", \"org.matrix.msc3852.last_seen_user_agent\");\nexport var PendingEventOrdering = /*#__PURE__*/function (PendingEventOrdering) {\n  PendingEventOrdering[\"Chronological\"] = \"chronological\";\n  PendingEventOrdering[\"Detached\"] = \"detached\";\n  return PendingEventOrdering;\n}({});\nexport var GET_LOGIN_TOKEN_CAPABILITY = new NamespacedValue(\"m.get_login_token\", \"org.matrix.msc3882.get_login_token\");\nexport var UNSTABLE_MSC2666_SHARED_ROOMS = \"uk.half-shot.msc2666\";\nexport var UNSTABLE_MSC2666_MUTUAL_ROOMS = \"uk.half-shot.msc2666.mutual_rooms\";\nexport var UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS = \"uk.half-shot.msc2666.query_mutual_rooms\";\nexport var UNSTABLE_MSC4140_DELAYED_EVENTS = \"org.matrix.msc4140\";\nexport var UNSTABLE_MSC4354_STICKY_EVENTS = \"org.matrix.msc4354\";\nexport var UNSTABLE_MSC4133_EXTENDED_PROFILES = \"uk.tcpip.msc4133\";\nexport var STABLE_MSC4133_EXTENDED_PROFILES = \"uk.tcpip.msc4133.stable\";\nvar CrossSigningKeyType = /*#__PURE__*/function (CrossSigningKeyType) {\n  CrossSigningKeyType[\"MasterKey\"] = \"master_key\";\n  CrossSigningKeyType[\"SelfSigningKey\"] = \"self_signing_key\";\n  CrossSigningKeyType[\"UserSigningKey\"] = \"user_signing_key\";\n  return CrossSigningKeyType;\n}(CrossSigningKeyType || {}); // Re-export for backwards compatibility\n/**\n * The summary of a room as defined by an initial version of MSC3266 and implemented in Synapse\n * Proposed at https://github.com/matrix-org/matrix-doc/pull/3266\n */\n/* eslint-enable camelcase */\n\n// We're using this constant for methods overloading and inspect whether a variable\n// contains an eventId or not. This was required to ensure backwards compatibility\n// of methods for threads\n// Probably not the most graceful solution but does a good enough job for now\nvar EVENT_ID_PREFIX = \"$\";\nexport var ClientEvent = /*#__PURE__*/function (ClientEvent) {\n  /**\n   * Fires whenever the SDK's syncing state is updated. The state can be one of:\n   * <ul>\n   *\n   * <li>PREPARED: The client has synced with the server at least once and is\n   * ready for methods to be called on it. This will be immediately followed by\n   * a state of SYNCING. <i>This is the equivalent of \"syncComplete\" in the\n   * previous API.</i></li>\n   *\n   * <li>CATCHUP: The client has detected the connection to the server might be\n   * available again and will now try to do a sync again. As this sync might take\n   * a long time (depending how long ago was last synced, and general server\n   * performance) the client is put in this mode so the UI can reflect trying\n   * to catch up with the server after losing connection.</li>\n   *\n   * <li>SYNCING : The client is currently polling for new events from the server.\n   * This will be called <i>after</i> processing latest events from a sync.</li>\n   *\n   * <li>ERROR : The client has had a problem syncing with the server. If this is\n   * called <i>before</i> PREPARED then there was a problem performing the initial\n   * sync. If this is called <i>after</i> PREPARED then there was a problem polling\n   * the server for updates. This may be called multiple times even if the state is\n   * already ERROR. <i>This is the equivalent of \"syncError\" in the previous\n   * API.</i></li>\n   *\n   * <li>RECONNECTING: The sync connection has dropped, but not (yet) in a way that\n   * should be considered erroneous.\n   * </li>\n   *\n   * <li>STOPPED: The client has stopped syncing with server due to stopClient\n   * being called.\n   * </li>\n   * </ul>\n   * State transition diagram:\n   * ```\n   *                                          +---->STOPPED\n   *                                          |\n   *              +----->PREPARED -------> SYNCING <--+\n   *              |                        ^  |  ^    |\n   *              |      CATCHUP ----------+  |  |    |\n   *              |        ^                  V  |    |\n   *   null ------+        |  +------- RECONNECTING   |\n   *              |        V  V                       |\n   *              +------->ERROR ---------------------+\n   *\n   * NB: 'null' will never be emitted by this event.\n   *\n   * ```\n   * Transitions:\n   * <ul>\n   *\n   * <li>`null -> PREPARED` : Occurs when the initial sync is completed\n   * first time. This involves setting up filters and obtaining push rules.\n   *\n   * <li>`null -> ERROR` : Occurs when the initial sync failed first time.\n   *\n   * <li>`ERROR -> PREPARED` : Occurs when the initial sync succeeds\n   * after previously failing.\n   *\n   * <li>`PREPARED -> SYNCING` : Occurs immediately after transitioning\n   * to PREPARED. Starts listening for live updates rather than catching up.\n   *\n   * <li>`SYNCING -> RECONNECTING` : Occurs when the live update fails.\n   *\n   * <li>`RECONNECTING -> RECONNECTING` : Can occur if the update calls\n   * continue to fail, but the keepalive calls (to /versions) succeed.\n   *\n   * <li>`RECONNECTING -> ERROR` : Occurs when the keepalive call also fails\n   *\n   * <li>`ERROR -> SYNCING` : Occurs when the client has performed a\n   * live update after having previously failed.\n   *\n   * <li>`ERROR -> ERROR` : Occurs when the client has failed to keepalive\n   * for a second time or more.</li>\n   *\n   * <li>`SYNCING -> SYNCING` : Occurs when the client has performed a live\n   * update. This is called <i>after</i> processing.</li>\n   *\n   * <li>`* -> STOPPED` : Occurs once the client has stopped syncing or\n   * trying to sync after stopClient has been called.</li>\n   * </ul>\n   *\n   * The payloads consits of the following 3 parameters:\n   *\n   * - state - An enum representing the syncing state. One of \"PREPARED\",\n   * \"SYNCING\", \"ERROR\", \"STOPPED\".\n   *\n   * - prevState - An enum representing the previous syncing state.\n   * One of \"PREPARED\", \"SYNCING\", \"ERROR\", \"STOPPED\" <b>or null</b>.\n   *\n   * - data - Data about this transition.\n   *\n   * @example\n   * ```\n   * matrixClient.on(\"sync\", function(state, prevState, data) {\n   *   switch (state) {\n   *     case \"ERROR\":\n   *       // update UI to say \"Connection Lost\"\n   *       break;\n   *     case \"SYNCING\":\n   *       // update UI to remove any \"Connection Lost\" message\n   *       break;\n   *     case \"PREPARED\":\n   *       // the client instance is ready to be queried.\n   *       var rooms = matrixClient.getRooms();\n   *       break;\n   *   }\n   * });\n   * ```\n   */\n  ClientEvent[\"Sync\"] = \"sync\";\n  /**\n   * Fires whenever the SDK receives a new event.\n   * <p>\n   * This is only fired for live events received via /sync - it is not fired for\n   * events received over context, search, or pagination APIs.\n   *\n   * The payload is the matrix event which caused this event to fire.\n   * @example\n   * ```\n   * matrixClient.on(\"event\", function(event){\n   *   var sender = event.getSender();\n   * });\n   * ```\n   */\n  ClientEvent[\"Event\"] = \"event\";\n  /** @deprecated Use {@link ReceivedToDeviceMessage}.\n   * Fires whenever the SDK receives a new to-device event.\n   * The payload is the matrix event ({@link MatrixEvent}) which caused this event to fire.\n   * @example\n   * ```\n   * matrixClient.on(\"toDeviceEvent\", function(event){\n   *   var sender = event.getSender();\n   * });\n   * ```\n   */\n  ClientEvent[\"ToDeviceEvent\"] = \"toDeviceEvent\";\n  /**\n   * Fires whenever the SDK receives a new (potentially decrypted) to-device message.\n   * The payload is the to-device message and the encryption info for that message ({@link ReceivedToDeviceMessage}).\n   * @example\n   * ```\n   * matrixClient.on(\"receivedToDeviceMessage\", function(payload){\n   *   const { message, encryptionInfo } = payload;\n   *   var claimed_sender = encryptionInfo ? encryptionInfo.sender : message.sender;\n   *   var isVerified = encryptionInfo ? encryptionInfo.verified : false;\n   *   var type = message.type;\n   * });\n   */\n  ClientEvent[\"ReceivedToDeviceMessage\"] = \"receivedToDeviceMessage\";\n  /**\n   * Fires whenever new user-scoped account_data is added.\n   * The payload is a pair of event ({@link MatrixEvent}) describing the account_data just added, and the previous event, if known:\n   *  - event: The event describing the account_data just added\n   *  - oldEvent: The previous account data, if known.\n   * @example\n   * ```\n   * matrixClient.on(\"accountData\", function(event, oldEvent){\n   *   myAccountData[event.type] = event.content;\n   * });\n   * ```\n   */\n  ClientEvent[\"AccountData\"] = \"accountData\";\n  /**\n   * Fires whenever a new Room is added. This will fire when you are invited to a\n   * room, as well as when you join a room. <strong>This event is experimental and\n   * may change.</strong>\n   *\n   * The payload is the newly created room, fully populated.\n   * @example\n   * ```\n   * matrixClient.on(\"Room\", function(room){\n   *   var roomId = room.roomId;\n   * });\n   * ```\n   */\n  ClientEvent[\"Room\"] = \"Room\";\n  /**\n   * Fires whenever a Room is removed. This will fire when you forget a room.\n   * <strong>This event is experimental and may change.</strong>\n   * The payload is the roomId of the deleted room.\n   * @example\n   * ```\n   * matrixClient.on(\"deleteRoom\", function(roomId){\n   *   // update UI from getRooms()\n   * });\n   * ```\n   */\n  ClientEvent[\"DeleteRoom\"] = \"deleteRoom\";\n  ClientEvent[\"SyncUnexpectedError\"] = \"sync.unexpectedError\";\n  /**\n   * Fires when the client .well-known info is fetched.\n   * The payload is the JSON object (see {@link IClientWellKnown}) returned by the server\n   */\n  ClientEvent[\"ClientWellKnown\"] = \"WellKnown.client\";\n  ClientEvent[\"ReceivedVoipEvent\"] = \"received_voip_event\";\n  ClientEvent[\"TurnServers\"] = \"turnServers\";\n  ClientEvent[\"TurnServersError\"] = \"turnServers.error\";\n  return ClientEvent;\n}({});\nvar SSO_ACTION_PARAM = new UnstableValue(\"action\", \"org.matrix.msc3824.action\");\n\n/**\n * Represents a Matrix Client. Only directly construct this if you want to use\n * custom modules. Normally, {@link createClient} should be used\n * as it specifies 'sensible' defaults for these modules.\n */\nexport class MatrixClient extends TypedEventEmitter {\n  constructor(opts) {\n    var _opts$logger, _opts$usingExternalCr, _this, _opts$disableVoip, _opts$enableEncrypted, _opts$cryptoCallbacks;\n    // If a custom logger is provided, use it. Otherwise, default to the global\n    // one in logger.ts.\n    super();\n    _this = this;\n    _defineProperty(this, \"logger\", void 0);\n    _defineProperty(this, \"reEmitter\", new TypedReEmitter(this));\n    _defineProperty(this, \"olmVersion\", null);\n    // populated after initLegacyCrypto\n    _defineProperty(this, \"usingExternalCrypto\", false);\n    _defineProperty(this, \"_store\", void 0);\n    _defineProperty(this, \"deviceId\", void 0);\n    _defineProperty(this, \"credentials\", void 0);\n    /**\n     * Encryption key used for encrypting sensitive data (such as e2ee keys) in storage.\n     *\n     * As supplied in the constructor via {@link IMatrixClientCreateOpts#pickleKey}.\n     * Used for migration from the legacy crypto to the rust crypto\n     */\n    _defineProperty(this, \"legacyPickleKey\", void 0);\n    _defineProperty(this, \"scheduler\", void 0);\n    _defineProperty(this, \"clientRunning\", false);\n    _defineProperty(this, \"timelineSupport\", false);\n    _defineProperty(this, \"urlPreviewCache\", {});\n    _defineProperty(this, \"identityServer\", void 0);\n    _defineProperty(this, \"http\", void 0);\n    // XXX: Intended private, used in code.\n    _defineProperty(this, \"cryptoBackend\", void 0);\n    // one of crypto or rustCrypto\n    /**\n     * Support MSC4362: Simplified Encrypted State Events.\n     *\n     * The client must be recreated for changes to this setting to take effect\n     * reliably.\n     *\n     * When this setting is true, if we find a state event that is encrypted\n     * (within a room that supports encrypted state), we will attempt to decrypt\n     * it as specified in MSC4362. If the user was in the room at the time an\n     * encrypted state event was received (meaning we have the key), even if\n     * this setting was set to false at the time it was received, recreating the\n     * client with this setting set to true will allow decrypting that event.\n     *\n     * When this setting is false, any state event that is encrypted will not be\n     * decrypted, meaning it will have no effect. This matched the behaviour of\n     * a client that does not support MSC4362.\n     */\n    _defineProperty(this, \"enableEncryptedStateEvents\", void 0);\n    _defineProperty(this, \"cryptoCallbacks\", void 0);\n    // XXX: Intended private, used in code.\n    _defineProperty(this, \"callEventHandler\", void 0);\n    // XXX: Intended private, used in code.\n    _defineProperty(this, \"groupCallEventHandler\", void 0);\n    _defineProperty(this, \"supportsCallTransfer\", false);\n    // XXX: Intended private, used in code.\n    _defineProperty(this, \"forceTURN\", false);\n    // XXX: Intended private, used in code.\n    _defineProperty(this, \"iceCandidatePoolSize\", 0);\n    // XXX: Intended private, used in code.\n    _defineProperty(this, \"idBaseUrl\", void 0);\n    _defineProperty(this, \"baseUrl\", void 0);\n    _defineProperty(this, \"isVoipWithNoMediaAllowed\", void 0);\n    _defineProperty(this, \"disableVoip\", void 0);\n    _defineProperty(this, \"useLivekitForGroupCalls\", void 0);\n    // Note: these are all `protected` to let downstream consumers make mistakes if they want to.\n    // We don't technically support this usage, but have reasons to do this.\n    _defineProperty(this, \"canSupportVoip\", false);\n    _defineProperty(this, \"peekSync\", null);\n    _defineProperty(this, \"isGuestAccount\", false);\n    _defineProperty(this, \"ongoingScrollbacks\", {});\n    _defineProperty(this, \"notifTimelineSet\", null);\n    /**\n     * Legacy crypto store used for migration from the legacy crypto to the rust crypto\n     * @private\n     */\n    _defineProperty(this, \"legacyCryptoStore\", void 0);\n    _defineProperty(this, \"verificationMethods\", void 0);\n    _defineProperty(this, \"fallbackICEServerAllowed\", false);\n    _defineProperty(this, \"syncApi\", void 0);\n    _defineProperty(this, \"roomNameGenerator\", void 0);\n    _defineProperty(this, \"pushRules\", void 0);\n    _defineProperty(this, \"syncLeftRoomsPromise\", void 0);\n    _defineProperty(this, \"syncedLeftRooms\", false);\n    _defineProperty(this, \"clientOpts\", void 0);\n    _defineProperty(this, \"clientWellKnownIntervalID\", void 0);\n    _defineProperty(this, \"canResetTimelineCallback\", void 0);\n    _defineProperty(this, \"canSupport\", new Map());\n    // The pushprocessor caches useful things, so keep one and re-use it\n    _defineProperty(this, \"pushProcessor\", new PushProcessor(this));\n    // Promise to a response of the server's /versions response\n    // TODO: This should expire: https://github.com/matrix-org/matrix-js-sdk/issues/1020\n    _defineProperty(this, \"serverVersionsPromise\", void 0);\n    _defineProperty(this, \"clientWellKnown\", void 0);\n    _defineProperty(this, \"clientWellKnownPromise\", void 0);\n    _defineProperty(this, \"turnServers\", []);\n    _defineProperty(this, \"turnServersExpiry\", 0);\n    _defineProperty(this, \"checkTurnServersIntervalID\", void 0);\n    _defineProperty(this, \"txnCtr\", 0);\n    _defineProperty(this, \"mediaHandler\", new MediaHandler(this));\n    _defineProperty(this, \"sessionId\", void 0);\n    /** IDs of events which are currently being encrypted.\n     *\n     * This is part of the cancellation mechanism: if the event is no longer listed here when encryption completes,\n     * that tells us that it has been cancelled, and we should not send it.\n     */\n    _defineProperty(this, \"eventsBeingEncrypted\", new Set());\n    _defineProperty(this, \"useE2eForGroupCall\", true);\n    _defineProperty(this, \"toDeviceMessageQueue\", void 0);\n    _defineProperty(this, \"livekitServiceURL\", void 0);\n    _defineProperty(this, \"_secretStorage\", void 0);\n    // A manager for determining which invites should be ignored.\n    _defineProperty(this, \"ignoredInvites\", void 0);\n    _defineProperty(this, \"matrixRTC\", void 0);\n    _defineProperty(this, \"serverCapabilitiesService\", void 0);\n    _defineProperty(this, \"startCallEventHandler\", () => {\n      if (this.isInitialSyncComplete()) {\n        if (supportsMatrixCall()) {\n          this.callEventHandler.start();\n          this.groupCallEventHandler.start();\n        }\n        this.off(ClientEvent.Sync, this.startCallEventHandler);\n      }\n    });\n    _defineProperty(this, \"startMatrixRTC\", () => {\n      if (this.isInitialSyncComplete()) {\n        this.matrixRTC.start();\n        this.off(ClientEvent.Sync, this.startMatrixRTC);\n      }\n    });\n    /**\n     * Once the client has been initialised, we want to clear notifications we\n     * know for a fact should be here.\n     * This issue should also be addressed on synapse's side and is tracked as part\n     * of https://github.com/matrix-org/synapse/issues/14837\n     *\n     * We consider a room or a thread as fully read if the current user has sent\n     * the last event in the live timeline of that context and if the read receipt\n     * we have on record matches.\n     */\n    _defineProperty(this, \"fixupRoomNotifications\", () => {\n      if (this.isInitialSyncComplete()) {\n        var _this$getRooms;\n        var unreadRooms = ((_this$getRooms = this.getRooms()) !== null && _this$getRooms !== void 0 ? _this$getRooms : []).filter(room => {\n          return room.getUnreadNotificationCount(NotificationCountType.Total) > 0;\n        });\n        for (var _room of unreadRooms) {\n          var currentUserId = this.getSafeUserId();\n          _room.fixupNotifications(currentUserId);\n        }\n        this.off(ClientEvent.Sync, this.fixupRoomNotifications);\n      }\n    });\n    this.logger = (_opts$logger = opts.logger) !== null && _opts$logger !== void 0 ? _opts$logger : logger;\n    opts.baseUrl = utils.ensureNoTrailingSlash(opts.baseUrl);\n    opts.idBaseUrl = utils.ensureNoTrailingSlash(opts.idBaseUrl);\n    this.baseUrl = opts.baseUrl;\n    this.idBaseUrl = opts.idBaseUrl;\n    this.identityServer = opts.identityServer;\n    this.usingExternalCrypto = (_opts$usingExternalCr = opts.usingExternalCrypto) !== null && _opts$usingExternalCr !== void 0 ? _opts$usingExternalCr : false;\n    this.store = opts.store || new StubStore();\n    this.deviceId = opts.deviceId || null;\n    this.sessionId = secureRandomString(10);\n    var userId = opts.userId || null;\n    this.credentials = {\n      userId\n    };\n    this.http = new MatrixHttpApi(this, {\n      fetchFn: opts.fetchFn,\n      baseUrl: opts.baseUrl,\n      idBaseUrl: opts.idBaseUrl,\n      accessToken: opts.accessToken,\n      refreshToken: opts.refreshToken,\n      tokenRefreshFunction: opts.tokenRefreshFunction,\n      prefix: ClientPrefix.V3,\n      onlyData: true,\n      extraParams: opts.queryParams,\n      localTimeoutMs: opts.localTimeoutMs,\n      useAuthorizationHeader: opts.useAuthorizationHeader,\n      logger: this.logger\n    });\n    if (opts.pickleKey) {\n      this.legacyPickleKey = opts.pickleKey;\n    }\n    this.useLivekitForGroupCalls = Boolean(opts.useLivekitForGroupCalls);\n    this.scheduler = opts.scheduler;\n    if (this.scheduler) {\n      this.scheduler.setProcessFunction(/*#__PURE__*/function () {\n        var _ref = _asyncToGenerator(function* (eventToSend) {\n          var room = _this.getRoom(eventToSend.getRoomId());\n          if (eventToSend.status !== EventStatus.SENDING) {\n            _this.updatePendingEventStatus(room, eventToSend, EventStatus.SENDING);\n          }\n          var res = yield _this.sendEventHttpRequest(eventToSend);\n          if (room) {\n            // ensure we update pending event before the next scheduler run so that any listeners to event id\n            // updates on the synchronous event emitter get a chance to run first.\n            room.updatePendingEvent(eventToSend, EventStatus.SENT, res.event_id);\n          }\n          return res;\n        });\n        return function (_x) {\n          return _ref.apply(this, arguments);\n        };\n      }());\n    }\n    this.disableVoip = (_opts$disableVoip = opts.disableVoip) !== null && _opts$disableVoip !== void 0 ? _opts$disableVoip : false;\n    if (!this.disableVoip && supportsMatrixCall()) {\n      this.callEventHandler = new CallEventHandler(this);\n      this.groupCallEventHandler = new GroupCallEventHandler(this);\n      this.canSupportVoip = true;\n      // Start listening for calls after the initial sync is done\n      // We do not need to backfill the call event buffer\n      // with encrypted events that might never get decrypted\n      this.on(ClientEvent.Sync, this.startCallEventHandler);\n    }\n\n    // NB. We initialise MatrixRTC whether we have call support or not: this is just\n    // the underlying session management and doesn't use any actual media capabilities\n    this.matrixRTC = new MatrixRTCSessionManager(this.logger, this);\n    this.serverCapabilitiesService = new ServerCapabilities(this.logger, this.http);\n    this.on(ClientEvent.Sync, this.fixupRoomNotifications);\n    this.timelineSupport = Boolean(opts.timelineSupport);\n    this.legacyCryptoStore = opts.cryptoStore;\n    this.verificationMethods = opts.verificationMethods;\n    this.cryptoCallbacks = opts.cryptoCallbacks || {};\n    this.enableEncryptedStateEvents = (_opts$enableEncrypted = opts.enableEncryptedStateEvents) !== null && _opts$enableEncrypted !== void 0 ? _opts$enableEncrypted : false;\n    this.forceTURN = opts.forceTURN || false;\n    this.iceCandidatePoolSize = opts.iceCandidatePoolSize === undefined ? 0 : opts.iceCandidatePoolSize;\n    this.supportsCallTransfer = opts.supportsCallTransfer || false;\n    this.fallbackICEServerAllowed = opts.fallbackICEServerAllowed || false;\n    this.isVoipWithNoMediaAllowed = opts.isVoipWithNoMediaAllowed || false;\n    if (opts.useE2eForGroupCall !== undefined) this.useE2eForGroupCall = opts.useE2eForGroupCall;\n    this.livekitServiceURL = opts.livekitServiceURL;\n    this.roomNameGenerator = opts.roomNameGenerator;\n    this.toDeviceMessageQueue = new ToDeviceMessageQueue(this, this.logger);\n\n    // The SDK doesn't really provide a clean way for events to recalculate the push\n    // actions for themselves, so we have to kinda help them out when they are encrypted.\n    // We do this so that push rules are correctly executed on events in their decrypted\n    // state, such as highlights when the user's name is mentioned.\n    this.on(MatrixEventEvent.Decrypted, event => {\n      fixNotificationCountOnDecryption(this, event);\n    });\n    this.ignoredInvites = new IgnoredInvites(this);\n    this._secretStorage = new ServerSideSecretStorageImpl(this, (_opts$cryptoCallbacks = opts.cryptoCallbacks) !== null && _opts$cryptoCallbacks !== void 0 ? _opts$cryptoCallbacks : {});\n\n    // having lots of event listeners is not unusual. 0 means \"unlimited\".\n    this.setMaxListeners(0);\n  }\n  set store(newStore) {\n    this._store = newStore;\n    this._store.setUserCreator(userId => User.createUser(userId, this));\n  }\n  get store() {\n    return this._store;\n  }\n\n  /**\n   * High level helper method to begin syncing and poll for new events. To listen for these\n   * events, add a listener for {@link ClientEvent.Event}\n   * via {@link MatrixClient#on}. Alternatively, listen for specific\n   * state change events.\n   * @param opts - Options to apply when syncing.\n   */\n  startClient(opts) {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      if (_this2.clientRunning) {\n        // client is already running.\n        return;\n      }\n      _this2.clientRunning = true;\n      _this2.on(ClientEvent.Sync, _this2.startMatrixRTC);\n\n      // Create our own user object artificially (instead of waiting for sync)\n      // so it's always available, even if the user is not in any rooms etc.\n      var userId = _this2.getUserId();\n      if (userId) {\n        _this2.store.storeUser(new User(userId));\n      }\n\n      // periodically poll for turn servers if we support voip\n      if (_this2.supportsVoip()) {\n        _this2.checkTurnServersIntervalID = setInterval(() => {\n          _this2.checkTurnServers();\n        }, TURN_CHECK_INTERVAL);\n        // noinspection ES6MissingAwait\n        _this2.checkTurnServers();\n      }\n      if (_this2.syncApi) {\n        // This shouldn't happen since we thought the client was not running\n        _this2.logger.error(\"Still have sync object whilst not running: stopping old one\");\n        _this2.syncApi.stop();\n      }\n      try {\n        yield _this2.getVersions();\n\n        // This should be done with `canSupport`\n        // TODO: https://github.com/vector-im/element-web/issues/23643\n        var {\n          threads,\n          list,\n          fwdPagination\n        } = yield _this2.doesServerSupportThread();\n        Thread.setServerSideSupport(threads);\n        Thread.setServerSideListSupport(list);\n        Thread.setServerSideFwdPaginationSupport(fwdPagination);\n      } catch (e) {\n        _this2.logger.error(\"Can't fetch server versions, continuing to initialise sync, this will be retried later\", e);\n      }\n      _this2.clientOpts = opts !== null && opts !== void 0 ? opts : {};\n      if (_this2.clientOpts.slidingSync) {\n        _this2.syncApi = new SlidingSyncSdk(_this2.clientOpts.slidingSync, _this2, _this2.clientOpts, _this2.buildSyncApiOptions());\n      } else {\n        _this2.syncApi = new SyncApi(_this2, _this2.clientOpts, _this2.buildSyncApiOptions());\n      }\n      _this2.syncApi.sync().catch(e => _this2.logger.info(\"Sync startup aborted with an error:\", e));\n      if (_this2.clientOpts.clientWellKnownPollPeriod !== undefined) {\n        _this2.clientWellKnownIntervalID = setInterval(() => {\n          _this2.fetchClientWellKnown();\n        }, 1000 * _this2.clientOpts.clientWellKnownPollPeriod);\n        _this2.fetchClientWellKnown();\n      }\n      _this2.toDeviceMessageQueue.start();\n      _this2.serverCapabilitiesService.start();\n    })();\n  }\n\n  /**\n   * Construct a SyncApiOptions for this client, suitable for passing into the SyncApi constructor\n   */\n  buildSyncApiOptions() {\n    return {\n      cryptoCallbacks: this.cryptoBackend,\n      canResetEntireTimeline: roomId => {\n        if (!this.canResetTimelineCallback) {\n          return false;\n        }\n        return this.canResetTimelineCallback(roomId);\n      },\n      logger: this.logger.getChild(\"sync\")\n    };\n  }\n\n  /**\n   * High level helper method to stop the client from polling and allow a\n   * clean shutdown.\n   */\n  stopClient() {\n    var _this$cryptoBackend, _this$syncApi, _this$peekSync, _this$callEventHandle, _this$groupCallEventH;\n    (_this$cryptoBackend = this.cryptoBackend) === null || _this$cryptoBackend === void 0 || _this$cryptoBackend.stop(); // crypto might have been initialised even if the client wasn't fully started\n\n    this.off(ClientEvent.Sync, this.startMatrixRTC);\n    if (!this.clientRunning) return; // already stopped\n\n    this.logger.debug(\"stopping MatrixClient\");\n    this.clientRunning = false;\n    (_this$syncApi = this.syncApi) === null || _this$syncApi === void 0 || _this$syncApi.stop();\n    this.syncApi = undefined;\n    (_this$peekSync = this.peekSync) === null || _this$peekSync === void 0 || _this$peekSync.stopPeeking();\n    (_this$callEventHandle = this.callEventHandler) === null || _this$callEventHandle === void 0 || _this$callEventHandle.stop();\n    (_this$groupCallEventH = this.groupCallEventHandler) === null || _this$groupCallEventH === void 0 || _this$groupCallEventH.stop();\n    this.callEventHandler = undefined;\n    this.groupCallEventHandler = undefined;\n    globalThis.clearInterval(this.checkTurnServersIntervalID);\n    this.checkTurnServersIntervalID = undefined;\n    if (this.clientWellKnownIntervalID !== undefined) {\n      globalThis.clearInterval(this.clientWellKnownIntervalID);\n    }\n    this.toDeviceMessageQueue.stop();\n    this.matrixRTC.stop();\n    this.serverCapabilitiesService.stop();\n  }\n\n  /**\n   * Clear any data out of the persistent stores used by the client.\n   *\n   * @param args.cryptoDatabasePrefix - The database name to use for indexeddb, defaults to 'matrix-js-sdk'.\n   * @returns Promise which resolves when the stores have been cleared.\n   */\n  clearStores() {\n    var _this3 = this;\n    var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n    if (this.clientRunning) {\n      throw new Error(\"Cannot clear stores while client is running\");\n    }\n    var promises = [];\n    promises.push(this.store.deleteAllData());\n    if (this.legacyCryptoStore) {\n      promises.push(this.legacyCryptoStore.deleteAllData());\n    }\n\n    // delete the stores used by the rust matrix-sdk-crypto, in case they were used\n    var deleteRustSdkStore = /*#__PURE__*/function () {\n      var _ref2 = _asyncToGenerator(function* () {\n        var indexedDB;\n        try {\n          indexedDB = globalThis.indexedDB;\n          if (!indexedDB) return; // No indexedDB support\n        } catch (_unused) {\n          // No indexedDB support\n          return;\n        }\n        var _loop = function* _loop(dbname) {\n          var prom = new Promise((resolve, reject) => {\n            _this3.logger.info(\"Removing IndexedDB instance \".concat(dbname));\n            var req = indexedDB.deleteDatabase(dbname);\n            req.onsuccess = _ => {\n              _this3.logger.info(\"Removed IndexedDB instance \".concat(dbname));\n              resolve(0);\n            };\n            req.onerror = e => {\n              // In private browsing, Firefox has a globalThis.indexedDB, but attempts to delete an indexeddb\n              // (even a non-existent one) fail with \"DOMException: A mutation operation was attempted on a\n              // database that did not allow mutations.\"\n              //\n              // it seems like the only thing we can really do is ignore the error.\n              _this3.logger.warn(\"Failed to remove IndexedDB instance \".concat(dbname, \":\"), e);\n              resolve(0);\n            };\n            req.onblocked = e => {\n              _this3.logger.info(\"cannot yet remove IndexedDB instance \".concat(dbname));\n            };\n          });\n          yield prom;\n        };\n        for (var dbname of [\"\".concat((_args$cryptoDatabaseP = args.cryptoDatabasePrefix) !== null && _args$cryptoDatabaseP !== void 0 ? _args$cryptoDatabaseP : RUST_SDK_STORE_PREFIX, \"::matrix-sdk-crypto\"), \"\".concat((_args$cryptoDatabaseP2 = args.cryptoDatabasePrefix) !== null && _args$cryptoDatabaseP2 !== void 0 ? _args$cryptoDatabaseP2 : RUST_SDK_STORE_PREFIX, \"::matrix-sdk-crypto-meta\")]) {\n          var _args$cryptoDatabaseP, _args$cryptoDatabaseP2;\n          yield* _loop(dbname);\n        }\n      });\n      return function deleteRustSdkStore() {\n        return _ref2.apply(this, arguments);\n      };\n    }();\n    promises.push(deleteRustSdkStore());\n    return Promise.all(promises).then(); // .then to fix types\n  }\n\n  /**\n   * Get the user-id of the logged-in user\n   *\n   * @returns MXID for the logged-in user, or null if not logged in\n   */\n  getUserId() {\n    var _this$credentials$use, _this$credentials;\n    return (_this$credentials$use = (_this$credentials = this.credentials) === null || _this$credentials === void 0 ? void 0 : _this$credentials.userId) !== null && _this$credentials$use !== void 0 ? _this$credentials$use : null;\n  }\n\n  /**\n   * Get the user-id of the logged-in user\n   *\n   * @returns MXID for the logged-in user\n   * @throws Error if not logged in\n   */\n  getSafeUserId() {\n    var userId = this.getUserId();\n    if (!userId) {\n      throw new Error(\"Expected logged in user but found none.\");\n    }\n    return userId;\n  }\n\n  /**\n   * Get the domain for this client's MXID\n   * @returns Domain of this MXID\n   */\n  getDomain() {\n    var _this$credentials2;\n    if ((_this$credentials2 = this.credentials) !== null && _this$credentials2 !== void 0 && _this$credentials2.userId) {\n      return this.credentials.userId.replace(/^.*?:/, \"\");\n    }\n    return null;\n  }\n\n  /**\n   * Get the local part of the current user ID e.g. \"foo\" in \"\\@foo:bar\".\n   * @returns The user ID localpart or null.\n   */\n  getUserIdLocalpart() {\n    var _this$credentials$use2, _this$credentials3;\n    return (_this$credentials$use2 = (_this$credentials3 = this.credentials) === null || _this$credentials3 === void 0 || (_this$credentials3 = _this$credentials3.userId) === null || _this$credentials3 === void 0 ? void 0 : _this$credentials3.split(\":\")[0].substring(1)) !== null && _this$credentials$use2 !== void 0 ? _this$credentials$use2 : null;\n  }\n\n  /**\n   * Get the device ID of this client\n   * @returns device ID\n   */\n  getDeviceId() {\n    return this.deviceId;\n  }\n\n  /**\n   * Get the session ID of this client\n   * @returns session ID\n   */\n  getSessionId() {\n    return this.sessionId;\n  }\n\n  /**\n   * Check if the runtime environment supports VoIP calling.\n   * @returns True if VoIP is supported.\n   */\n  supportsVoip() {\n    return !this.disableVoip && this.canSupportVoip;\n  }\n\n  /**\n   * @returns\n   */\n  getMediaHandler() {\n    return this.mediaHandler;\n  }\n\n  /**\n   * Set whether VoIP calls are forced to use only TURN\n   * candidates. This is the same as the forceTURN option\n   * when creating the client.\n   * @param force - True to force use of TURN servers\n   */\n  setForceTURN(force) {\n    this.forceTURN = force;\n  }\n\n  /**\n   * Set whether to advertise transfer support to other parties on Matrix calls.\n   * @param support - True to advertise the 'm.call.transferee' capability\n   */\n  setSupportsCallTransfer(support) {\n    this.supportsCallTransfer = support;\n  }\n\n  /**\n   * Returns true if to-device signalling for group calls will be encrypted with Olm.\n   * If false, it will be sent unencrypted.\n   * @returns boolean Whether group call signalling will be encrypted\n   */\n  getUseE2eForGroupCall() {\n    return this.useE2eForGroupCall;\n  }\n\n  /**\n   * Creates a new call.\n   * The place*Call methods on the returned call can be used to actually place a call\n   *\n   * @param roomId - The room the call is to be placed in.\n   * @returns the call or null if the browser doesn't support calling.\n   */\n  createCall(roomId) {\n    return createNewMatrixCall(this, roomId);\n  }\n\n  /**\n   * Creates a new group call and sends the associated state event\n   * to alert other members that the room now has a group call.\n   *\n   * @param roomId - The room the call is to be placed in.\n   */\n  createGroupCall(roomId, type, isPtt, intent, dataChannelsEnabled, dataChannelOptions) {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      if (_this4.getGroupCallForRoom(roomId)) {\n        throw new Error(\"\".concat(roomId, \" already has an existing group call\"));\n      }\n      var room = _this4.getRoom(roomId);\n      if (!room) {\n        throw new Error(\"Cannot find room \".concat(roomId));\n      }\n\n      // Because without Media section a WebRTC connection is not possible, so need a RTCDataChannel to set up a\n      // no media WebRTC connection anyway.\n      return new GroupCall(_this4, room, type, isPtt, intent, undefined, dataChannelsEnabled || _this4.isVoipWithNoMediaAllowed, dataChannelOptions, _this4.isVoipWithNoMediaAllowed, _this4.useLivekitForGroupCalls, _this4.livekitServiceURL).create();\n    })();\n  }\n  getLivekitServiceURL() {\n    return this.livekitServiceURL;\n  }\n\n  // This shouldn't need to exist, but the widget API has startup ordering problems that\n  // mean it doesn't know the livekit URL fast enough: remove this once this is fixed.\n  setLivekitServiceURL(newURL) {\n    this.livekitServiceURL = newURL;\n  }\n\n  /**\n   * Wait until an initial state for the given room has been processed by the\n   * client and the client is aware of any ongoing group calls. Awaiting on\n   * the promise returned by this method before calling getGroupCallForRoom()\n   * avoids races where getGroupCallForRoom is called before the state for that\n   * room has been processed. It does not, however, fix other races, eg. two\n   * clients both creating a group call at the same time.\n   * @param roomId - The room ID to wait for\n   * @returns A promise that resolves once existing group calls in the room\n   *          have been processed.\n   */\n  waitUntilRoomReadyForGroupCalls(roomId) {\n    return this.groupCallEventHandler.waitUntilRoomReadyForGroupCalls(roomId);\n  }\n\n  /**\n   * Get an existing group call for the provided room.\n   * @returns The group call or null if it doesn't already exist.\n   */\n  getGroupCallForRoom(roomId) {\n    return this.groupCallEventHandler.groupCalls.get(roomId) || null;\n  }\n\n  /**\n   * Get the current sync state.\n   * @returns the sync state, which may be null.\n   * @see MatrixClient#event:\"sync\"\n   */\n  getSyncState() {\n    var _this$syncApi$getSync, _this$syncApi2;\n    return (_this$syncApi$getSync = (_this$syncApi2 = this.syncApi) === null || _this$syncApi2 === void 0 ? void 0 : _this$syncApi2.getSyncState()) !== null && _this$syncApi$getSync !== void 0 ? _this$syncApi$getSync : null;\n  }\n\n  /**\n   * Returns the additional data object associated with\n   * the current sync state, or null if there is no\n   * such data.\n   * Sync errors, if available, are put in the 'error' key of\n   * this object.\n   */\n  getSyncStateData() {\n    if (!this.syncApi) {\n      return null;\n    }\n    return this.syncApi.getSyncStateData();\n  }\n\n  /**\n   * Whether the initial sync has completed.\n   * @returns True if at least one sync has happened.\n   */\n  isInitialSyncComplete() {\n    var state = this.getSyncState();\n    if (!state) {\n      return false;\n    }\n    return state === SyncState.Prepared || state === SyncState.Syncing;\n  }\n\n  /**\n   * Return whether the client is configured for a guest account.\n   * @returns True if this is a guest access_token (or no token is supplied).\n   */\n  isGuest() {\n    return this.isGuestAccount;\n  }\n\n  /**\n   * Set whether this client is a guest account. <b>This method is experimental\n   * and may change without warning.</b>\n   * @param guest - True if this is a guest account.\n   * @experimental if the token is a macaroon, it should be encoded in it that it is a 'guest'\n   * access token, which means that the SDK can determine this entirely without\n   * the dev manually flipping this flag.\n   */\n  setGuest(guest) {\n    this.isGuestAccount = guest;\n  }\n\n  /**\n   * Return the provided scheduler, if any.\n   * @returns The scheduler or undefined\n   */\n  getScheduler() {\n    return this.scheduler;\n  }\n\n  /**\n   * Retry a backed off syncing request immediately. This should only be used when\n   * the user <b>explicitly</b> attempts to retry their lost connection.\n   * Will also retry any outbound to-device messages currently in the queue to be sent\n   * (retries of regular outgoing events are handled separately, per-event).\n   * @returns True if this resulted in a request being retried.\n   */\n  retryImmediately() {\n    var _this$syncApi$retryIm, _this$syncApi3;\n    // don't await for this promise: we just want to kick it off\n    this.toDeviceMessageQueue.sendQueue();\n    return (_this$syncApi$retryIm = (_this$syncApi3 = this.syncApi) === null || _this$syncApi3 === void 0 ? void 0 : _this$syncApi3.retryImmediately()) !== null && _this$syncApi$retryIm !== void 0 ? _this$syncApi$retryIm : false;\n  }\n\n  /**\n   * Return the global notification EventTimelineSet, if any\n   *\n   * @returns the globl notification EventTimelineSet\n   */\n  getNotifTimelineSet() {\n    return this.notifTimelineSet;\n  }\n\n  /**\n   * Set the global notification EventTimelineSet\n   *\n   */\n  setNotifTimelineSet(set) {\n    this.notifTimelineSet = set;\n  }\n\n  /**\n   * Gets the cached capabilities of the homeserver, returning cached ones if available.\n   * If there are no cached capabilities and none can be fetched, throw an exception.\n   *\n   * @returns Promise resolving with The capabilities of the homeserver\n   */\n  getCapabilities() {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      var caps = _this5.serverCapabilitiesService.getCachedCapabilities();\n      if (caps) return caps;\n      return _this5.serverCapabilitiesService.fetchCapabilities();\n    })();\n  }\n\n  /**\n   * Gets the cached capabilities of the homeserver. If none have been fetched yet,\n   * return undefined.\n   *\n   * @returns The capabilities of the homeserver\n   */\n  getCachedCapabilities() {\n    return this.serverCapabilitiesService.getCachedCapabilities();\n  }\n\n  /**\n   * Fetches the latest capabilities from the homeserver, ignoring any cached\n   * versions. The newly returned version is cached.\n   *\n   * @returns A promise which resolves to the capabilities of the homeserver\n   */\n  fetchCapabilities() {\n    return this.serverCapabilitiesService.fetchCapabilities();\n  }\n\n  /**\n   * Initialise support for end-to-end encryption in this client, using the rust matrix-sdk-crypto.\n   *\n   * **WARNING**: the cryptography stack is not thread-safe. Having multiple `MatrixClient` instances connected to\n   * the same Indexed DB will cause data corruption and decryption failures. The application layer is responsible for\n   * ensuring that only one `MatrixClient` issue is instantiated at a time.\n   *\n   * @param args.useIndexedDB - True to use an indexeddb store, false to use an in-memory store. Defaults to 'true'.\n   * @param args.cryptoDatabasePrefix - The database name to use for indexeddb, defaults to 'matrix-js-sdk'.\n   *    Unused if useIndexedDB is 'false'.\n   * @param args.storageKey - A key with which to encrypt the indexeddb store. If provided, it must be exactly\n   *    32 bytes of data, and must be the same each time the client is initialised for a given device.\n   *    If both this and `storagePassword` are unspecified, the store will be unencrypted.\n   * @param args.storagePassword - An alternative to `storageKey`. A password which will be used to derive a key to\n   *    encrypt the store with. Deriving a key from a password is (deliberately) a slow operation, so prefer\n   *    to pass a `storageKey` directly where possible.\n   *\n   * @returns a Promise which will resolve when the crypto layer has been\n   *    successfully initialised.\n   */\n  initRustCrypto() {\n    var _arguments = arguments,\n      _this6 = this;\n    return _asyncToGenerator(function* () {\n      var _args$cryptoDatabaseP3, _this6$legacyPickleKe;\n      var args = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : {};\n      if (_this6.cryptoBackend) {\n        _this6.logger.warn(\"Attempt to re-initialise e2e encryption on MatrixClient\");\n        return;\n      }\n      var userId = _this6.getUserId();\n      if (userId === null) {\n        throw new Error(\"Cannot enable encryption on MatrixClient with unknown userId: \" + \"ensure userId is passed in createClient().\");\n      }\n      var deviceId = _this6.getDeviceId();\n      if (deviceId === null) {\n        throw new Error(\"Cannot enable encryption on MatrixClient with unknown deviceId: \" + \"ensure deviceId is passed in createClient().\");\n      }\n\n      // importing rust-crypto will download the webassembly, so we delay it until we know it will be\n      // needed.\n      _this6.logger.debug(\"Downloading Rust crypto library\");\n      var RustCrypto = yield import(\"./rust-crypto/index.js\");\n      var rustCrypto = yield RustCrypto.initRustCrypto({\n        logger: _this6.logger,\n        http: _this6.http,\n        userId: userId,\n        deviceId: deviceId,\n        secretStorage: _this6.secretStorage,\n        cryptoCallbacks: _this6.cryptoCallbacks,\n        storePrefix: args.useIndexedDB === false ? null : (_args$cryptoDatabaseP3 = args.cryptoDatabasePrefix) !== null && _args$cryptoDatabaseP3 !== void 0 ? _args$cryptoDatabaseP3 : RUST_SDK_STORE_PREFIX,\n        storeKey: args.storageKey,\n        storePassphrase: args.storagePassword,\n        legacyCryptoStore: _this6.legacyCryptoStore,\n        legacyPickleKey: (_this6$legacyPickleKe = _this6.legacyPickleKey) !== null && _this6$legacyPickleKe !== void 0 ? _this6$legacyPickleKe : \"DEFAULT_KEY\",\n        legacyMigrationProgressListener: (progress, total) => {\n          _this6.emit(CryptoEvent.LegacyCryptoStoreMigrationProgress, progress, total);\n        },\n        enableEncryptedStateEvents: _this6.enableEncryptedStateEvents\n      });\n      rustCrypto.setSupportedVerificationMethods(_this6.verificationMethods);\n      _this6.cryptoBackend = rustCrypto;\n\n      // attach the event listeners needed by RustCrypto\n      _this6.on(RoomMemberEvent.Membership, rustCrypto.onRoomMembership.bind(rustCrypto));\n      _this6.on(ClientEvent.Event, event => {\n        rustCrypto.onLiveEventFromSync(event);\n      });\n\n      // re-emit the events emitted by the crypto impl\n      _this6.reEmitter.reEmit(rustCrypto, [CryptoEvent.VerificationRequestReceived, CryptoEvent.UserTrustStatusChanged, CryptoEvent.KeyBackupStatus, CryptoEvent.KeyBackupSessionsRemaining, CryptoEvent.KeyBackupFailed, CryptoEvent.KeyBackupDecryptionKeyCached, CryptoEvent.KeysChanged, CryptoEvent.DevicesUpdated, CryptoEvent.WillUpdateDevices, CryptoEvent.DehydratedDeviceCreated, CryptoEvent.DehydratedDeviceUploaded, CryptoEvent.RehydrationStarted, CryptoEvent.RehydrationProgress, CryptoEvent.RehydrationCompleted, CryptoEvent.RehydrationError, CryptoEvent.DehydrationKeyCached, CryptoEvent.DehydratedDeviceRotationError]);\n    })();\n  }\n\n  /**\n   * Access the server-side secret storage API for this client.\n   */\n  get secretStorage() {\n    return this._secretStorage;\n  }\n\n  /**\n   * Access the crypto API for this client.\n   *\n   * If end-to-end encryption has been enabled for this client (via {@link initRustCrypto}),\n   * returns an object giving access to the crypto API. Otherwise, returns `undefined`.\n   */\n  getCrypto() {\n    return this.cryptoBackend;\n  }\n\n  /**\n   * Whether encryption is enabled for a room.\n   * @param roomId - the room id to query.\n   * @returns whether encryption is enabled.\n   *\n   * @deprecated Not correctly supported for Rust Cryptography. Use {@link CryptoApi.isEncryptionEnabledInRoom} and/or\n   *    {@link Room.hasEncryptionStateEvent}.\n   */\n  isRoomEncrypted(roomId) {\n    var room = this.getRoom(roomId);\n    if (!room) {\n      // we don't know about this room, so can't determine if it should be\n      // encrypted. Let's assume not.\n      return false;\n    }\n\n    // if there is an 'm.room.encryption' event in this room, it should be\n    // encrypted (independently of whether we actually support encryption)\n    return room.hasEncryptionStateEvent();\n  }\n\n  /**\n   * Check whether the key backup private key is stored in secret storage.\n   * @returns map of key name to key info the secret is\n   *     encrypted with, or null if it is not present or not encrypted with a\n   *     trusted key\n   */\n  isKeyBackupKeyStored() {\n    return Promise.resolve(this.secretStorage.isStored(\"m.megolm_backup.v1\"));\n  }\n  makeKeyBackupPath(roomId, sessionId, version) {\n    var path;\n    if (sessionId !== undefined) {\n      path = utils.encodeUri(\"/room_keys/keys/$roomId/$sessionId\", {\n        $roomId: roomId,\n        $sessionId: sessionId\n      });\n    } else if (roomId !== undefined) {\n      path = utils.encodeUri(\"/room_keys/keys/$roomId\", {\n        $roomId: roomId\n      });\n    } else {\n      path = \"/room_keys/keys\";\n    }\n    var queryData = version === undefined ? undefined : {\n      version\n    };\n    return {\n      path,\n      queryData\n    };\n  }\n  deleteKeysFromBackup(roomId, sessionId, version) {\n    var _this7 = this;\n    return _asyncToGenerator(function* () {\n      var path = _this7.makeKeyBackupPath(roomId, sessionId, version);\n      yield _this7.http.authedRequest(Method.Delete, path.path, path.queryData, undefined, {\n        prefix: ClientPrefix.V3\n      });\n    })();\n  }\n\n  /**\n   * Get the config for the media repository.\n   *\n   * @param useAuthenticatedMedia - If true, the caller supports authenticated\n   * media and wants an authentication-required URL. Note that server support\n   * for authenticated media will *not* be checked - it is the caller's responsibility\n   * to do so before calling this function.\n   *\n   * @returns Promise which resolves with an object containing the config.\n   */\n  getMediaConfig() {\n    var useAuthenticatedMedia = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n    var path = useAuthenticatedMedia ? \"/media/config\" : \"/config\";\n    return this.http.authedRequest(Method.Get, path, undefined, undefined, {\n      prefix: useAuthenticatedMedia ? ClientPrefix.V1 : MediaPrefix.V3\n    });\n  }\n\n  /**\n   * Get the room for the given room ID.\n   * This function will return a valid room for any room for which a Room event\n   * has been emitted. Note in particular that other events, eg. RoomState.members\n   * will be emitted for a room before this function will return the given room.\n   * @param roomId - The room ID\n   * @returns The Room or null if it doesn't exist or there is no data store.\n   */\n  getRoom(roomId) {\n    if (!roomId) {\n      return null;\n    }\n    return this.store.getRoom(roomId);\n  }\n\n  /**\n   * Retrieve all known rooms.\n   * @returns A list of rooms, or an empty list if there is no data store.\n   */\n  getRooms() {\n    return this.store.getRooms();\n  }\n\n  /**\n   * Retrieve all rooms that should be displayed to the user\n   * This is essentially getRooms() with some rooms filtered out, eg. old versions\n   * of rooms that have been replaced or (in future) other rooms that have been\n   * marked at the protocol level as not to be displayed to the user.\n   *\n   * @param msc3946ProcessDynamicPredecessor - if true, look for an\n   *                                           m.room.predecessor state event and\n   *                                           use it if found (MSC3946).\n   * @returns A list of rooms, or an empty list if there is no data store.\n   */\n  getVisibleRooms() {\n    var msc3946ProcessDynamicPredecessor = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n    var allRooms = this.store.getRooms();\n    var visibleRooms = new Set(allRooms);\n    for (var _room2 of visibleRooms) {\n      var predecessors = this.findPredecessorRooms(_room2, true, msc3946ProcessDynamicPredecessor);\n      for (var predecessor of predecessors) {\n        visibleRooms.delete(predecessor);\n      }\n    }\n    return Array.from(visibleRooms);\n  }\n\n  /**\n   * Retrieve a user.\n   * @param userId - The user ID to retrieve.\n   * @returns A user or null if there is no data store or the user does\n   * not exist.\n   */\n  getUser(userId) {\n    return this.store.getUser(userId);\n  }\n\n  /**\n   * Retrieve all known users.\n   * @returns A list of users, or an empty list if there is no data store.\n   */\n  getUsers() {\n    return this.store.getUsers();\n  }\n\n  /**\n   * Set account data event for the current user, and wait for the result to be echoed over `/sync`.\n   *\n   * Waiting for the remote echo ensures that a subsequent call to {@link getAccountData} will return the updated\n   * value.\n   *\n   * If called before the client is started with {@link startClient}, logs a warning and falls back to\n   * {@link setAccountDataRaw}.\n   *\n   * Retries the request up to 5 times in the case of an {@link ConnectionError}.\n   *\n   * @param eventType - The event type\n   * @param content - the contents object for the event\n   */\n  setAccountData(eventType, content) {\n    var _this8 = this;\n    return _asyncToGenerator(function* () {\n      // If the sync loop is not running, fall back to setAccountDataRaw.\n      if (!_this8.clientRunning) {\n        _this8.logger.warn(\"Calling `setAccountData` before the client is started: `getAccountData` may return inconsistent results.\");\n        return yield retryNetworkOperation(5, () => _this8.setAccountDataRaw(eventType, content));\n      }\n\n      // If the account data is already correct, then we cannot expect an update over sync, and the operation\n      // is, in any case, a no-op.\n      //\n      // NB that we rely on this operation being synchronous to avoid a race condition: there must be no `await`\n      // between here and `this.addListener` below, in case we miss an update.\n      var existingData = _this8.store.getAccountData(eventType);\n      if (existingData && deepCompare(existingData.event.content, content)) return {};\n\n      // Create a promise which will resolve when the update is received\n      var updatedResolvers = Promise.withResolvers();\n      function accountDataListener(event) {\n        // Note that we cannot safely check that the content matches what we expected, because there is a race:\n        //   * We set the new content\n        //   * Another client sets alternative content\n        //   * Then /sync returns, but only reflects the latest content.\n        //\n        // Of course there is room for debate over what we should actually do in that case -- a subsequent\n        // `getAccountData` isn't going to return the expected value, but whose fault is that? Databases are hard.\n        //\n        // Anyway, what we *shouldn't* do is get stuck in a loop. I think the best we can do is check that the event\n        // type matches.\n        if (event.getType() === eventType) updatedResolvers.resolve();\n      }\n      _this8.addListener(ClientEvent.AccountData, accountDataListener);\n      try {\n        var result = yield retryNetworkOperation(5, () => _this8.setAccountDataRaw(eventType, content));\n        yield updatedResolvers.promise;\n        return result;\n      } finally {\n        _this8.removeListener(ClientEvent.AccountData, accountDataListener);\n      }\n    })();\n  }\n\n  /**\n   * Set account data event for the current user, without waiting for the remote echo.\n   *\n   * @param eventType - The event type\n   * @param content - the contents object for the event\n   */\n  setAccountDataRaw(eventType, content) {\n    var path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n      $userId: this.credentials.userId,\n      $type: eventType\n    });\n    return this.http.authedRequest(Method.Put, path, undefined, content);\n  }\n\n  /**\n   * Get account data event of given type for the current user.\n   * @param eventType - The event type\n   * @returns The contents of the given account data event\n   */\n  getAccountData(eventType) {\n    return this.store.getAccountData(eventType);\n  }\n\n  /**\n   * Get account data event of given type for the current user. This variant\n   * gets account data directly from the homeserver if the local store is not\n   * ready, which can be useful very early in startup before the initial sync.\n   * @param eventType - The event type\n   * @returns Promise which resolves: The contents of the given account data event.\n   * @returns Rejects: with an error response.\n   */\n  getAccountDataFromServer(eventType) {\n    var _this9 = this;\n    return _asyncToGenerator(function* () {\n      if (_this9.isInitialSyncComplete()) {\n        var _event = _this9.store.getAccountData(eventType);\n        if (!_event) {\n          return null;\n        }\n        // The network version below returns just the content, so this branch\n        // does the same to match.\n        return _event.getContent();\n      }\n      var path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n        $userId: _this9.credentials.userId,\n        $type: eventType\n      });\n      try {\n        return yield _this9.http.authedRequest(Method.Get, path);\n      } catch (e) {\n        var _data;\n        if (((_data = e.data) === null || _data === void 0 ? void 0 : _data.errcode) === \"M_NOT_FOUND\") {\n          return null;\n        }\n        throw e;\n      }\n    })();\n  }\n  deleteAccountData(eventType) {\n    var _this0 = this;\n    return _asyncToGenerator(function* () {\n      var msc3391DeleteAccountDataServerSupport = _this0.canSupport.get(Feature.AccountDataDeletion);\n      // if deletion is not supported overwrite with empty content\n      if (msc3391DeleteAccountDataServerSupport === ServerSupport.Unsupported) {\n        yield _this0.setAccountData(eventType, {});\n        return;\n      }\n      var path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n        $userId: _this0.getSafeUserId(),\n        $type: eventType\n      });\n      var options = msc3391DeleteAccountDataServerSupport === ServerSupport.Unstable ? {\n        prefix: \"/_matrix/client/unstable/org.matrix.msc3391\"\n      } : undefined;\n      return yield _this0.http.authedRequest(Method.Delete, path, undefined, undefined, options);\n    })();\n  }\n\n  /**\n   * Gets the users that are ignored by this client\n   * @returns The array of users that are ignored (empty if none)\n   */\n  getIgnoredUsers() {\n    var event = this.getAccountData(EventType.IgnoredUserList);\n    if (!(event !== null && event !== void 0 && event.getContent()[\"ignored_users\"])) return [];\n    return Object.keys(event.getContent()[\"ignored_users\"]);\n  }\n\n  /**\n   * Sets the users that the current user should ignore.\n   * @param userIds - the user IDs to ignore\n   * @returns Promise which resolves: an empty object\n   * @returns Rejects: with an error response.\n   */\n  setIgnoredUsers(userIds) {\n    var content = {\n      ignored_users: {}\n    };\n    userIds.forEach(u => {\n      content.ignored_users[u] = {};\n    });\n    return this.setAccountData(EventType.IgnoredUserList, content);\n  }\n\n  /**\n   * Gets whether or not a specific user is being ignored by this client.\n   * @param userId - the user ID to check\n   * @returns true if the user is ignored, false otherwise\n   */\n  isUserIgnored(userId) {\n    return this.getIgnoredUsers().includes(userId);\n  }\n\n  /**\n   * Join a room. If you have already joined the room, this will no-op.\n   * @param roomIdOrAlias - The room ID or room alias to join.\n   * @param opts - Options when joining the room.\n   * @returns Promise which resolves: Room object.\n   * @returns Rejects: with an error response.\n   */\n  joinRoom(roomIdOrAlias) {\n    var _arguments2 = arguments,\n      _this1 = this;\n    return _asyncToGenerator(function* () {\n      var _roomMember$events$me, _roomMember$events$me2;\n      var opts = _arguments2.length > 1 && _arguments2[1] !== undefined ? _arguments2[1] : {};\n      var room = _this1.getRoom(roomIdOrAlias);\n      var roomMember = room === null || room === void 0 ? void 0 : room.getMember(_this1.getSafeUserId());\n      var preJoinMembership = roomMember === null || roomMember === void 0 ? void 0 : roomMember.membership;\n\n      // If we were invited to the room, the ID of the user that sent the invite. Otherwise, `null`.\n      var inviter = preJoinMembership == KnownMembership.Invite ? (_roomMember$events$me = roomMember === null || roomMember === void 0 || (_roomMember$events$me2 = roomMember.events.member) === null || _roomMember$events$me2 === void 0 ? void 0 : _roomMember$events$me2.getSender()) !== null && _roomMember$events$me !== void 0 ? _roomMember$events$me : null : null;\n      _this1.logger.debug(\"joinRoom[\".concat(roomIdOrAlias, \"]: preJoinMembership=\").concat(preJoinMembership, \", inviter=\").concat(inviter, \", opts=\").concat(JSON.stringify(opts)));\n      if (preJoinMembership == KnownMembership.Join) return room;\n      var signPromise = Promise.resolve();\n      if (opts.inviteSignUrl) {\n        var _url = new URL(opts.inviteSignUrl);\n        _url.searchParams.set(\"mxid\", _this1.credentials.userId);\n        signPromise = _this1.http.requestOtherUrl(Method.Post, _url);\n      }\n      var queryParams = {};\n      if (opts.viaServers) {\n        // server_name has been deprecated in favour of via with Matrix >1.11 (MSC4156)\n        // We only use the first 3 servers, to avoid URI length issues.\n        queryParams.via = queryParams.server_name = opts.viaServers.slice(0, 3);\n      }\n      var data = {};\n      var signedInviteObj = yield signPromise;\n      if (signedInviteObj) {\n        data.third_party_signed = signedInviteObj;\n      }\n      var path = utils.encodeUri(\"/join/$roomid\", {\n        $roomid: roomIdOrAlias\n      });\n      var res = yield _this1.http.authedRequest(Method.Post, path, queryParams, data);\n      var roomId = res.room_id;\n      if (opts.acceptSharedHistory && inviter && _this1.cryptoBackend) {\n        // Try to accept the room key bundle specified in a `m.room_key_bundle` to-device message we (might have) already received.\n        var bundleDownloaded = yield _this1.cryptoBackend.maybeAcceptKeyBundle(roomId, inviter);\n        // If this fails, i.e. we haven't received this message yet, we need to wait until the to-device message arrives.\n        if (!bundleDownloaded) {\n          _this1.cryptoBackend.markRoomAsPendingKeyBundle(roomId, inviter);\n        }\n      }\n\n      // In case we were originally given an alias, check the room cache again\n      // with the resolved ID - this method is supposed to no-op if we already\n      // were in the room, after all.\n      var resolvedRoom = _this1.getRoom(roomId);\n      if (resolvedRoom !== null && resolvedRoom !== void 0 && resolvedRoom.hasMembershipState(_this1.credentials.userId, KnownMembership.Join)) return resolvedRoom;\n      var syncApi = new SyncApi(_this1, _this1.clientOpts, _this1.buildSyncApiOptions());\n      return syncApi.createRoom(roomId);\n    })();\n  }\n\n  /**\n   * Knock a room. If you have already knocked the room, this will no-op.\n   * @param roomIdOrAlias - The room ID or room alias to knock.\n   * @param opts - Options when knocking the room.\n   * @returns Promise which resolves: `{room_id: {string}}`\n   * @returns Rejects: with an error response.\n   */\n  knockRoom(roomIdOrAlias) {\n    var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    var room = this.getRoom(roomIdOrAlias);\n    if (room !== null && room !== void 0 && room.hasMembershipState(this.credentials.userId, KnownMembership.Knock)) {\n      return Promise.resolve({\n        room_id: room.roomId\n      });\n    }\n    var path = utils.encodeUri(\"/knock/$roomIdOrAlias\", {\n      $roomIdOrAlias: roomIdOrAlias\n    });\n    var queryParams = {};\n    if (opts.viaServers) {\n      // We only use the first 3 servers, to avoid URI length issues.\n      var viaServers = Array.isArray(opts.viaServers) ? opts.viaServers.slice(0, 3) : [opts.viaServers];\n      // server_name has been deprecated in favour of via with Matrix >1.11 (MSC4156)\n      queryParams.server_name = viaServers;\n      queryParams.via = viaServers;\n    }\n    var body = {};\n    if (opts.reason) {\n      body.reason = opts.reason;\n    }\n    return this.http.authedRequest(Method.Post, path, queryParams, body);\n  }\n\n  /**\n   * Resend an event. Will also retry any to-device messages waiting to be sent.\n   * @param event - The event to resend.\n   * @param room - Optional. The room the event is in. Will update the\n   * timeline entry if provided.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  resendEvent(event, room) {\n    // also kick the to-device queue to retry\n    this.toDeviceMessageQueue.sendQueue();\n    this.updatePendingEventStatus(room, event, EventStatus.SENDING);\n    return this.encryptAndSendEvent(room, event);\n  }\n\n  /**\n   * Cancel a queued or unsent event.\n   *\n   * @param event -   Event to cancel\n   * @throws Error if the event is not in QUEUED, NOT_SENT or ENCRYPTING state\n   */\n  cancelPendingEvent(event) {\n    if (![EventStatus.QUEUED, EventStatus.NOT_SENT, EventStatus.ENCRYPTING].includes(event.status)) {\n      throw new Error(\"cannot cancel an event with status \" + event.status);\n    }\n\n    // If the event is currently being encrypted then remove it from the pending list, to indicate that it should\n    // not be sent.\n    if (event.status === EventStatus.ENCRYPTING) {\n      this.eventsBeingEncrypted.delete(event.getId());\n    } else if (this.scheduler && event.status === EventStatus.QUEUED) {\n      // tell the scheduler to forget about it, if it's queued\n      this.scheduler.removeEventFromQueue(event);\n    }\n\n    // then tell the room about the change of state, which will remove it\n    // from the room's list of pending events.\n    var room = this.getRoom(event.getRoomId());\n    this.updatePendingEventStatus(room, event, EventStatus.CANCELLED);\n  }\n\n  /**\n   * @returns Promise which resolves: TODO\n   * @returns Rejects: with an error response.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  setRoomName(roomId, name) {\n    return this.sendStateEvent(roomId, EventType.RoomName, {\n      name: name\n    });\n  }\n\n  /**\n   * @param roomId - The room to update the topic in.\n   * @param topic - The plaintext topic. May be empty to remove the topic.\n   * @param htmlTopic - Optional.\n   * @returns Promise which resolves: TODO\n   * @returns Rejects: with an error response.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  setRoomTopic(roomId, topic, htmlTopic) {\n    var content = ContentHelpers.makeTopicContent(topic, htmlTopic);\n    return this.sendStateEvent(roomId, EventType.RoomTopic, content);\n  }\n\n  /**\n   * @returns Promise which resolves: to an object keyed by tagId with objects containing a numeric order field.\n   * @returns Rejects: with an error response.\n   */\n  getRoomTags(roomId) {\n    var path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags\", {\n      $userId: this.credentials.userId,\n      $roomId: roomId\n    });\n    return this.http.authedRequest(Method.Get, path);\n  }\n\n  /**\n   * @param tagName - name of room tag to be set\n   * @param metadata - associated with that tag to be stored\n   * @returns Promise which resolves: to an empty object\n   * @returns Rejects: with an error response.\n   */\n  setRoomTag(roomId, tagName) {\n    var metadata = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n    var path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags/$tag\", {\n      $userId: this.credentials.userId,\n      $roomId: roomId,\n      $tag: tagName\n    });\n    return this.http.authedRequest(Method.Put, path, undefined, metadata);\n  }\n\n  /**\n   * @param tagName - name of room tag to be removed\n   * @returns Promise which resolves: to an empty object\n   * @returns Rejects: with an error response.\n   */\n  deleteRoomTag(roomId, tagName) {\n    var path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags/$tag\", {\n      $userId: this.credentials.userId,\n      $roomId: roomId,\n      $tag: tagName\n    });\n    return this.http.authedRequest(Method.Delete, path);\n  }\n\n  /**\n   * @param eventType - event type to be set\n   * @param content - event content\n   * @returns Promise which resolves: to an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n  setRoomAccountData(roomId, eventType, content) {\n    var path = utils.encodeUri(\"/user/$userId/rooms/$roomId/account_data/$type\", {\n      $userId: this.credentials.userId,\n      $roomId: roomId,\n      $type: eventType\n    });\n    return this.http.authedRequest(Method.Put, path, undefined, content);\n  }\n\n  /**\n   * Set a power level to one or multiple users.\n   * Will apply changes atop of current power level event from local state if running & synced, falling back\n   * to fetching latest from the `/state/` API.\n   * @param roomId - the room to update power levels in\n   * @param userId - the ID of the user or users to update power levels of\n   * @param powerLevel - the numeric power level to update given users to\n   * @returns Promise which resolves: to an ISendEventResponse object\n   * @returns Rejects: with an error response.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  setPowerLevel(roomId, userId, powerLevel) {\n    var _this10 = this;\n    return _asyncToGenerator(function* () {\n      var _content;\n      var content;\n      if (_this10.clientRunning && _this10.isInitialSyncComplete()) {\n        var _this10$getRoom;\n        content = (_this10$getRoom = _this10.getRoom(roomId)) === null || _this10$getRoom === void 0 || (_this10$getRoom = _this10$getRoom.currentState) === null || _this10$getRoom === void 0 || (_this10$getRoom = _this10$getRoom.getStateEvents(EventType.RoomPowerLevels, \"\")) === null || _this10$getRoom === void 0 ? void 0 : _this10$getRoom.getContent();\n      }\n      if (!content) {\n        try {\n          content = yield _this10.getStateEvent(roomId, EventType.RoomPowerLevels, \"\");\n        } catch (e) {\n          // It is possible for a Matrix room to not have a power levels event\n          if (e instanceof MatrixError && e.errcode === \"M_NOT_FOUND\") {\n            content = {};\n          } else {\n            throw e;\n          }\n        }\n      }\n\n      // take a copy of the content to ensure we don't corrupt\n      // existing client state with a failed power level change\n      content = utils.deepCopy(content);\n      if (!((_content = content) !== null && _content !== void 0 && _content.users)) {\n        content.users = {};\n      }\n      var users = Array.isArray(userId) ? userId : [userId];\n      for (var user of users) {\n        if (powerLevel == null) {\n          delete content.users[user];\n        } else {\n          content.users[user] = powerLevel;\n        }\n      }\n      return _this10.sendStateEvent(roomId, EventType.RoomPowerLevels, content, \"\");\n    })();\n  }\n\n  /**\n   * Create an m.beacon_info event\n   * @returns\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  // eslint-disable-next-line @typescript-eslint/naming-convention\n  unstable_createLiveBeacon(roomId, beaconInfoContent) {\n    var _this11 = this;\n    return _asyncToGenerator(function* () {\n      return _this11.unstable_setLiveBeacon(roomId, beaconInfoContent);\n    })();\n  }\n\n  /**\n   * Upsert a live beacon event\n   * using a specific m.beacon_info.* event variable type\n   * @param roomId - string\n   * @returns\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  // eslint-disable-next-line @typescript-eslint/naming-convention\n  unstable_setLiveBeacon(roomId, beaconInfoContent) {\n    var _this12 = this;\n    return _asyncToGenerator(function* () {\n      return _this12.sendStateEvent(roomId, M_BEACON_INFO.name, beaconInfoContent, _this12.getUserId());\n    })();\n  }\n\n  /**\n   * Send a Matrix timeline event.\n   * @param roomId The room to send to.\n   * @param eventType The event type.\n   * @param content The event content.\n   * @param txnId An optional ID to deduplicate requests in case of repeated attempts.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n\n  sendEvent(roomId, threadIdOrEventType, eventTypeOrContent, contentOrTxnId, txnIdOrVoid) {\n    var threadId;\n    var eventType;\n    var content;\n    var txnId;\n    if (!(threadIdOrEventType !== null && threadIdOrEventType !== void 0 && threadIdOrEventType.startsWith(EVENT_ID_PREFIX)) && threadIdOrEventType !== null) {\n      txnId = contentOrTxnId;\n      content = eventTypeOrContent;\n      eventType = threadIdOrEventType;\n      threadId = null;\n    } else {\n      txnId = txnIdOrVoid;\n      content = contentOrTxnId;\n      eventType = eventTypeOrContent;\n      threadId = threadIdOrEventType;\n    }\n    this.addThreadRelationIfNeeded(content, threadId, roomId);\n    return this.sendCompleteEvent({\n      roomId,\n      threadId,\n      eventObject: {\n        type: eventType,\n        content\n      },\n      txnId\n    });\n  }\n\n  /**\n   * If we expect that an event is part of a thread but is missing the relation\n   * we need to add it manually, as well as the reply fallback\n   */\n  addThreadRelationIfNeeded(content, threadId, roomId) {\n    var _content$mRelates_to;\n    if (threadId && !((_content$mRelates_to = content[\"m.relates_to\"]) !== null && _content$mRelates_to !== void 0 && _content$mRelates_to.rel_type)) {\n      var _content$mRelates_to2, _this$getRoom;\n      var isReply = !!((_content$mRelates_to2 = content[\"m.relates_to\"]) !== null && _content$mRelates_to2 !== void 0 && _content$mRelates_to2[\"m.in_reply_to\"]);\n      content[\"m.relates_to\"] = _objectSpread(_objectSpread({}, content[\"m.relates_to\"]), {}, {\n        rel_type: THREAD_RELATION_TYPE.name,\n        event_id: threadId,\n        // Set is_falling_back to true unless this is actually intended to be a reply\n        is_falling_back: !isReply\n      });\n      var thread = (_this$getRoom = this.getRoom(roomId)) === null || _this$getRoom === void 0 ? void 0 : _this$getRoom.getThread(threadId);\n      if (thread && !isReply) {\n        var _thread$lastReply$get, _thread$lastReply;\n        content[\"m.relates_to\"][\"m.in_reply_to\"] = {\n          event_id: (_thread$lastReply$get = (_thread$lastReply = thread.lastReply(ev => {\n            return ev.isRelation(THREAD_RELATION_TYPE.name) && !ev.status;\n          })) === null || _thread$lastReply === void 0 ? void 0 : _thread$lastReply.getId()) !== null && _thread$lastReply$get !== void 0 ? _thread$lastReply$get : threadId\n        };\n      }\n    }\n  }\n\n  /**\n   * @param eventObject - An object with the partial structure of an event, to which event_id, user_id, room_id and origin_server_ts will be added.\n   * @param txnId - Optional.\n   * @returns Promise which resolves: to an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n\n  /**\n   * Sends a delayed event (MSC4140).\n   * @param eventObject - An object with the partial structure of an event, to which event_id, user_id, room_id and origin_server_ts will be added.\n   * @param delayOpts - Properties of the delay for this event.\n   * @param txnId - Optional.\n   * @returns Promise which resolves: to an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n\n  sendCompleteEvent(_ref3) {\n    var {\n      roomId,\n      threadId,\n      eventObject,\n      delayOpts,\n      queryDict,\n      txnId\n    } = _ref3;\n    if (!txnId) {\n      txnId = this.makeTxnId();\n    }\n\n    // We always construct a MatrixEvent when sending because the store and scheduler use them.\n    // We'll extract the params back out if it turns out the client has no scheduler or store.\n    var localEvent = new MatrixEvent(Object.assign(eventObject, {\n      event_id: \"~\" + roomId + \":\" + txnId,\n      user_id: this.credentials.userId,\n      sender: this.credentials.userId,\n      room_id: roomId,\n      origin_server_ts: new Date().getTime()\n    }));\n    var room = this.getRoom(roomId);\n    var thread = threadId ? room === null || room === void 0 ? void 0 : room.getThread(threadId) : undefined;\n    if (thread) {\n      localEvent.setThread(thread);\n    }\n    if (!delayOpts) {\n      // set up re-emitter for this new event - this is normally the job of EventMapper but we don't use it here\n      this.reEmitter.reEmit(localEvent, [MatrixEventEvent.Replaced, MatrixEventEvent.VisibilityChange]);\n      room === null || room === void 0 || room.reEmitter.reEmit(localEvent, [MatrixEventEvent.BeforeRedaction]);\n    }\n\n    // if this is a relation or redaction of an event\n    // that hasn't been sent yet (e.g. with a local id starting with a ~)\n    // then listen for the remote echo of that event so that by the time\n    // this event does get sent, we have the correct event_id\n    var targetId = localEvent.getAssociatedId();\n    if (targetId !== null && targetId !== void 0 && targetId.startsWith(\"~\")) {\n      var target = room === null || room === void 0 ? void 0 : room.getPendingEvents().find(e => e.getId() === targetId);\n      target === null || target === void 0 || target.once(MatrixEventEvent.LocalEventIdReplaced, () => {\n        localEvent.updateAssociatedId(target.getId());\n      });\n    }\n    var type = localEvent.getType();\n    this.logger.debug(\"sendEvent of type \".concat(type, \" in \").concat(roomId, \" with txnId \").concat(txnId).concat(delayOpts ? \" (delayed event)\" : \"\").concat(queryDict ? \" query params: \" + JSON.stringify(queryDict) : \"\"));\n    localEvent.setTxnId(txnId);\n    localEvent.setStatus(EventStatus.SENDING);\n\n    // TODO: separate store for delayed events?\n    if (!delayOpts) {\n      // add this event immediately to the local store as 'sending'.\n      room === null || room === void 0 || room.addPendingEvent(localEvent, txnId);\n\n      // addPendingEvent can change the state to NOT_SENT if it believes\n      // that there's other events that have failed. We won't bother to\n      // try sending the event if the state has changed as such.\n      if (localEvent.status === EventStatus.NOT_SENT) {\n        return Promise.reject(new Error(\"Event blocked by other events not yet sent\"));\n      }\n      return this.encryptAndSendEvent(room, localEvent, queryDict);\n    } else {\n      return this.encryptAndSendEvent(room, localEvent, delayOpts, queryDict);\n    }\n  }\n\n  /**\n   * encrypts the event if necessary; adds the event to the queue, or sends it; marks the event as sent/unsent\n   * @returns returns a promise which resolves with the result of the send request\n   */\n\n  /**\n   * Simply sends a delayed event without encrypting it.\n   * TODO: Allow encrypted delayed events, and encrypt them properly\n   * @param delayOpts - Properties of the delay for this event.\n   * @returns returns a promise which resolves with the result of the delayed send request\n   */\n\n  encryptAndSendEvent(room, event, delayOptsOrQuery, queryDict) {\n    var _this13 = this;\n    return _asyncToGenerator(function* () {\n      var queryOpts = queryDict;\n      if (delayOptsOrQuery && isSendDelayedEventRequestOpts(delayOptsOrQuery)) {\n        return _this13.sendEventHttpRequest(event, delayOptsOrQuery, queryOpts);\n      } else if (!queryOpts) {\n        queryOpts = delayOptsOrQuery;\n      }\n      try {\n        var cancelled;\n        _this13.eventsBeingEncrypted.add(event.getId());\n        try {\n          yield _this13.encryptEventIfNeeded(event, room !== null && room !== void 0 ? room : undefined);\n        } finally {\n          cancelled = !_this13.eventsBeingEncrypted.delete(event.getId());\n        }\n        if (cancelled) {\n          // cancelled via MatrixClient::cancelPendingEvent\n          return {};\n        }\n\n        // encryptEventIfNeeded may have updated the status from SENDING to ENCRYPTING. If so, we need\n        // to put it back.\n        if (event.status === EventStatus.ENCRYPTING) {\n          _this13.updatePendingEventStatus(room, event, EventStatus.SENDING);\n        }\n        var promise = null;\n        if (_this13.scheduler) {\n          // if this returns a promise then the scheduler has control now and will\n          // resolve/reject when it is done. Internally, the scheduler will invoke\n          // processFn which is set to this._sendEventHttpRequest so the same code\n          // path is executed regardless.\n          promise = _this13.scheduler.queueEvent(event);\n          if (promise && _this13.scheduler.getQueueForEvent(event).length > 1) {\n            // event is processed FIFO so if the length is 2 or more we know\n            // this event is stuck behind an earlier event.\n            _this13.updatePendingEventStatus(room, event, EventStatus.QUEUED);\n          }\n        }\n        if (!promise) {\n          promise = _this13.sendEventHttpRequest(event, queryOpts);\n          if (room) {\n            promise = promise.then(res => {\n              room.updatePendingEvent(event, EventStatus.SENT, res[\"event_id\"]);\n              return res;\n            });\n          }\n        }\n        return yield promise;\n      } catch (err) {\n        _this13.logger.error(\"Error sending event\", err);\n        try {\n          // set the error on the event before we update the status:\n          // updating the status emits the event, so the state should be\n          // consistent at that point.\n          event.error = err;\n          _this13.updatePendingEventStatus(room, event, EventStatus.NOT_SENT);\n        } catch (e) {\n          _this13.logger.error(\"Exception in error handler!\", e);\n        }\n        if (err instanceof MatrixError) {\n          err.event = event;\n        }\n        throw err;\n      }\n    })();\n  }\n  encryptEventIfNeeded(event, room) {\n    var _this14 = this;\n    return _asyncToGenerator(function* () {\n      // If the room is unknown, we cannot encrypt for it\n      if (!room) return;\n      if (!(yield _this14.shouldEncryptEventForRoom(event, room))) return;\n      if (!_this14.cryptoBackend && _this14.usingExternalCrypto) {\n        // The client has opted to allow sending messages to encrypted\n        // rooms even if the room is encrypted, and we haven't set up\n        // crypto. This is useful for users of matrix-org/pantalaimon\n        return;\n      }\n      if (!_this14.cryptoBackend) {\n        throw new Error(\"This room is configured to use encryption, but your client does not support encryption.\");\n      }\n      _this14.updatePendingEventStatus(room, event, EventStatus.ENCRYPTING);\n      yield _this14.cryptoBackend.encryptEvent(event, room);\n    })();\n  }\n\n  /**\n   * Determine whether a given event should be encrypted when we send it to the given room.\n   *\n   * This takes into account event type and room configuration.\n   */\n  shouldEncryptEventForRoom(event, room) {\n    var _this15 = this;\n    return _asyncToGenerator(function* () {\n      var _this15$cryptoBackend;\n      if (event.isEncrypted()) {\n        // this event has already been encrypted; this happens if the\n        // encryption step succeeded, but the send step failed on the first\n        // attempt.\n        return false;\n      }\n      if (event.getType() === EventType.Reaction) {\n        // For reactions, there is a very little gained by encrypting the entire\n        // event, as relation data is already kept in the clear. Event\n        // encryption for a reaction effectively only obscures the event type,\n        // but the purpose is still obvious from the relation data, so nothing\n        // is really gained. It also causes quite a few problems, such as:\n        //   * triggers notifications via default push rules\n        //   * prevents server-side bundling for reactions\n        // The reaction key / content / emoji value does warrant encrypting, but\n        // this will be handled separately by encrypting just this value.\n        // See https://github.com/matrix-org/matrix-doc/pull/1849#pullrequestreview-248763642\n        return false;\n      }\n      if (event.isRedaction()) {\n        // Redactions do not support encryption in the spec at this time.\n        // Whilst it mostly worked in some clients, it wasn't compliant.\n        return false;\n      }\n\n      // If the room has an m.room.encryption event, we should encrypt.\n      if (room.hasEncryptionStateEvent()) return true;\n\n      // If we have a crypto impl, and *it* thinks we should encrypt, then we should.\n      if (yield (_this15$cryptoBackend = _this15.cryptoBackend) === null || _this15$cryptoBackend === void 0 ? void 0 : _this15$cryptoBackend.isEncryptionEnabledInRoom(room.roomId)) return true;\n\n      // Otherwise, no need to encrypt.\n      return false;\n    })();\n  }\n\n  /**\n   * Returns the eventType that should be used taking encryption into account\n   * for a given eventType.\n   * @param roomId - the room for the events `eventType` relates to\n   * @param eventType - the event type\n   * @returns the event type taking encryption into account\n   */\n  getEncryptedIfNeededEventType(roomId, eventType) {\n    var _this$getRoom2;\n    if (eventType === EventType.Reaction) return eventType;\n    return (_this$getRoom2 = this.getRoom(roomId)) !== null && _this$getRoom2 !== void 0 && _this$getRoom2.hasEncryptionStateEvent() ? EventType.RoomMessageEncrypted : eventType;\n  }\n  updatePendingEventStatus(room, event, newStatus) {\n    if (room) {\n      room.updatePendingEvent(event, newStatus);\n    } else {\n      event.setStatus(newStatus);\n    }\n  }\n  sendEventHttpRequest(event, queryOrDelayOpts, queryDict) {\n    var txnId = event.getTxnId();\n    if (!txnId) {\n      txnId = this.makeTxnId();\n      event.setTxnId(txnId);\n    }\n    var pathParams = {\n      $roomId: event.getRoomId(),\n      $eventType: event.getWireType(),\n      $stateKey: event.getStateKey(),\n      $txnId: txnId\n    };\n    var path;\n    if (event.isState()) {\n      var pathTemplate = \"/rooms/$roomId/state/$eventType\";\n      if (event.getStateKey() && event.getStateKey().length > 0) {\n        pathTemplate = \"/rooms/$roomId/state/$eventType/$stateKey\";\n      }\n      path = utils.encodeUri(pathTemplate, pathParams);\n    } else if (event.isRedaction() && event.event.redacts) {\n      var _pathTemplate = \"/rooms/$roomId/redact/$redactsEventId/$txnId\";\n      path = utils.encodeUri(_pathTemplate, _objectSpread({\n        $redactsEventId: event.event.redacts\n      }, pathParams));\n    } else {\n      path = utils.encodeUri(\"/rooms/$roomId/send/$eventType/$txnId\", pathParams);\n    }\n    var delayOpts = queryOrDelayOpts && isSendDelayedEventRequestOpts(queryOrDelayOpts) ? queryOrDelayOpts : undefined;\n    var queryOpts = !delayOpts ? queryOrDelayOpts : queryDict;\n    var content = event.getWireContent();\n    if (delayOpts) {\n      return this.http.authedRequest(Method.Put, path, _objectSpread(_objectSpread({}, getUnstableDelayQueryOpts(delayOpts)), queryOpts), content);\n    } else {\n      return this.http.authedRequest(Method.Put, path, queryOpts, content).then(res => {\n        this.logger.debug(\"Event sent to \".concat(event.getRoomId(), \" with event id \").concat(res.event_id));\n        return res;\n      });\n    }\n  }\n\n  /**\n   * @param txnId -  transaction id. One will be made up if not supplied.\n   * @param opts - Redact options\n   * @returns Promise which resolves: TODO\n   * @returns Rejects: with an error response.\n   * @throws Error if called with `with_rel_types` (MSC3912) but the server does not support it.\n   *         Callers should check whether the server supports MSC3912 via `MatrixClient.canSupport`.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n\n  redactEvent(roomId, threadId, eventId, txnId, opts) {\n    var _eventId, _opts, _opts2;\n    if (!((_eventId = eventId) !== null && _eventId !== void 0 && _eventId.startsWith(EVENT_ID_PREFIX))) {\n      opts = txnId;\n      txnId = eventId;\n      eventId = threadId;\n      threadId = null;\n    }\n    var reason = (_opts = opts) === null || _opts === void 0 ? void 0 : _opts.reason;\n    var content = {\n      reason\n    };\n    if (((_opts2 = opts) === null || _opts2 === void 0 ? void 0 : _opts2.with_rel_types) !== undefined) {\n      if (this.canSupport.get(Feature.RelationBasedRedactions) === ServerSupport.Unsupported) {\n        throw new Error(\"Server does not support relation based redactions \" + \"roomId \".concat(roomId, \" eventId \").concat(eventId, \" txnId: \").concat(txnId, \" threadId \").concat(threadId));\n      }\n      var withRelTypesPropName = this.canSupport.get(Feature.RelationBasedRedactions) === ServerSupport.Stable ? MSC3912_RELATION_BASED_REDACTIONS_PROP.stable : MSC3912_RELATION_BASED_REDACTIONS_PROP.unstable;\n      content[withRelTypesPropName] = opts.with_rel_types;\n    }\n    return this.sendCompleteEvent({\n      roomId,\n      threadId,\n      eventObject: {\n        type: EventType.RoomRedaction,\n        content,\n        redacts: eventId\n      },\n      txnId: txnId\n    });\n  }\n\n  /**\n   * @param txnId - Optional.\n   * @returns Promise which resolves: to an ISendEventResponse object\n   * @returns Rejects: with an error response.\n   */\n\n  sendMessage(roomId, threadId, content, txnId) {\n    if (typeof threadId !== \"string\" && threadId !== null) {\n      txnId = content;\n      content = threadId;\n      threadId = null;\n    }\n    var eventType = EventType.RoomMessage;\n    var sendContent = content;\n    return this.sendEvent(roomId, threadId, eventType, sendContent, txnId);\n  }\n\n  /**\n   * @param txnId - Optional.\n   * @returns\n   * @returns Rejects: with an error response.\n   */\n\n  sendTextMessage(roomId, threadId, body, txnId) {\n    var _threadId;\n    if (!((_threadId = threadId) !== null && _threadId !== void 0 && _threadId.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {\n      txnId = body;\n      body = threadId;\n      threadId = null;\n    }\n    var content = ContentHelpers.makeTextMessage(body);\n    return this.sendMessage(roomId, threadId, content, txnId);\n  }\n\n  /**\n   * @param txnId - Optional.\n   * @returns Promise which resolves: to a ISendEventResponse object\n   * @returns Rejects: with an error response.\n   */\n\n  sendNotice(roomId, threadId, body, txnId) {\n    var _threadId2;\n    if (!((_threadId2 = threadId) !== null && _threadId2 !== void 0 && _threadId2.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {\n      txnId = body;\n      body = threadId;\n      threadId = null;\n    }\n    var content = ContentHelpers.makeNotice(body);\n    return this.sendMessage(roomId, threadId, content, txnId);\n  }\n\n  /**\n   * @param txnId - Optional.\n   * @returns Promise which resolves: to a ISendEventResponse object\n   * @returns Rejects: with an error response.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n\n  sendEmoteMessage(roomId, threadId, body, txnId) {\n    var _threadId3;\n    if (!((_threadId3 = threadId) !== null && _threadId3 !== void 0 && _threadId3.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {\n      txnId = body;\n      body = threadId;\n      threadId = null;\n    }\n    var content = ContentHelpers.makeEmoteMessage(body);\n    return this.sendMessage(roomId, threadId, content, txnId);\n  }\n\n  /**\n   * @returns Promise which resolves: to a ISendEventResponse object\n   * @returns Rejects: with an error response.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n\n  sendImageMessage(roomId, threadId, url, info) {\n    var _threadId4;\n    var text = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : \"Image\";\n    if (!((_threadId4 = threadId) !== null && _threadId4 !== void 0 && _threadId4.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {\n      text = info || \"Image\";\n      info = url;\n      url = threadId;\n      threadId = null;\n    }\n    var content = {\n      msgtype: MsgType.Image,\n      url: url,\n      info: info,\n      body: text\n    };\n    return this.sendMessage(roomId, threadId, content);\n  }\n\n  /**\n   * @returns Promise which resolves: to a ISendEventResponse object\n   * @returns Rejects: with an error response.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n\n  sendStickerMessage(roomId, threadId, url, info) {\n    var _threadId5;\n    var text = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : \"Sticker\";\n    if (!((_threadId5 = threadId) !== null && _threadId5 !== void 0 && _threadId5.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {\n      text = info || \"Sticker\";\n      info = url;\n      url = threadId;\n      threadId = null;\n    }\n    var content = {\n      url: url,\n      info: info,\n      body: text\n    };\n    return this.sendEvent(roomId, threadId, EventType.Sticker, content);\n  }\n\n  /**\n   * @returns Promise which resolves: to a ISendEventResponse object\n   * @returns Rejects: with an error response.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n\n  sendHtmlMessage(roomId, threadId, body, htmlBody) {\n    var _threadId6;\n    if (!((_threadId6 = threadId) !== null && _threadId6 !== void 0 && _threadId6.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {\n      htmlBody = body;\n      body = threadId;\n      threadId = null;\n    }\n    var content = ContentHelpers.makeHtmlMessage(body, htmlBody);\n    return this.sendMessage(roomId, threadId, content);\n  }\n\n  /**\n   * @returns Promise which resolves: to a ISendEventResponse object\n   * @returns Rejects: with an error response.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n\n  sendHtmlNotice(roomId, threadId, body, htmlBody) {\n    var _threadId7;\n    if (!((_threadId7 = threadId) !== null && _threadId7 !== void 0 && _threadId7.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {\n      htmlBody = body;\n      body = threadId;\n      threadId = null;\n    }\n    var content = ContentHelpers.makeHtmlNotice(body, htmlBody);\n    return this.sendMessage(roomId, threadId, content);\n  }\n\n  /**\n   * @returns Promise which resolves: to a ISendEventResponse object\n   * @returns Rejects: with an error response.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n\n  sendHtmlEmote(roomId, threadId, body, htmlBody) {\n    var _threadId8;\n    if (!((_threadId8 = threadId) !== null && _threadId8 !== void 0 && _threadId8.startsWith(EVENT_ID_PREFIX)) && threadId !== null) {\n      htmlBody = body;\n      body = threadId;\n      threadId = null;\n    }\n    var content = ContentHelpers.makeHtmlEmote(body, htmlBody);\n    return this.sendMessage(roomId, threadId, content);\n  }\n\n  /**\n   * Send a delayed timeline event.\n   *\n   * Note: This endpoint is unstable, and can throw an `Error`.\n   *   Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  // eslint-disable-next-line\n  _unstable_sendDelayedEvent(roomId, delayOpts, threadId, eventType, content, txnId) {\n    var _this16 = this;\n    return _asyncToGenerator(function* () {\n      if (!(yield _this16.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n        throw new UnsupportedDelayedEventsEndpointError(\"Server does not support the delayed events API\", \"sendDelayedEvent\");\n      }\n      _this16.addThreadRelationIfNeeded(content, threadId, roomId);\n      return _this16.sendCompleteEvent({\n        roomId,\n        threadId,\n        eventObject: {\n          type: eventType,\n          content\n        },\n        delayOpts,\n        txnId\n      });\n    })();\n  }\n\n  /**\n   * Send a delayed sticky timeline event.\n   *\n   * Note: This endpoint is unstable, and can throw an `Error`.\n   *   Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) and\n   *   [MSC4354](https://github.com/matrix-org/matrix-spec-proposals/pull/4354) for more details.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  // eslint-disable-next-line\n  _unstable_sendStickyDelayedEvent(roomId, stickDuration, delayOpts, threadId, eventType, content, txnId) {\n    var _this17 = this;\n    return _asyncToGenerator(function* () {\n      if (!(yield _this17.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n        throw new UnsupportedDelayedEventsEndpointError(\"Server does not support the delayed events API\", \"getDelayedEvents\");\n      }\n      if (!(yield _this17.doesServerSupportUnstableFeature(UNSTABLE_MSC4354_STICKY_EVENTS))) {\n        throw new UnsupportedStickyEventsEndpointError(\"Server does not support the sticky events\", \"sendStickyEvent\");\n      }\n      _this17.addThreadRelationIfNeeded(content, threadId, roomId);\n      return _this17.sendCompleteEvent({\n        roomId,\n        threadId,\n        eventObject: {\n          type: eventType,\n          content\n        },\n        queryDict: {\n          \"org.matrix.msc4354.sticky_duration_ms\": stickDuration\n        },\n        delayOpts,\n        txnId\n      });\n    })();\n  }\n\n  /**\n   * Send a delayed state event.\n   *\n   * Note: This endpoint is unstable, and can throw an `Error`.\n   *   Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  // eslint-disable-next-line\n  _unstable_sendDelayedStateEvent(roomId, delayOpts, eventType, content) {\n    var _arguments3 = arguments,\n      _this18 = this;\n    return _asyncToGenerator(function* () {\n      var stateKey = _arguments3.length > 4 && _arguments3[4] !== undefined ? _arguments3[4] : \"\";\n      var opts = _arguments3.length > 5 && _arguments3[5] !== undefined ? _arguments3[5] : {};\n      if (!(yield _this18.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n        throw new UnsupportedDelayedEventsEndpointError(\"Server does not support the delayed events API\", \"sendDelayedStateEvent\");\n      }\n      var pathParams = {\n        $roomId: roomId,\n        $eventType: eventType,\n        $stateKey: stateKey\n      };\n      var path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n      if (stateKey !== undefined) {\n        path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n      }\n      return _this18.http.authedRequest(Method.Put, path, getUnstableDelayQueryOpts(delayOpts), content, opts);\n    })();\n  }\n\n  /**\n   * Send a sticky timeline event.\n   *\n   * Note: This endpoint is unstable, and can throw an `Error`.\n   *   Check progress on [MSC4354](https://github.com/matrix-org/matrix-spec-proposals/pull/4354) for more details.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  // eslint-disable-next-line\n  _unstable_sendStickyEvent(roomId, stickDuration, threadId, eventType, content, txnId) {\n    var _this19 = this;\n    return _asyncToGenerator(function* () {\n      if (!(yield _this19.doesServerSupportUnstableFeature(UNSTABLE_MSC4354_STICKY_EVENTS))) {\n        throw new UnsupportedStickyEventsEndpointError(\"Server does not support the sticky events\", \"sendStickyEvent\");\n      }\n      _this19.addThreadRelationIfNeeded(content, threadId, roomId);\n      return _this19.sendCompleteEvent({\n        roomId,\n        threadId,\n        eventObject: {\n          type: eventType,\n          content\n        },\n        queryDict: {\n          \"org.matrix.msc4354.sticky_duration_ms\": stickDuration\n        },\n        txnId\n      });\n    })();\n  }\n\n  /**\n   * Get information about delayed events owned by the requesting user.\n   *\n   * Note: This endpoint is unstable, and can throw an `Error`.\n   *   Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n   */\n  // eslint-disable-next-line\n  _unstable_getDelayedEvents(status, delayId, fromToken) {\n    var _this20 = this;\n    return _asyncToGenerator(function* () {\n      if (!(yield _this20.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n        throw new UnsupportedDelayedEventsEndpointError(\"Server does not support the delayed events API\", \"getDelayedEvents\");\n      }\n      var queryDict = {\n        from: fromToken,\n        status,\n        delay_id: delayId\n      };\n      return yield _this20.http.authedRequest(Method.Get, \"/delayed_events\", queryDict, undefined, {\n        prefix: \"\".concat(ClientPrefix.Unstable, \"/\").concat(UNSTABLE_MSC4140_DELAYED_EVENTS)\n      });\n    })();\n  }\n\n  /**\n   * Manage a delayed event associated with the given delay_id.\n   *\n   * Note: This endpoint is unstable, and can throw an `Error`.\n   *   Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n   *\n   * @deprecated Instead use one of:\n   * - {@link _unstable_cancelScheduledDelayedEvent}\n   * - {@link _unstable_restartScheduledDelayedEvent}\n   * - {@link _unstable_sendScheduledDelayedEvent}\n   */\n  // eslint-disable-next-line @typescript-eslint/naming-convention\n  _unstable_updateDelayedEvent(delayId, action) {\n    var _arguments4 = arguments,\n      _this21 = this;\n    return _asyncToGenerator(function* () {\n      var requestOptions = _arguments4.length > 2 && _arguments4[2] !== undefined ? _arguments4[2] : {};\n      if (!(yield _this21.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n        throw new UnsupportedDelayedEventsEndpointError(\"Server does not support the delayed events API\", \"updateDelayedEvent\");\n      }\n      return yield _this21.updateScheduledDelayedEventWithActionInBody(delayId, action, requestOptions);\n    })();\n  }\n\n  /**\n   * Cancel the scheduled delivery of the delayed event matching the provided delayId.\n   *\n   * Note: This endpoint is unstable, and can throw an `Error`.\n   *   Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n   *\n   * @throws A M_NOT_FOUND error if no matching delayed event could be found.\n   */\n  // eslint-disable-next-line @typescript-eslint/naming-convention\n  _unstable_cancelScheduledDelayedEvent(delayId) {\n    var _arguments5 = arguments,\n      _this22 = this;\n    return _asyncToGenerator(function* () {\n      var requestOptions = _arguments5.length > 1 && _arguments5[1] !== undefined ? _arguments5[1] : {};\n      return yield _this22.updateScheduledDelayedEvent(delayId, UpdateDelayedEventAction.Cancel, requestOptions);\n    })();\n  }\n\n  /**\n   * Restart the scheduled delivery of the delayed event matching the given delayId.\n   *\n   * Note: This endpoint is unstable, and can throw an `Error`.\n   *   Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n   *\n   * @throws A M_NOT_FOUND error if no matching delayed event could be found.\n   */\n  // eslint-disable-next-line @typescript-eslint/naming-convention\n  _unstable_restartScheduledDelayedEvent(delayId) {\n    var _arguments6 = arguments,\n      _this23 = this;\n    return _asyncToGenerator(function* () {\n      var requestOptions = _arguments6.length > 1 && _arguments6[1] !== undefined ? _arguments6[1] : {};\n      return yield _this23.updateScheduledDelayedEvent(delayId, UpdateDelayedEventAction.Restart, requestOptions);\n    })();\n  }\n\n  /**\n   * Immediately send the delayed event matching the given delayId,\n   * instead of waiting for its scheduled delivery.\n   *\n   * Note: This endpoint is unstable, and can throw an `Error`.\n   *   Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n   *\n   * @throws A M_NOT_FOUND error if no matching delayed event could be found.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  // eslint-disable-next-line @typescript-eslint/naming-convention\n  _unstable_sendScheduledDelayedEvent(delayId) {\n    var _arguments7 = arguments,\n      _this24 = this;\n    return _asyncToGenerator(function* () {\n      var requestOptions = _arguments7.length > 1 && _arguments7[1] !== undefined ? _arguments7[1] : {};\n      return yield _this24.updateScheduledDelayedEvent(delayId, UpdateDelayedEventAction.Send, requestOptions);\n    })();\n  }\n  updateScheduledDelayedEvent(delayId, action) {\n    var _arguments8 = arguments,\n      _this25 = this;\n    return _asyncToGenerator(function* () {\n      var requestOptions = _arguments8.length > 2 && _arguments8[2] !== undefined ? _arguments8[2] : {};\n      if (!(yield _this25.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n        throw new UnsupportedDelayedEventsEndpointError(\"Server does not support the delayed events API\", \"\".concat(action, \"ScheduledDelayedEvent\"));\n      }\n      try {\n        var path = utils.encodeUri(\"/delayed_events/$delayId/$action\", {\n          $delayId: delayId,\n          $action: action\n        });\n        return yield _this25.http.request(Method.Post, path, undefined, undefined, _objectSpread(_objectSpread({}, requestOptions), {}, {\n          prefix: \"\".concat(ClientPrefix.Unstable, \"/\").concat(UNSTABLE_MSC4140_DELAYED_EVENTS)\n        }));\n      } catch (e) {\n        if (e instanceof MatrixError && e.errcode === \"M_UNRECOGNIZED\") {\n          // For backwards compatibility with an older version of this endpoint\n          // which put the update action in the request body instead of the path\n          return yield _this25.updateScheduledDelayedEventWithActionInBody(delayId, action, requestOptions);\n        } else {\n          throw e;\n        }\n      }\n    })();\n  }\n\n  /**\n   * @deprecated Present for backwards compatibility with an older version of MSC4140\n   * which had a single, authenticated endpoint for updating a delayed event, instead\n   * of one unauthenticated endpoint per update action.\n   */\n  updateScheduledDelayedEventWithActionInBody(delayId, action) {\n    var _arguments9 = arguments,\n      _this26 = this;\n    return _asyncToGenerator(function* () {\n      var requestOptions = _arguments9.length > 2 && _arguments9[2] !== undefined ? _arguments9[2] : {};\n      var path = utils.encodeUri(\"/delayed_events/$delayId\", {\n        $delayId: delayId\n      });\n      var data = {\n        action\n      };\n      try {\n        return yield _this26.http.request(Method.Post, path, undefined, data, _objectSpread(_objectSpread({}, requestOptions), {}, {\n          prefix: \"\".concat(ClientPrefix.Unstable, \"/\").concat(UNSTABLE_MSC4140_DELAYED_EVENTS)\n        }));\n      } catch (e) {\n        if (e instanceof MatrixError && e.errcode === \"M_MISSING_TOKEN\") {\n          // For backwards compatibility with an older version of this endpoint\n          // which required authentication\n          return yield _this26.http.authedRequest(Method.Post, path, undefined, data, _objectSpread(_objectSpread({}, requestOptions), {}, {\n            prefix: \"\".concat(ClientPrefix.Unstable, \"/\").concat(UNSTABLE_MSC4140_DELAYED_EVENTS)\n          }));\n        } else {\n          throw e;\n        }\n      }\n    })();\n  }\n\n  /**\n   * Send a receipt.\n   * @param event - The event being acknowledged\n   * @param receiptType - The kind of receipt e.g. \"m.read\". Other than\n   * ReceiptType.Read are experimental!\n   * @param body - Additional content to send alongside the receipt.\n   * @param unthreaded - An unthreaded receipt will clear room+thread notifications\n   * @returns Promise which resolves: to an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n  sendReceipt(event, receiptType, body) {\n    var _arguments0 = arguments,\n      _this27 = this;\n    return _asyncToGenerator(function* () {\n      var unthreaded = _arguments0.length > 3 && _arguments0[3] !== undefined ? _arguments0[3] : false;\n      if (_this27.isGuest()) {\n        return Promise.resolve({}); // guests cannot send receipts so don't bother.\n      }\n      var path = utils.encodeUri(\"/rooms/$roomId/receipt/$receiptType/$eventId\", {\n        $roomId: event.getRoomId(),\n        $receiptType: receiptType,\n        $eventId: event.getId()\n      });\n\n      // Unless we're explicitly making an unthreaded receipt or we don't\n      // support threads, include the `thread_id` property in the body.\n      var shouldAddThreadId = !unthreaded && _this27.supportsThreads();\n      var fullBody = shouldAddThreadId ? _objectSpread(_objectSpread({}, body), {}, {\n        thread_id: threadIdForReceipt(event)\n      }) : body;\n      var promise = _this27.http.authedRequest(Method.Post, path, undefined, fullBody || {});\n      var room = _this27.getRoom(event.getRoomId());\n      if (room && _this27.credentials.userId) {\n        room.addLocalEchoReceipt(_this27.credentials.userId, event, receiptType, unthreaded);\n      }\n      return promise;\n    })();\n  }\n\n  /**\n   * Send a read receipt.\n   * @param event - The event that has been read.\n   * @param receiptType - other than ReceiptType.Read are experimental! Optional.\n   * @returns Promise which resolves: to an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n  sendReadReceipt(event) {\n    var _arguments1 = arguments,\n      _this28 = this;\n    return _asyncToGenerator(function* () {\n      var receiptType = _arguments1.length > 1 && _arguments1[1] !== undefined ? _arguments1[1] : ReceiptType.Read;\n      var unthreaded = _arguments1.length > 2 && _arguments1[2] !== undefined ? _arguments1[2] : false;\n      if (!event) return;\n      var eventId = event.getId();\n      var room = _this28.getRoom(event.getRoomId());\n      if (room !== null && room !== void 0 && room.hasPendingEvent(eventId)) {\n        throw new Error(\"Cannot set read receipt to a pending event (\".concat(eventId, \")\"));\n      }\n      return _this28.sendReceipt(event, receiptType, {}, unthreaded);\n    })();\n  }\n\n  /**\n   * Set a marker to indicate the point in a room before which the user has read every\n   * event. This can be retrieved from room account data (the event type is `m.fully_read`)\n   * and displayed as a horizontal line in the timeline that is visually distinct to the\n   * position of the user's own read receipt.\n   * @param roomId - ID of the room that has been read\n   * @param rmEventId - ID of the event that has been read\n   * @param rrEvent - the event tracked by the read receipt. This is here for\n   * convenience because the RR and the RM are commonly updated at the same time as each\n   * other. The local echo of this receipt will be done if set. Optional.\n   * @param rpEvent - the m.read.private read receipt event for when we don't\n   * want other users to see the read receipts. This is experimental. Optional.\n   * @returns Promise which resolves: the empty object, `{}`.\n   */\n  setRoomReadMarkers(roomId, rmEventId, rrEvent, rpEvent) {\n    var _this29 = this;\n    return _asyncToGenerator(function* () {\n      var room = _this29.getRoom(roomId);\n      if (room !== null && room !== void 0 && room.hasPendingEvent(rmEventId)) {\n        throw new Error(\"Cannot set read marker to a pending event (\".concat(rmEventId, \")\"));\n      }\n\n      // Add the optional RR update, do local echo like `sendReceipt`\n      var rrEventId;\n      if (rrEvent) {\n        rrEventId = rrEvent.getId();\n        if (room !== null && room !== void 0 && room.hasPendingEvent(rrEventId)) {\n          throw new Error(\"Cannot set read receipt to a pending event (\".concat(rrEventId, \")\"));\n        }\n        room === null || room === void 0 || room.addLocalEchoReceipt(_this29.credentials.userId, rrEvent, ReceiptType.Read);\n      }\n\n      // Add the optional private RR update, do local echo like `sendReceipt`\n      var rpEventId;\n      if (rpEvent) {\n        rpEventId = rpEvent.getId();\n        if (room !== null && room !== void 0 && room.hasPendingEvent(rpEventId)) {\n          throw new Error(\"Cannot set read receipt to a pending event (\".concat(rpEventId, \")\"));\n        }\n        room === null || room === void 0 || room.addLocalEchoReceipt(_this29.credentials.userId, rpEvent, ReceiptType.ReadPrivate);\n      }\n      return yield _this29.setRoomReadMarkersHttpRequest(roomId, rmEventId, rrEventId, rpEventId);\n    })();\n  }\n\n  /**\n   *\n   * @param roomId\n   * @param notificationEventId\n   * @returns\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  sendRtcDecline(roomId, notificationEventId) {\n    return this.sendEvent(roomId, EventType.RTCDecline, {\n      \"m.relates_to\": {\n        event_id: notificationEventId,\n        rel_type: RelationType.Reference\n      }\n    });\n  }\n\n  /**\n   * Get a preview of the given URL as of (roughly) the given point in time,\n   * described as an object with OpenGraph keys and associated values.\n   * Attributes may be synthesized where actual OG metadata is lacking.\n   * Caches results to prevent hammering the server.\n   * @param url - The URL to get preview data for\n   * @param ts - The preferred point in time that the preview should\n   * describe (ms since epoch).  The preview returned will either be the most\n   * recent one preceding this timestamp if available, or failing that the next\n   * most recent available preview.\n   * @returns Promise which resolves: Object of OG metadata.\n   * @returns Rejects: with an error response.\n   * May return synthesized attributes if the URL lacked OG meta.\n   */\n  getUrlPreview(url, ts) {\n    // bucket the timestamp to the nearest minute to prevent excessive spam to the server\n    // Surely 60-second accuracy is enough for anyone.\n    ts = Math.floor(ts / 60000) * 60000;\n    var parsed = new URL(url);\n    parsed.hash = \"\"; // strip the hash as it won't affect the preview\n    url = parsed.toString();\n    var key = ts + \"_\" + url;\n\n    // If there's already a request in flight (or we've handled it), return that instead.\n    if (key in this.urlPreviewCache) {\n      return this.urlPreviewCache[key];\n    }\n    var resp = this.http.authedRequest(Method.Get, \"/preview_url\", {\n      url,\n      ts: ts.toString()\n    }, undefined, {\n      prefix: MediaPrefix.V3,\n      priority: \"low\"\n    });\n    // TODO: Expire the URL preview cache sometimes\n    this.urlPreviewCache[key] = resp;\n    return resp;\n  }\n\n  /**\n   * @returns Promise which resolves: to an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n  sendTyping(roomId, isTyping, timeoutMs) {\n    if (this.isGuest()) {\n      return Promise.resolve({}); // guests cannot send typing notifications so don't bother.\n    }\n    var path = utils.encodeUri(\"/rooms/$roomId/typing/$userId\", {\n      $roomId: roomId,\n      $userId: this.getUserId()\n    });\n    var data = {\n      typing: isTyping\n    };\n    if (isTyping) {\n      data.timeout = timeoutMs ? timeoutMs : 20000;\n    }\n    return this.http.authedRequest(Method.Put, path, undefined, data);\n  }\n\n  /**\n   * Determines the history of room upgrades for a given room, as far as the\n   * client can see. Returns an array of Rooms where the first entry is the\n   * oldest and the last entry is the newest (likely current) room. If the\n   * provided room is not found, this returns an empty list. This works in\n   * both directions, looking for older and newer rooms of the given room.\n   * @param roomId - The room ID to search from\n   * @param verifyLinks - If true, the function will only return rooms\n   * which can be proven to be linked. For example, rooms which have a create\n   * event pointing to an old room which the client is not aware of or doesn't\n   * have a matching tombstone would not be returned.\n   * @param msc3946ProcessDynamicPredecessor - if true, look for\n   * m.room.predecessor state events as well as create events, and prefer\n   * predecessor events where they exist (MSC3946).\n   * @returns An array of rooms representing the upgrade\n   * history.\n   */\n  getRoomUpgradeHistory(roomId) {\n    var verifyLinks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n    var msc3946ProcessDynamicPredecessor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n    var currentRoom = this.getRoom(roomId);\n    if (!currentRoom) return [];\n    var before = this.findPredecessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor);\n    var after = this.findSuccessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor);\n    return [...before, currentRoom, ...after];\n  }\n  findPredecessorRooms(room, verifyLinks, msc3946ProcessDynamicPredecessor) {\n    var _room$findPredecessor;\n    var ret = [];\n    var seenRoomIDs = new Set([room.roomId]);\n\n    // Work backwards from newer to older rooms\n    var predecessorRoomId = (_room$findPredecessor = room.findPredecessor(msc3946ProcessDynamicPredecessor)) === null || _room$findPredecessor === void 0 ? void 0 : _room$findPredecessor.roomId;\n    while (predecessorRoomId !== null) {\n      var _room$findPredecessor2;\n      if (predecessorRoomId) {\n        if (seenRoomIDs.has(predecessorRoomId)) break;\n        seenRoomIDs.add(predecessorRoomId);\n      }\n      var predecessorRoom = this.getRoom(predecessorRoomId);\n      if (predecessorRoom === null) {\n        break;\n      }\n      if (verifyLinks) {\n        var tombstone = predecessorRoom.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n        if (!tombstone || tombstone.getContent()[\"replacement_room\"] !== room.roomId) {\n          break;\n        }\n      }\n\n      // Insert at the front because we're working backwards from the currentRoom\n      ret.splice(0, 0, predecessorRoom);\n      room = predecessorRoom;\n      predecessorRoomId = (_room$findPredecessor2 = room.findPredecessor(msc3946ProcessDynamicPredecessor)) === null || _room$findPredecessor2 === void 0 ? void 0 : _room$findPredecessor2.roomId;\n    }\n    return ret;\n  }\n  findSuccessorRooms(room, verifyLinks, msc3946ProcessDynamicPredecessor) {\n    var ret = [];\n\n    // Work forwards, looking at tombstone events\n    var tombstoneEvent = room.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n    while (tombstoneEvent) {\n      var successorRoom = this.getRoom(tombstoneEvent.getContent()[\"replacement_room\"]);\n      if (!successorRoom) break; // end of the chain\n      if (successorRoom.roomId === room.roomId) break; // Tombstone is referencing its own room\n\n      if (verifyLinks) {\n        var _successorRoom$findPr;\n        var predecessorRoomId = (_successorRoom$findPr = successorRoom.findPredecessor(msc3946ProcessDynamicPredecessor)) === null || _successorRoom$findPr === void 0 ? void 0 : _successorRoom$findPr.roomId;\n        if (!predecessorRoomId || predecessorRoomId !== room.roomId) {\n          break;\n        }\n      }\n\n      // Push to the end because we're looking forwards\n      ret.push(successorRoom);\n      var roomIds = new Set(ret.map(ref => ref.roomId));\n      if (roomIds.size < ret.length) {\n        // The last room added to the list introduced a previous roomId\n        // To avoid recursion, return the last rooms - 1\n        return ret.slice(0, ret.length - 1);\n      }\n\n      // Set the current room to the reference room so we know where we're at\n      room = successorRoom;\n      tombstoneEvent = room.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n    }\n    return ret;\n  }\n\n  /**\n   * Send an invite to the given user to join the given room.\n   *\n   * @param roomId - The ID of the room to which the user should be invited.\n   * @param userId - The ID of the user that should be invited.\n   * @param opts - Optional reason object. For backwards compatibility, a string is also accepted, and will be interpreted as a reason.\n   *\n   * @returns An empty object.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  invite(roomId, userId) {\n    var _arguments10 = arguments,\n      _this30 = this;\n    return _asyncToGenerator(function* () {\n      var opts = _arguments10.length > 2 && _arguments10[2] !== undefined ? _arguments10[2] : {};\n      if (typeof opts != \"object\") {\n        opts = {\n          reason: opts\n        };\n      }\n      if (opts.shareEncryptedHistory) {\n        var _this30$cryptoBackend;\n        yield (_this30$cryptoBackend = _this30.cryptoBackend) === null || _this30$cryptoBackend === void 0 ? void 0 : _this30$cryptoBackend.shareRoomHistoryWithUser(roomId, userId);\n      }\n      return yield _this30.membershipChange(roomId, userId, KnownMembership.Invite, opts.reason);\n    })();\n  }\n\n  /**\n   * Invite a user to a room based on their email address.\n   * @param roomId - The room to invite the user to.\n   * @param email - The email address to invite.\n   * @returns Promise which resolves: `{}` an empty object.\n   * @returns Rejects: with an error response.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  inviteByEmail(roomId, email) {\n    return this.inviteByThreePid(roomId, \"email\", email);\n  }\n\n  /**\n   * Invite a user to a room based on a third-party identifier.\n   * @param roomId - The room to invite the user to.\n   * @param medium - The medium to invite the user e.g. \"email\".\n   * @param address - The address for the specified medium.\n   * @returns Promise which resolves: `{}` an empty object.\n   * @returns Rejects: with an error response.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  inviteByThreePid(roomId, medium, address) {\n    var _this31 = this;\n    return _asyncToGenerator(function* () {\n      var _this31$identityServe;\n      var path = utils.encodeUri(\"/rooms/$roomId/invite\", {\n        $roomId: roomId\n      });\n      var identityServerUrl = _this31.getIdentityServerUrl(true);\n      if (!identityServerUrl) {\n        return Promise.reject(new MatrixError({\n          error: \"No supplied identity server URL\",\n          errcode: \"ORG.MATRIX.JSSDK_MISSING_PARAM\"\n        }));\n      }\n      var params = {\n        id_server: identityServerUrl,\n        medium: medium,\n        address: address\n      };\n      if ((_this31$identityServe = _this31.identityServer) !== null && _this31$identityServe !== void 0 && _this31$identityServe.getAccessToken) {\n        var identityAccessToken = yield _this31.identityServer.getAccessToken();\n        if (identityAccessToken) {\n          params[\"id_access_token\"] = identityAccessToken;\n        }\n      }\n      return _this31.http.authedRequest(Method.Post, path, undefined, params);\n    })();\n  }\n\n  /**\n   * @returns Promise which resolves: `{}` an empty object.\n   * @returns Rejects: with an error response.\n   */\n  leave(roomId) {\n    return this.membershipChange(roomId, undefined, KnownMembership.Leave);\n  }\n\n  /**\n   * Leaves all rooms in the chain of room upgrades based on the given room. By\n   * default, this will leave all the previous and upgraded rooms, including the\n   * given room. To only leave the given room and any previous rooms, keeping the\n   * upgraded (modern) rooms untouched supply `false` to `includeFuture`.\n   * @param roomId - The room ID to start leaving at\n   * @param includeFuture - If true, the whole chain (past and future) of\n   * upgraded rooms will be left.\n   * @returns Promise which resolves when completed with an object keyed\n   * by room ID and value of the error encountered when leaving or null.\n   */\n  leaveRoomChain(roomId) {\n    var includeFuture = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n    var upgradeHistory = this.getRoomUpgradeHistory(roomId, true);\n    var eligibleToLeave = upgradeHistory;\n    if (!includeFuture) {\n      eligibleToLeave = [];\n      for (var _room3 of upgradeHistory) {\n        eligibleToLeave.push(_room3);\n        if (_room3.roomId === roomId) {\n          break;\n        }\n      }\n    }\n    var populationResults = {};\n    var promises = [];\n    var doLeave = roomId => {\n      return this.leave(roomId).then(() => {\n        delete populationResults[roomId];\n      }).catch(err => {\n        // suppress error\n        populationResults[roomId] = err;\n      });\n    };\n    for (var _room4 of eligibleToLeave) {\n      promises.push(doLeave(_room4.roomId));\n    }\n    return Promise.all(promises).then(() => populationResults);\n  }\n\n  /**\n   * @param reason - Optional.\n   * @returns Promise which resolves: TODO\n   * @returns Rejects: with an error response.\n   */\n  ban(roomId, userId, reason) {\n    return this.membershipChange(roomId, userId, KnownMembership.Ban, reason);\n  }\n\n  /**\n   * @param deleteRoom - True to delete the room from the store on success.\n   * Default: true.\n   * @returns Promise which resolves: `{}` an empty object.\n   * @returns Rejects: with an error response.\n   */\n  forget(roomId) {\n    var _arguments11 = arguments,\n      _this32 = this;\n    return _asyncToGenerator(function* () {\n      var deleteRoom = _arguments11.length > 1 && _arguments11[1] !== undefined ? _arguments11[1] : true;\n      // API returns an empty object\n      var path = utils.encodeUri(\"/rooms/$room_id/forget\", {\n        $room_id: roomId\n      });\n      var response = yield _this32.http.authedRequest(Method.Post, path);\n      if (deleteRoom) {\n        _this32.store.removeRoom(roomId);\n        _this32.emit(ClientEvent.DeleteRoom, roomId);\n      }\n      return response;\n    })();\n  }\n\n  /**\n   * @returns Promise which resolves: Object (currently empty)\n   * @returns Rejects: with an error response.\n   */\n  unban(roomId, userId) {\n    // unbanning != set their state to leave: this used to be\n    // the case, but was then changed so that leaving was always\n    // a revoking of privilege, otherwise two people racing to\n    // kick / ban someone could end up banning and then un-banning\n    // them.\n    var path = utils.encodeUri(\"/rooms/$roomId/unban\", {\n      $roomId: roomId\n    });\n    var data = {\n      user_id: userId\n    };\n    return this.http.authedRequest(Method.Post, path, undefined, data);\n  }\n\n  /**\n   * @param reason - Optional.\n   * @returns Promise which resolves: `{}` an empty object.\n   * @returns Rejects: with an error response.\n   */\n  kick(roomId, userId, reason) {\n    var path = utils.encodeUri(\"/rooms/$roomId/kick\", {\n      $roomId: roomId\n    });\n    var data = {\n      user_id: userId,\n      reason: reason\n    };\n    return this.http.authedRequest(Method.Post, path, undefined, data);\n  }\n  membershipChange(roomId, userId, membership, reason) {\n    // API returns an empty object\n    var path = utils.encodeUri(\"/rooms/$room_id/$membership\", {\n      $room_id: roomId,\n      $membership: membership\n    });\n    return this.http.authedRequest(Method.Post, path, undefined, {\n      user_id: userId,\n      // may be undefined e.g. on leave\n      reason: reason\n    });\n  }\n\n  /**\n   * Obtain a dict of actions which should be performed for this event according\n   * to the push rules for this user.  Caches the dict on the event.\n   * @param event - The event to get push actions for.\n   * @param forceRecalculate - forces to recalculate actions for an event\n   * Useful when an event just got decrypted\n   * @returns A dict of actions to perform.\n   */\n  getPushActionsForEvent(event) {\n    var forceRecalculate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n    if (!event.getPushActions() || forceRecalculate) {\n      var {\n        actions,\n        rule\n      } = this.pushProcessor.actionsAndRuleForEvent(event);\n      event.setPushDetails(actions, rule);\n    }\n    return event.getPushActions();\n  }\n\n  /**\n   * Obtain a dict of actions which should be performed for this event according\n   * to the push rules for this user.  Caches the dict on the event.\n   * @param event - The event to get push actions for.\n   * @param forceRecalculate - forces to recalculate actions for an event\n   * Useful when an event just got decrypted\n   * @returns A dict of actions to perform.\n   */\n  getPushDetailsForEvent(event) {\n    var forceRecalculate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n    if (!event.getPushDetails() || forceRecalculate) {\n      var {\n        actions,\n        rule\n      } = this.pushProcessor.actionsAndRuleForEvent(event);\n      event.setPushDetails(actions, rule);\n    }\n    return event.getPushDetails();\n  }\n\n  /**\n   * @param info - The kind of info to set (e.g. 'avatar_url')\n   * @param data - The JSON object to set.\n   * @returns\n   * @returns Rejects: with an error response.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  // eslint-disable-next-line camelcase\n\n  setProfileInfo(info, data) {\n    var path = utils.encodeUri(\"/profile/$userId/$info\", {\n      $userId: this.credentials.userId,\n      $info: info\n    });\n    return this.http.authedRequest(Method.Put, path, undefined, data);\n  }\n\n  /**\n   * @returns Promise which resolves: `{}` an empty object.\n   * @returns Rejects: with an error response.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  setDisplayName(name) {\n    var _this33 = this;\n    return _asyncToGenerator(function* () {\n      var prom = yield _this33.setProfileInfo(\"displayname\", {\n        displayname: name\n      });\n      // XXX: synthesise a profile update for ourselves because Synapse is broken and won't\n      var user = _this33.getUser(_this33.getUserId());\n      if (user) {\n        user.displayName = name;\n        user.emit(UserEvent.DisplayName, user.events.presence, user);\n      }\n      return prom;\n    })();\n  }\n\n  /**\n   * @returns Promise which resolves: `{}` an empty object.\n   * @returns Rejects: with an error response.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  setAvatarUrl(url) {\n    var _this34 = this;\n    return _asyncToGenerator(function* () {\n      var prom = yield _this34.setProfileInfo(\"avatar_url\", {\n        avatar_url: url\n      });\n      // XXX: synthesise a profile update for ourselves because Synapse is broken and won't\n      var user = _this34.getUser(_this34.getUserId());\n      if (user) {\n        user.avatarUrl = url;\n        user.emit(UserEvent.AvatarUrl, user.events.presence, user);\n      }\n      return prom;\n    })();\n  }\n\n  /**\n   * Turn an MXC URL into an HTTP one. <strong>This method is experimental and\n   * may change.</strong>\n   * @param mxcUrl - The MXC URL\n   * @param width - The desired width of the thumbnail.\n   * @param height - The desired height of the thumbnail.\n   * @param resizeMethod - The thumbnail resize method to use, either\n   * \"crop\" or \"scale\".\n   * @param allowDirectLinks - If true, return any non-mxc URLs\n   * directly. Fetching such URLs will leak information about the user to\n   * anyone they share a room with. If false, will return null for such URLs.\n   * @param allowRedirects - If true, the caller supports the URL being 307 or\n   * 308 redirected to another resource upon request. If false, redirects\n   * are not expected. Implied `true` when `useAuthentication` is `true`.\n   * @param useAuthentication - If true, the caller supports authenticated\n   * media and wants an authentication-required URL. Note that server support\n   * for authenticated media will *not* be checked - it is the caller's responsibility\n   * to do so before calling this function. Note also that `useAuthentication`\n   * implies `allowRedirects`. Defaults to false (unauthenticated endpoints).\n   * @returns the avatar URL or null.\n   */\n  mxcUrlToHttp(mxcUrl, width, height, resizeMethod, allowDirectLinks, allowRedirects, useAuthentication) {\n    return getHttpUriForMxc(this.baseUrl, mxcUrl, width, height, resizeMethod, allowDirectLinks, allowRedirects, useAuthentication);\n  }\n\n  /**\n   * Specify the set_presence value to be used for subsequent calls to the Sync API.\n   * This has an advantage over calls to the PUT /presence API in that it\n   * doesn't clobber status_msg set by other devices.\n   * @param presence - the presence to specify to set_presence of sync calls\n   */\n  setSyncPresence(presence) {\n    var _this35 = this;\n    return _asyncToGenerator(function* () {\n      var _this35$syncApi;\n      (_this35$syncApi = _this35.syncApi) === null || _this35$syncApi === void 0 || _this35$syncApi.setPresence(presence);\n    })();\n  }\n\n  /**\n   * @param opts - Options to apply\n   * @returns Promise which resolves\n   * @returns Rejects: with an error response.\n   * @throws If 'presence' isn't a valid presence enum value.\n   */\n  setPresence(opts) {\n    var _this36 = this;\n    return _asyncToGenerator(function* () {\n      var path = utils.encodeUri(\"/presence/$userId/status\", {\n        $userId: _this36.credentials.userId\n      });\n      var validStates = [\"offline\", \"online\", \"unavailable\"];\n      if (validStates.indexOf(opts.presence) === -1) {\n        throw new Error(\"Bad presence value: \" + opts.presence);\n      }\n      yield _this36.http.authedRequest(Method.Put, path, undefined, opts);\n    })();\n  }\n\n  /**\n   * @param userId - The user to get presence for\n   * @returns Promise which resolves: The presence state for this user.\n   * @returns Rejects: with an error response.\n   */\n  getPresence(userId) {\n    var path = utils.encodeUri(\"/presence/$userId/status\", {\n      $userId: userId\n    });\n    return this.http.authedRequest(Method.Get, path);\n  }\n\n  /**\n   * Retrieve older messages from the given room and put them in the timeline.\n   *\n   * If this is called multiple times whilst a request is ongoing, the <i>same</i>\n   * Promise will be returned. If there was a problem requesting scrollback, there\n   * will be a small delay before another request can be made (to prevent tight-looping\n   * when there is no connection).\n   *\n   * @param room - The room to get older messages in.\n   * @param limit - Optional. The maximum number of previous events to\n   * pull in. Default: 30.\n   * @returns Promise which resolves: Room. If you are at the beginning\n   * of the timeline, `Room.oldState.paginationToken` will be\n   * `null`.\n   * @returns Rejects: with an error response.\n   */\n  scrollback(room) {\n    var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 30;\n    var timeToWaitMs = 0;\n    var info = this.ongoingScrollbacks[room.roomId] || {};\n    if (info.promise) {\n      return info.promise;\n    } else if (info.errorTs) {\n      var timeWaitedMs = Date.now() - info.errorTs;\n      timeToWaitMs = Math.max(SCROLLBACK_DELAY_MS - timeWaitedMs, 0);\n    }\n    if (room.oldState.paginationToken === null) {\n      return Promise.resolve(room); // already at the start.\n    }\n    // attempt to grab more events from the store first\n    var numAdded = this.store.scrollback(room, limit).length;\n    if (numAdded === limit) {\n      // store contained everything we needed.\n      return Promise.resolve(room);\n    }\n    // reduce the required number of events appropriately\n    limit = limit - numAdded;\n    var promise = new Promise((resolve, reject) => {\n      // wait for a time before doing this request\n      // (which may be 0 in order not to special case the code paths)\n      sleep(timeToWaitMs).then(() => {\n        return this.createMessagesRequest(room.roomId, room.oldState.paginationToken, limit, Direction.Backward);\n      }).then(res => {\n        var _res$end, _res$end2;\n        var matrixEvents = res.chunk.map(this.getEventMapper());\n        if (res.state) {\n          var stateEvents = res.state.map(this.getEventMapper());\n          room.currentState.setUnknownStateEvents(stateEvents);\n        }\n        var [timelineEvents, threadedEvents, unknownRelations] = room.partitionThreadedEvents(matrixEvents);\n        this.processAggregatedTimelineEvents(room, timelineEvents);\n        room.addEventsToTimeline(timelineEvents, true, true, room.getLiveTimeline());\n        this.processThreadEvents(room, threadedEvents, true);\n        unknownRelations.forEach(event => room.relations.aggregateChildEvent(event));\n        room.oldState.paginationToken = (_res$end = res.end) !== null && _res$end !== void 0 ? _res$end : null;\n        if (res.chunk.length === 0) {\n          room.oldState.paginationToken = null;\n        }\n        this.store.storeEvents(room, matrixEvents, (_res$end2 = res.end) !== null && _res$end2 !== void 0 ? _res$end2 : null, true);\n        delete this.ongoingScrollbacks[room.roomId];\n        resolve(room);\n      }).catch(err => {\n        this.ongoingScrollbacks[room.roomId] = {\n          errorTs: Date.now()\n        };\n        reject(err);\n      });\n    });\n    info = {\n      promise\n    };\n    this.ongoingScrollbacks[room.roomId] = info;\n    return promise;\n  }\n  getEventMapper(options) {\n    return eventMapperFor(this, options || {});\n  }\n\n  /**\n   * Calls the `/context` API for the given room ID & event ID.\n   * Returns the response, with `event` asserted and all optional arrays defaulted to an empty array.\n   * @param roomId - the room ID to request a context for\n   * @param eventId - the event ID to request a context for\n   * @throws if `event` in the response is missing\n   * @private\n   */\n  getEventContext(roomId, eventId) {\n    var _this37 = this;\n    return _asyncToGenerator(function* () {\n      var _this37$clientOpts;\n      var path = utils.encodeUri(\"/rooms/$roomId/context/$eventId\", {\n        $roomId: roomId,\n        $eventId: eventId\n      });\n      var params = {\n        limit: \"0\"\n      };\n      if ((_this37$clientOpts = _this37.clientOpts) !== null && _this37$clientOpts !== void 0 && _this37$clientOpts.lazyLoadMembers) {\n        params.filter = JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER);\n      }\n\n      // TODO: we should implement a backoff (as per scrollback()) to deal more nicely with HTTP errors.\n      var res = yield _this37.http.authedRequest(Method.Get, path, params);\n      if (res.event) {\n        var _res$events_after, _res$events_before, _res$state;\n        return {\n          start: res.start,\n          end: res.end,\n          event: res.event,\n          events_after: (_res$events_after = res.events_after) !== null && _res$events_after !== void 0 ? _res$events_after : [],\n          events_before: (_res$events_before = res.events_before) !== null && _res$events_before !== void 0 ? _res$events_before : [],\n          state: (_res$state = res.state) !== null && _res$state !== void 0 ? _res$state : []\n        };\n      }\n      throw new Error(\"'event' not in '/context' result - homeserver too old?\");\n    })();\n  }\n\n  /**\n   * Get an EventTimeline for the given event\n   *\n   * <p>If the EventTimelineSet object already has the given event in its store, the\n   * corresponding timeline will be returned. Otherwise, a /context request is\n   * made, and used to construct an EventTimeline.\n   * If the event does not belong to this EventTimelineSet then undefined will be returned.\n   *\n   * @param timelineSet -  The timelineSet to look for the event in, must be bound to a room\n   * @param eventId -  The ID of the event to look for\n   *\n   * @returns Promise which resolves:\n   *    {@link EventTimeline} including the given event\n   */\n  getEventTimeline(timelineSet, eventId) {\n    var _this38 = this;\n    return _asyncToGenerator(function* () {\n      var _ref4, _timelineSet$getTimel, _timelineSet$room$fin;\n      // don't allow any timeline support unless it's been enabled.\n      if (!_this38.timelineSupport) {\n        throw new Error(\"timeline support is disabled. Set the 'timelineSupport'\" + \" parameter to true when creating MatrixClient to enable it.\");\n      }\n      if (!(timelineSet !== null && timelineSet !== void 0 && timelineSet.room)) {\n        throw new Error(\"getEventTimeline only supports room timelines\");\n      }\n      if (timelineSet.getTimelineForEvent(eventId)) {\n        return timelineSet.getTimelineForEvent(eventId);\n      }\n      if (timelineSet.thread && _this38.supportsThreads()) {\n        var _yield$_this38$getThr;\n        return (_yield$_this38$getThr = yield _this38.getThreadTimeline(timelineSet, eventId)) !== null && _yield$_this38$getThr !== void 0 ? _yield$_this38$getThr : null;\n      }\n      var res = yield _this38.getEventContext(timelineSet.room.roomId, eventId);\n\n      // by the time the request completes, the event might have ended up in the timeline.\n      if (timelineSet.getTimelineForEvent(eventId)) {\n        return timelineSet.getTimelineForEvent(eventId);\n      }\n      var mapper = _this38.getEventMapper();\n      var event = mapper(res.event);\n      if (event.isRelation(THREAD_RELATION_TYPE.name)) {\n        _this38.logger.warn(\"Tried loading a regular timeline at the position of a thread event\");\n        return null;\n      }\n      var events = [\n      // Order events from most recent to oldest (reverse-chronological).\n      // We start with the last event, since that's the point at which we have known state.\n      // events_after is already backwards; events_before is forwards.\n      ...res.events_after.reverse().map(mapper), event, ...res.events_before.map(mapper)];\n\n      // Here we handle non-thread timelines only, but still process any thread events to populate thread summaries.\n      var timeline = timelineSet.getTimelineForEvent(events[0].getId());\n      if (timeline) {\n        timeline.getState(EventTimeline.BACKWARDS).setUnknownStateEvents(res.state.map(mapper));\n      } else {\n        var _res$end3;\n        timeline = timelineSet.addTimeline();\n        timeline.initialiseState(res.state.map(mapper));\n        timeline.getState(EventTimeline.FORWARDS).paginationToken = (_res$end3 = res.end) !== null && _res$end3 !== void 0 ? _res$end3 : null;\n      }\n      var [timelineEvents, threadedEvents, unknownRelations] = timelineSet.room.partitionThreadedEvents(events);\n      timelineSet.addEventsToTimeline(timelineEvents, true, false, timeline, res.start);\n      // The target event is not in a thread but process the contextual events, so we can show any threads around it.\n      _this38.processThreadEvents(timelineSet.room, threadedEvents, true);\n      _this38.processAggregatedTimelineEvents(timelineSet.room, timelineEvents);\n      unknownRelations.forEach(event => timelineSet.relations.aggregateChildEvent(event));\n\n      // There is no guarantee that the event ended up in \"timeline\" (we might have switched to a neighbouring\n      // timeline) - so check the room's index again. On the other hand, there's no guarantee the event ended up\n      // anywhere, if it was later redacted, so we just return the timeline we first thought of.\n      return (_ref4 = (_timelineSet$getTimel = timelineSet.getTimelineForEvent(eventId)) !== null && _timelineSet$getTimel !== void 0 ? _timelineSet$getTimel : (_timelineSet$room$fin = timelineSet.room.findThreadForEvent(event)) === null || _timelineSet$room$fin === void 0 ? void 0 : _timelineSet$room$fin.liveTimeline) !== null && _ref4 !== void 0 ? _ref4 :\n      // for Threads degraded support\n      timeline;\n    })();\n  }\n  getThreadTimeline(timelineSet, eventId) {\n    var _this39 = this;\n    return _asyncToGenerator(function* () {\n      if (!_this39.supportsThreads()) {\n        throw new Error(\"could not get thread timeline: no client support\");\n      }\n      if (!timelineSet.room) {\n        throw new Error(\"could not get thread timeline: not a room timeline\");\n      }\n      if (!timelineSet.thread) {\n        throw new Error(\"could not get thread timeline: not a thread timeline\");\n      }\n      var res = yield _this39.getEventContext(timelineSet.room.roomId, eventId);\n      var mapper = _this39.getEventMapper();\n      var event = mapper(res.event);\n      if (!timelineSet.canContain(event)) {\n        return undefined;\n      }\n      var recurse = _this39.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;\n      if (Thread.hasServerSideSupport) {\n        if (Thread.hasServerSideFwdPaginationSupport) {\n          var _resOlder$next_batch, _resNewer$next_batch, _timelineSet$getTimel2;\n          if (!timelineSet.thread) {\n            throw new Error(\"could not get thread timeline: not a thread timeline\");\n          }\n          var thread = timelineSet.thread;\n          var resOlder = yield _this39.fetchRelations(timelineSet.room.roomId, thread.id, null, null, {\n            dir: Direction.Backward,\n            from: res.start,\n            recurse: recurse || undefined\n          });\n          var resNewer = yield _this39.fetchRelations(timelineSet.room.roomId, thread.id, null, null, {\n            dir: Direction.Forward,\n            from: res.end,\n            recurse: recurse || undefined\n          });\n          var events = [\n          // Order events from most recent to oldest (reverse-chronological).\n          // We start with the last event, since that's the point at which we have known state.\n          // events_after is already backwards; events_before is forwards.\n          ...resNewer.chunk.reverse().filter(getRelationsThreadFilter(thread.id)).map(mapper), event, ...resOlder.chunk.filter(getRelationsThreadFilter(thread.id)).map(mapper)];\n          for (var _event2 of events) {\n            var _timelineSet$thread;\n            yield (_timelineSet$thread = timelineSet.thread) === null || _timelineSet$thread === void 0 ? void 0 : _timelineSet$thread.processEvent(_event2);\n          }\n\n          // Here we handle non-thread timelines only, but still process any thread events to populate thread summaries.\n          var timeline = timelineSet.getTimelineForEvent(event.getId());\n          if (timeline) {\n            timeline.getState(EventTimeline.BACKWARDS).setUnknownStateEvents(res.state.map(mapper));\n          } else {\n            timeline = timelineSet.addTimeline();\n            timeline.initialiseState(res.state.map(mapper));\n          }\n          timelineSet.addEventsToTimeline(events, true, false, timeline, resNewer.next_batch);\n          if (!resOlder.next_batch) {\n            var originalEvent = yield _this39.fetchRoomEvent(timelineSet.room.roomId, thread.id);\n            timelineSet.addEventsToTimeline([mapper(originalEvent)], true, false, timeline, null);\n          }\n          timeline.setPaginationToken((_resOlder$next_batch = resOlder.next_batch) !== null && _resOlder$next_batch !== void 0 ? _resOlder$next_batch : null, Direction.Backward);\n          timeline.setPaginationToken((_resNewer$next_batch = resNewer.next_batch) !== null && _resNewer$next_batch !== void 0 ? _resNewer$next_batch : null, Direction.Forward);\n          _this39.processAggregatedTimelineEvents(timelineSet.room, events);\n\n          // There is no guarantee that the event ended up in \"timeline\" (we might have switched to a neighbouring\n          // timeline) - so check the room's index again. On the other hand, there's no guarantee the event ended up\n          // anywhere, if it was later redacted, so we just return the timeline we first thought of.\n          return (_timelineSet$getTimel2 = timelineSet.getTimelineForEvent(eventId)) !== null && _timelineSet$getTimel2 !== void 0 ? _timelineSet$getTimel2 : timeline;\n        } else {\n          var _resOlder$next_batch2;\n          // Where the event is a thread reply (not a root) and running in MSC-enabled mode the Thread timeline only\n          // functions contiguously, so we have to jump through some hoops to get our target event in it.\n          // XXX: workaround for https://github.com/vector-im/element-meta/issues/150\n\n          var _thread = timelineSet.thread;\n          var _resOlder = yield _this39.fetchRelations(timelineSet.room.roomId, _thread.id, THREAD_RELATION_TYPE.name, null, {\n            dir: Direction.Backward,\n            from: res.start,\n            recurse: recurse || undefined\n          });\n          var eventsNewer = [];\n          var nextBatch = res.end;\n          while (nextBatch) {\n            var _resNewer = yield _this39.fetchRelations(timelineSet.room.roomId, _thread.id, THREAD_RELATION_TYPE.name, null, {\n              dir: Direction.Forward,\n              from: nextBatch,\n              recurse: recurse || undefined\n            });\n            nextBatch = _resNewer.next_batch;\n            eventsNewer.push(..._resNewer.chunk);\n          }\n          var _events = [\n          // Order events from most recent to oldest (reverse-chronological).\n          // We start with the last event, since that's the point at which we have known state.\n          // events_after is already backwards; events_before is forwards.\n          ...eventsNewer.reverse().map(mapper), event, ..._resOlder.chunk.map(mapper)];\n          for (var _event3 of _events) {\n            var _timelineSet$thread2;\n            yield (_timelineSet$thread2 = timelineSet.thread) === null || _timelineSet$thread2 === void 0 ? void 0 : _timelineSet$thread2.processEvent(_event3);\n          }\n\n          // Here we handle non-thread timelines only, but still process any thread events to populate thread\n          // summaries.\n          var _timeline = timelineSet.getLiveTimeline();\n          _timeline.getState(EventTimeline.BACKWARDS).setUnknownStateEvents(res.state.map(mapper));\n          timelineSet.addEventsToTimeline(_events, true, false, _timeline, null);\n          if (!_resOlder.next_batch) {\n            var _originalEvent = yield _this39.fetchRoomEvent(timelineSet.room.roomId, _thread.id);\n            timelineSet.addEventsToTimeline([mapper(_originalEvent)], true, false, _timeline, null);\n          }\n          _timeline.setPaginationToken((_resOlder$next_batch2 = _resOlder.next_batch) !== null && _resOlder$next_batch2 !== void 0 ? _resOlder$next_batch2 : null, Direction.Backward);\n          _timeline.setPaginationToken(null, Direction.Forward);\n          _this39.processAggregatedTimelineEvents(timelineSet.room, _events);\n          return _timeline;\n        }\n      }\n    })();\n  }\n\n  /**\n   * Get an EventTimeline for the latest events in the room. This will just\n   * call `/messages` to get the latest message in the room, then use\n   * `client.getEventTimeline(...)` to construct a new timeline from it.\n   *\n   * @param timelineSet -  The timelineSet to find or add the timeline to\n   *\n   * @returns Promise which resolves:\n   *    {@link EventTimeline} timeline with the latest events in the room\n   */\n  getLatestTimeline(timelineSet) {\n    var _this40 = this;\n    return _asyncToGenerator(function* () {\n      // don't allow any timeline support unless it's been enabled.\n      if (!_this40.timelineSupport) {\n        throw new Error(\"timeline support is disabled. Set the 'timelineSupport'\" + \" parameter to true when creating MatrixClient to enable it.\");\n      }\n      if (!timelineSet.room) {\n        throw new Error(\"getLatestTimeline only supports room timelines\");\n      }\n      var event;\n      if (timelineSet.threadListType !== null) {\n        var _res$chunk;\n        var res = yield _this40.createThreadListMessagesRequest(timelineSet.room.roomId, null, 1, Direction.Backward, timelineSet.threadListType, timelineSet.getFilter());\n        event = (_res$chunk = res.chunk) === null || _res$chunk === void 0 ? void 0 : _res$chunk[0];\n      } else if (timelineSet.thread && Thread.hasServerSideSupport) {\n        var _res$chunk2;\n        var recurse = _this40.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;\n        var _res = yield _this40.fetchRelations(timelineSet.room.roomId, timelineSet.thread.id, THREAD_RELATION_TYPE.name, null, {\n          dir: Direction.Backward,\n          limit: 1,\n          recurse: recurse || undefined\n        });\n        event = (_res$chunk2 = _res.chunk) === null || _res$chunk2 === void 0 ? void 0 : _res$chunk2[0];\n      } else {\n        var _this40$clientOpts, _res2$chunk;\n        var messagesPath = utils.encodeUri(\"/rooms/$roomId/messages\", {\n          $roomId: timelineSet.room.roomId\n        });\n        var _params = {\n          dir: \"b\"\n        };\n        if ((_this40$clientOpts = _this40.clientOpts) !== null && _this40$clientOpts !== void 0 && _this40$clientOpts.lazyLoadMembers) {\n          _params.filter = JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER);\n        }\n        var _res2 = yield _this40.http.authedRequest(Method.Get, messagesPath, _params);\n        event = (_res2$chunk = _res2.chunk) === null || _res2$chunk === void 0 ? void 0 : _res2$chunk[0];\n      }\n      if (!event) {\n        throw new Error(\"No message returned when trying to construct getLatestTimeline\");\n      }\n      return _this40.getEventTimeline(timelineSet, event.event_id);\n    })();\n  }\n\n  /**\n   * Makes a request to /messages with the appropriate lazy loading filter set.\n   * XXX: if we do get rid of scrollback (as it's not used at the moment),\n   * we could inline this method again in paginateEventTimeline as that would\n   * then be the only call-site\n   * @param limit - the maximum amount of events the retrieve\n   * @param dir - 'f' or 'b'\n   * @param timelineFilter - the timeline filter to pass\n   */\n  // XXX: Intended private, used in code.\n  createMessagesRequest(roomId, fromToken) {\n    var _this$clientOpts;\n    var limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 30;\n    var dir = arguments.length > 3 ? arguments[3] : undefined;\n    var timelineFilter = arguments.length > 4 ? arguments[4] : undefined;\n    var path = utils.encodeUri(\"/rooms/$roomId/messages\", {\n      $roomId: roomId\n    });\n    var params = {\n      limit: limit.toString(),\n      dir: dir\n    };\n    if (fromToken) {\n      params.from = fromToken;\n    }\n    var filter = null;\n    if ((_this$clientOpts = this.clientOpts) !== null && _this$clientOpts !== void 0 && _this$clientOpts.lazyLoadMembers) {\n      // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER,\n      // so the timelineFilter doesn't get written into it below\n      filter = Object.assign({}, Filter.LAZY_LOADING_MESSAGES_FILTER);\n    }\n    if (timelineFilter) {\n      var _timelineFilter$getRo;\n      // XXX: it's horrific that /messages' filter parameter doesn't match\n      // /sync's one - see https://matrix.org/jira/browse/SPEC-451\n      filter = filter || {};\n      Object.assign(filter, (_timelineFilter$getRo = timelineFilter.getRoomTimelineFilterComponent()) === null || _timelineFilter$getRo === void 0 ? void 0 : _timelineFilter$getRo.toJSON());\n    }\n    if (filter) {\n      params.filter = JSON.stringify(filter);\n    }\n    return this.http.authedRequest(Method.Get, path, params);\n  }\n\n  /**\n   * Makes a request to /messages with the appropriate lazy loading filter set.\n   * XXX: if we do get rid of scrollback (as it's not used at the moment),\n   * we could inline this method again in paginateEventTimeline as that would\n   * then be the only call-site\n   * @param limit - the maximum amount of events the retrieve\n   * @param dir - 'f' or 'b'\n   * @param timelineFilter - the timeline filter to pass\n   */\n  // XXX: Intended private, used by room.fetchRoomThreads\n  createThreadListMessagesRequest(roomId, fromToken) {\n    var _this$clientOpts2;\n    var limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 30;\n    var dir = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : Direction.Backward;\n    var threadListType = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : ThreadFilterType.All;\n    var timelineFilter = arguments.length > 5 ? arguments[5] : undefined;\n    var path = utils.encodeUri(\"/rooms/$roomId/threads\", {\n      $roomId: roomId\n    });\n    var params = {\n      limit: limit.toString(),\n      dir: dir,\n      include: threadFilterTypeToFilter(threadListType)\n    };\n    if (fromToken) {\n      params.from = fromToken;\n    }\n    var filter = {};\n    if ((_this$clientOpts2 = this.clientOpts) !== null && _this$clientOpts2 !== void 0 && _this$clientOpts2.lazyLoadMembers) {\n      // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER,\n      // so the timelineFilter doesn't get written into it below\n      filter = _objectSpread({}, Filter.LAZY_LOADING_MESSAGES_FILTER);\n    }\n    if (timelineFilter) {\n      var _timelineFilter$getRo2;\n      // XXX: it's horrific that /messages' filter parameter doesn't match\n      // /sync's one - see https://matrix.org/jira/browse/SPEC-451\n      filter = _objectSpread(_objectSpread({}, filter), (_timelineFilter$getRo2 = timelineFilter.getRoomTimelineFilterComponent()) === null || _timelineFilter$getRo2 === void 0 ? void 0 : _timelineFilter$getRo2.toJSON());\n    }\n    if (Object.keys(filter).length) {\n      params.filter = JSON.stringify(filter);\n    }\n    var opts = {\n      prefix: Thread.hasServerSideListSupport === FeatureSupport.Stable ? ClientPrefix.V1 : \"/_matrix/client/unstable/org.matrix.msc3856\"\n    };\n    return this.http.authedRequest(Method.Get, path, params, undefined, opts).then(res => {\n      var _res$chunk3;\n      return _objectSpread(_objectSpread({}, res), {}, {\n        chunk: (_res$chunk3 = res.chunk) === null || _res$chunk3 === void 0 ? void 0 : _res$chunk3.reverse(),\n        start: res.prev_batch,\n        end: res.next_batch\n      });\n    });\n  }\n\n  /**\n   * Take an EventTimeline, and back/forward-fill results.\n   *\n   * @param eventTimeline - timeline object to be updated\n   *\n   * @returns Promise which resolves to a boolean: false if there are no\n   *    events and we reached either end of the timeline; else true.\n   */\n  paginateEventTimeline(eventTimeline, opts) {\n    var _this41 = this;\n    var isNotifTimeline = eventTimeline.getTimelineSet() === this.notifTimelineSet;\n    var room = this.getRoom(eventTimeline.getRoomId());\n    var threadListType = eventTimeline.getTimelineSet().threadListType;\n    var thread = eventTimeline.getTimelineSet().thread;\n\n    // TODO: we should implement a backoff (as per scrollback()) to deal more\n    // nicely with HTTP errors.\n    opts = opts || {};\n    var backwards = opts.backwards || false;\n    if (isNotifTimeline) {\n      if (!backwards) {\n        throw new Error(\"paginateNotifTimeline can only paginate backwards\");\n      }\n    }\n    var dir = backwards ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS;\n    var token = eventTimeline.getPaginationToken(dir);\n    var pendingRequest = eventTimeline.paginationRequests[dir];\n    if (pendingRequest) {\n      // already a request in progress - return the existing promise\n      return pendingRequest;\n    }\n    var path;\n    var params;\n    var promise;\n    if (isNotifTimeline) {\n      var _opts$limit;\n      path = \"/notifications\";\n      params = {\n        limit: ((_opts$limit = opts.limit) !== null && _opts$limit !== void 0 ? _opts$limit : 30).toString(),\n        only: \"highlight\"\n      };\n      if (token && token !== \"end\") {\n        params.from = token;\n      }\n      promise = this.http.authedRequest(Method.Get, path, params).then(/*#__PURE__*/function () {\n        var _ref5 = _asyncToGenerator(function* (res) {\n          var token = res.next_token;\n          var matrixEvents = [];\n          res.notifications = res.notifications.filter(noUnsafeEventProps);\n          for (var i = 0; i < res.notifications.length; i++) {\n            var notification = res.notifications[i];\n            var _event4 = _this41.getEventMapper()(notification.event);\n\n            // @TODO(kerrya) reprocessing every notification is ugly\n            // remove if we get server MSC3994 support\n            _this41.getPushDetailsForEvent(_event4, true);\n            _event4.event.room_id = notification.room_id; // XXX: gutwrenching\n            matrixEvents[i] = _event4;\n          }\n\n          // No need to partition events for threads here, everything lives\n          // in the notification timeline set\n          var timelineSet = eventTimeline.getTimelineSet();\n          timelineSet.addEventsToTimeline(matrixEvents, backwards, false, eventTimeline, token);\n          _this41.processAggregatedTimelineEvents(timelineSet.room, matrixEvents);\n\n          // if we've hit the end of the timeline, we need to stop trying to\n          // paginate. We need to keep the 'forwards' token though, to make sure\n          // we can recover from gappy syncs.\n          if (backwards && !res.next_token) {\n            eventTimeline.setPaginationToken(null, dir);\n          }\n          return Boolean(res.next_token);\n        });\n        return function (_x2) {\n          return _ref5.apply(this, arguments);\n        };\n      }()).finally(() => {\n        eventTimeline.paginationRequests[dir] = null;\n      });\n      eventTimeline.paginationRequests[dir] = promise;\n    } else if (threadListType !== null) {\n      if (!room) {\n        throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n      }\n      if (!Thread.hasServerSideFwdPaginationSupport && dir === Direction.Forward) {\n        throw new Error(\"Cannot paginate threads forwards without server-side support for MSC 3715\");\n      }\n      promise = this.createThreadListMessagesRequest(eventTimeline.getRoomId(), token, opts.limit, dir, threadListType, eventTimeline.getFilter()).then(res => {\n        if (res.state) {\n          var roomState = eventTimeline.getState(dir);\n          var stateEvents = res.state.filter(noUnsafeEventProps).map(this.getEventMapper());\n          roomState.setUnknownStateEvents(stateEvents);\n        }\n        var token = res.end;\n        var matrixEvents = res.chunk.filter(noUnsafeEventProps).map(this.getEventMapper());\n        var timelineSet = eventTimeline.getTimelineSet();\n        timelineSet.addEventsToTimeline(matrixEvents, backwards, false, eventTimeline, token);\n        this.processAggregatedTimelineEvents(room, matrixEvents);\n        this.processThreadRoots(room, matrixEvents, backwards);\n\n        // if we've hit the end of the timeline, we need to stop trying to\n        // paginate. We need to keep the 'forwards' token though, to make sure\n        // we can recover from gappy syncs.\n        if (backwards && res.end == res.start) {\n          eventTimeline.setPaginationToken(null, dir);\n        }\n        return res.end !== res.start;\n      }).finally(() => {\n        eventTimeline.paginationRequests[dir] = null;\n      });\n      eventTimeline.paginationRequests[dir] = promise;\n    } else if (thread) {\n      var _eventTimeline$getRoo, _eventTimeline$getRoo2;\n      var _room5 = this.getRoom((_eventTimeline$getRoo = eventTimeline.getRoomId()) !== null && _eventTimeline$getRoo !== void 0 ? _eventTimeline$getRoo : undefined);\n      if (!_room5) {\n        throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n      }\n      var recurse = this.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;\n      promise = this.fetchRelations((_eventTimeline$getRoo2 = eventTimeline.getRoomId()) !== null && _eventTimeline$getRoo2 !== void 0 ? _eventTimeline$getRoo2 : \"\", thread.id, null, null, {\n        dir,\n        limit: opts.limit,\n        from: token !== null && token !== void 0 ? token : undefined,\n        recurse: recurse || undefined\n      }).then(/*#__PURE__*/function () {\n        var _ref6 = _asyncToGenerator(function* (res) {\n          var mapper = _this41.getEventMapper();\n          var matrixEvents = res.chunk.filter(noUnsafeEventProps).filter(getRelationsThreadFilter(thread.id)).map(mapper);\n\n          // Process latest events first\n          for (var _event5 of matrixEvents.slice().reverse()) {\n            yield thread === null || thread === void 0 ? void 0 : thread.processEvent(_event5);\n            var sender = _event5.getSender();\n            if (!backwards || (thread === null || thread === void 0 ? void 0 : thread.getEventReadUpTo(sender)) === null) {\n              _room5.addLocalEchoReceipt(sender, _event5, ReceiptType.Read);\n            }\n          }\n          var newToken = res.next_batch;\n          var timelineSet = eventTimeline.getTimelineSet();\n          timelineSet.addEventsToTimeline(matrixEvents, backwards, false, eventTimeline, newToken !== null && newToken !== void 0 ? newToken : null);\n          if (!newToken && backwards) {\n            var _thread$rootEvent, _eventTimeline$getRoo3;\n            var originalEvent = (_thread$rootEvent = thread.rootEvent) !== null && _thread$rootEvent !== void 0 ? _thread$rootEvent : mapper(yield _this41.fetchRoomEvent((_eventTimeline$getRoo3 = eventTimeline.getRoomId()) !== null && _eventTimeline$getRoo3 !== void 0 ? _eventTimeline$getRoo3 : \"\", thread.id));\n            timelineSet.addEventsToTimeline([originalEvent], true, false, eventTimeline, null);\n          }\n          _this41.processAggregatedTimelineEvents(timelineSet.room, matrixEvents);\n\n          // if we've hit the end of the timeline, we need to stop trying to\n          // paginate. We need to keep the 'forwards' token though, to make sure\n          // we can recover from gappy syncs.\n          if (backwards && !newToken) {\n            eventTimeline.setPaginationToken(null, dir);\n          }\n          return Boolean(newToken);\n        });\n        return function (_x3) {\n          return _ref6.apply(this, arguments);\n        };\n      }()).finally(() => {\n        eventTimeline.paginationRequests[dir] = null;\n      });\n      eventTimeline.paginationRequests[dir] = promise;\n    } else {\n      if (!room) {\n        throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n      }\n      promise = this.createMessagesRequest(eventTimeline.getRoomId(), token, opts.limit, dir, eventTimeline.getFilter()).then(res => {\n        if (res.state) {\n          var roomState = eventTimeline.getState(dir);\n          var stateEvents = res.state.filter(noUnsafeEventProps).map(this.getEventMapper());\n          roomState.setUnknownStateEvents(stateEvents);\n        }\n        var token = res.end;\n        var matrixEvents = res.chunk.filter(noUnsafeEventProps).map(this.getEventMapper());\n        var timelineSet = eventTimeline.getTimelineSet();\n        var [timelineEvents,, unknownRelations] = room.partitionThreadedEvents(matrixEvents);\n        timelineSet.addEventsToTimeline(timelineEvents, backwards, false, eventTimeline, token);\n        this.processAggregatedTimelineEvents(room, timelineEvents);\n        this.processThreadRoots(room, timelineEvents.filter(it => it.getServerAggregatedRelation(THREAD_RELATION_TYPE.name)), false);\n        unknownRelations.forEach(event => room.relations.aggregateChildEvent(event));\n        var atEnd = res.end === undefined || res.end === res.start;\n\n        // if we've hit the end of the timeline, we need to stop trying to\n        // paginate. We need to keep the 'forwards' token though, to make sure\n        // we can recover from gappy syncs.\n        if (backwards && atEnd) {\n          eventTimeline.setPaginationToken(null, dir);\n        }\n        return !atEnd;\n      }).finally(() => {\n        eventTimeline.paginationRequests[dir] = null;\n      });\n      eventTimeline.paginationRequests[dir] = promise;\n    }\n    return promise;\n  }\n\n  /**\n   * Reset the notifTimelineSet entirely, paginating in some historical notifs as\n   * a starting point for subsequent pagination.\n   */\n  resetNotifTimelineSet() {\n    if (!this.notifTimelineSet) {\n      return;\n    }\n\n    // FIXME: This thing is a total hack, and results in duplicate events being\n    // added to the timeline both from /sync and /notifications, and lots of\n    // slow and wasteful processing and pagination.  The correct solution is to\n    // extend /messages or /search or something to filter on notifications.\n\n    // use the fictitious token 'end'. in practice we would ideally give it\n    // the oldest backwards pagination token from /sync, but /sync doesn't\n    // know about /notifications, so we have no choice but to start paginating\n    // from the current point in time.  This may well overlap with historical\n    // notifs which are then inserted into the timeline by /sync responses.\n    this.notifTimelineSet.resetLiveTimeline(\"end\");\n\n    // we could try to paginate a single event at this point in order to get\n    // a more valid pagination token, but it just ends up with an out of order\n    // timeline. given what a mess this is and given we're going to have duplicate\n    // events anyway, just leave it with the dummy token for now.\n    /*\n    this.paginateNotifTimeline(this._notifTimelineSet.getLiveTimeline(), {\n        backwards: true,\n        limit: 1\n    });\n    */\n  }\n\n  /**\n   * Peek into a room and receive updates about the room. This only works if the\n   * history visibility for the room is world_readable.\n   * @param roomId - The room to attempt to peek into.\n   * @param limit - The number of timeline events to initially retrieve.\n   * @returns Promise which resolves: Room object\n   * @returns Rejects: with an error response.\n   */\n  peekInRoom(roomId) {\n    var _this$peekSync2;\n    var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 20;\n    (_this$peekSync2 = this.peekSync) === null || _this$peekSync2 === void 0 || _this$peekSync2.stopPeeking();\n    this.peekSync = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n    return this.peekSync.peek(roomId, limit);\n  }\n\n  /**\n   * Stop any ongoing room peeking.\n   */\n  stopPeeking() {\n    if (this.peekSync) {\n      this.peekSync.stopPeeking();\n      this.peekSync = null;\n    }\n  }\n\n  /**\n   * Set r/w flags for guest access in a room.\n   * @param roomId - The room to configure guest access in.\n   * @param opts - Options\n   * @returns Promise which resolves\n   * @returns Rejects: with an error response.\n   */\n  setGuestAccess(roomId, opts) {\n    var writePromise = this.sendStateEvent(roomId, EventType.RoomGuestAccess, {\n      guest_access: opts.allowJoin ? GuestAccess.CanJoin : GuestAccess.Forbidden\n    }, \"\");\n    var readPromise = Promise.resolve();\n    if (opts.allowRead) {\n      readPromise = this.sendStateEvent(roomId, EventType.RoomHistoryVisibility, {\n        history_visibility: HistoryVisibility.WorldReadable\n      }, \"\");\n    }\n    return Promise.all([readPromise, writePromise]).then(); // .then() to hide results for contract\n  }\n\n  /**\n   * Requests an email verification token for the purposes of registration.\n   * This API requests a token from the homeserver.\n   * The doesServerRequireIdServerParam() method can be used to determine if\n   * the server requires the id_server parameter to be provided.\n   *\n   * Parameters and return value are as for requestEmailToken\n    * @param email - As requestEmailToken\n   * @param clientSecret - As requestEmailToken\n   * @param sendAttempt - As requestEmailToken\n   * @param nextLink - As requestEmailToken\n   * @returns Promise which resolves: As requestEmailToken\n   */\n  requestRegisterEmailToken(email, clientSecret, sendAttempt, nextLink) {\n    return this.requestTokenFromEndpoint(\"/register/email/requestToken\", {\n      email: email,\n      client_secret: clientSecret,\n      send_attempt: sendAttempt,\n      next_link: nextLink\n    });\n  }\n\n  /**\n   * Requests a text message verification token for the purposes of registration.\n   * This API requests a token from the homeserver.\n   * The doesServerRequireIdServerParam() method can be used to determine if\n   * the server requires the id_server parameter to be provided.\n   *\n   * @param phoneCountry - The ISO 3166-1 alpha-2 code for the country in which\n   *    phoneNumber should be parsed relative to.\n   * @param phoneNumber - The phone number, in national or international format\n   * @param clientSecret - As requestEmailToken\n   * @param sendAttempt - As requestEmailToken\n   * @param nextLink - As requestEmailToken\n   * @returns Promise which resolves: As requestEmailToken\n   */\n  requestRegisterMsisdnToken(phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink) {\n    return this.requestTokenFromEndpoint(\"/register/msisdn/requestToken\", {\n      country: phoneCountry,\n      phone_number: phoneNumber,\n      client_secret: clientSecret,\n      send_attempt: sendAttempt,\n      next_link: nextLink\n    });\n  }\n\n  /**\n   * Requests an email verification token for the purposes of adding a\n   * third party identifier to an account.\n   * This API requests a token from the homeserver.\n   * The doesServerRequireIdServerParam() method can be used to determine if\n   * the server requires the id_server parameter to be provided.\n   * If an account with the given email address already exists and is\n   * associated with an account other than the one the user is authed as,\n   * it will either send an email to the address informing them of this\n   * or return M_THREEPID_IN_USE (which one is up to the homeserver).\n   *\n   * @param email - As requestEmailToken\n   * @param clientSecret - As requestEmailToken\n   * @param sendAttempt - As requestEmailToken\n   * @param nextLink - As requestEmailToken\n   * @returns Promise which resolves: As requestEmailToken\n   */\n  requestAdd3pidEmailToken(email, clientSecret, sendAttempt, nextLink) {\n    return this.requestTokenFromEndpoint(\"/account/3pid/email/requestToken\", {\n      email: email,\n      client_secret: clientSecret,\n      send_attempt: sendAttempt,\n      next_link: nextLink\n    });\n  }\n\n  /**\n   * Requests a text message verification token for the purposes of adding a\n   * third party identifier to an account.\n   * This API proxies the identity server /validate/email/requestToken API,\n   * adding specific behaviour for the addition of phone numbers to an\n   * account, as requestAdd3pidEmailToken.\n   *\n   * @param phoneCountry - As requestRegisterMsisdnToken\n   * @param phoneNumber - As requestRegisterMsisdnToken\n   * @param clientSecret - As requestEmailToken\n   * @param sendAttempt - As requestEmailToken\n   * @param nextLink - As requestEmailToken\n   * @returns Promise which resolves: As requestEmailToken\n   */\n  requestAdd3pidMsisdnToken(phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink) {\n    return this.requestTokenFromEndpoint(\"/account/3pid/msisdn/requestToken\", {\n      country: phoneCountry,\n      phone_number: phoneNumber,\n      client_secret: clientSecret,\n      send_attempt: sendAttempt,\n      next_link: nextLink\n    });\n  }\n\n  /**\n   * Requests an email verification token for the purposes of resetting\n   * the password on an account.\n   * This API proxies the identity server /validate/email/requestToken API,\n   * adding specific behaviour for the password resetting. Specifically,\n   * if no account with the given email address exists, it may either\n   * return M_THREEPID_NOT_FOUND or send an email\n   * to the address informing them of this (which one is up to the homeserver).\n   *\n   * requestEmailToken calls the equivalent API directly on the identity server,\n   * therefore bypassing the password reset specific logic.\n   *\n   * @param email - As requestEmailToken\n   * @param clientSecret - As requestEmailToken\n   * @param sendAttempt - As requestEmailToken\n   * @param nextLink - As requestEmailToken\n   * @returns Promise which resolves: As requestEmailToken\n   */\n  requestPasswordEmailToken(email, clientSecret, sendAttempt, nextLink) {\n    return this.requestTokenFromEndpoint(\"/account/password/email/requestToken\", {\n      email: email,\n      client_secret: clientSecret,\n      send_attempt: sendAttempt,\n      next_link: nextLink\n    });\n  }\n\n  /**\n   * Requests a text message verification token for the purposes of resetting\n   * the password on an account.\n   * This API proxies the identity server /validate/email/requestToken API,\n   * adding specific behaviour for the password resetting, as requestPasswordEmailToken.\n   *\n   * @param phoneCountry - As requestRegisterMsisdnToken\n   * @param phoneNumber - As requestRegisterMsisdnToken\n   * @param clientSecret - As requestEmailToken\n   * @param sendAttempt - As requestEmailToken\n   * @param nextLink - As requestEmailToken\n   * @returns Promise which resolves: As requestEmailToken\n   */\n  requestPasswordMsisdnToken(phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink) {\n    return this.requestTokenFromEndpoint(\"/account/password/msisdn/requestToken\", {\n      country: phoneCountry,\n      phone_number: phoneNumber,\n      client_secret: clientSecret,\n      send_attempt: sendAttempt,\n      next_link: nextLink\n    });\n  }\n\n  /**\n   * Internal utility function for requesting validation tokens from usage-specific\n   * requestToken endpoints.\n   *\n   * @param endpoint - The endpoint to send the request to\n   * @param params - Parameters for the POST request\n   * @returns Promise which resolves: As requestEmailToken\n   */\n  requestTokenFromEndpoint(endpoint, params) {\n    var _this42 = this;\n    return _asyncToGenerator(function* () {\n      var postParams = Object.assign({}, params);\n      return _this42.http.request(Method.Post, endpoint, undefined, postParams);\n    })();\n  }\n\n  /**\n   * Get the room-kind push rule associated with a room.\n   * @param scope - \"global\" or device-specific.\n   * @param roomId - the id of the room.\n   * @returns the rule or undefined.\n   */\n  getRoomPushRule(scope, roomId) {\n    // There can be only room-kind push rule per room\n    // and its id is the room id.\n    if (this.pushRules) {\n      var _this$pushRules$scope;\n      return (_this$pushRules$scope = this.pushRules[scope]) === null || _this$pushRules$scope === void 0 || (_this$pushRules$scope = _this$pushRules$scope.room) === null || _this$pushRules$scope === void 0 ? void 0 : _this$pushRules$scope.find(rule => rule.rule_id === roomId);\n    } else {\n      throw new Error(\"SyncApi.sync() must be done before accessing to push rules.\");\n    }\n  }\n\n  /**\n   * Set a room-kind muting push rule in a room.\n   * The operation also updates MatrixClient.pushRules at the end.\n   * @param scope - \"global\" or device-specific.\n   * @param roomId - the id of the room.\n   * @param mute - the mute state.\n   * @returns Promise which resolves: result object\n   * @returns Rejects: with an error response.\n   */\n  setRoomMutePushRule(scope, roomId, mute) {\n    var promise;\n    var hasDontNotifyRule = false;\n\n    // Get the existing room-kind push rule if any\n    var roomPushRule = this.getRoomPushRule(scope, roomId);\n    if (roomPushRule !== null && roomPushRule !== void 0 && roomPushRule.actions.includes(PushRuleActionName.DontNotify)) {\n      hasDontNotifyRule = true;\n    }\n    if (!mute) {\n      // Remove the rule only if it is a muting rule\n      if (hasDontNotifyRule) {\n        promise = this.deletePushRule(scope, PushRuleKind.RoomSpecific, roomPushRule.rule_id);\n      }\n    } else {\n      if (!roomPushRule) {\n        promise = this.addPushRule(scope, PushRuleKind.RoomSpecific, roomId, {\n          actions: [PushRuleActionName.DontNotify]\n        });\n      } else if (!hasDontNotifyRule) {\n        // Remove the existing one before setting the mute push rule\n        // This is a workaround to SYN-590 (Push rule update fails)\n        var doneResolvers = Promise.withResolvers();\n        this.deletePushRule(scope, PushRuleKind.RoomSpecific, roomPushRule.rule_id).then(() => {\n          this.addPushRule(scope, PushRuleKind.RoomSpecific, roomId, {\n            actions: [PushRuleActionName.DontNotify]\n          }).then(() => {\n            doneResolvers.resolve();\n          }).catch(err => {\n            doneResolvers.reject(err);\n          });\n        }).catch(err => {\n          doneResolvers.reject(err);\n        });\n        promise = doneResolvers.promise;\n      }\n    }\n    if (promise) {\n      return new Promise((resolve, reject) => {\n        // Update this.pushRules when the operation completes\n        promise.then(() => {\n          this.getPushRules().then(result => {\n            this.pushRules = result;\n            resolve();\n          }).catch(err => {\n            reject(err);\n          });\n        }).catch(err => {\n          // Update it even if the previous operation fails. This can help the\n          // app to recover when push settings has been modified from another client\n          this.getPushRules().then(result => {\n            this.pushRules = result;\n            reject(err);\n          }).catch(err2 => {\n            reject(err);\n          });\n        });\n      });\n    }\n  }\n  searchMessageText(opts) {\n    var roomEvents = {\n      search_term: opts.query\n    };\n    if (\"keys\" in opts) {\n      roomEvents.keys = opts.keys;\n    }\n    return this.search({\n      body: {\n        search_categories: {\n          room_events: roomEvents\n        }\n      }\n    });\n  }\n\n  /**\n   * Perform a server-side search for room events.\n   *\n   * The returned promise resolves to an object containing the fields:\n   *\n   *  * count:       estimate of the number of results\n   *  * next_batch:  token for back-pagination; if undefined, there are no more results\n   *  * highlights:  a list of words to highlight from the stemming algorithm\n   *  * results:     a list of results\n   *\n   * Each entry in the results list is a SearchResult.\n   *\n   * @returns Promise which resolves: result object\n   * @returns Rejects: with an error response.\n   */\n  searchRoomEvents(opts) {\n    // TODO: support search groups\n\n    var body = {\n      search_categories: {\n        room_events: {\n          search_term: opts.term,\n          filter: opts.filter,\n          order_by: SearchOrderBy.Recent,\n          event_context: {\n            before_limit: 1,\n            after_limit: 1,\n            include_profile: true\n          }\n        }\n      }\n    };\n    var searchResults = {\n      _query: body,\n      results: [],\n      highlights: []\n    };\n    return this.search({\n      body: body\n    }).then(res => this.processRoomEventsSearch(searchResults, res));\n  }\n\n  /**\n   * Take a result from an earlier searchRoomEvents call, and backfill results.\n   *\n   * @param searchResults -  the results object to be updated\n   * @returns Promise which resolves: updated result object\n   * @returns Rejects: with an error response.\n   */\n  backPaginateRoomEventsSearch(searchResults) {\n    // TODO: we should implement a backoff (as per scrollback()) to deal more\n    // nicely with HTTP errors.\n\n    if (!searchResults.next_batch) {\n      return Promise.reject(new Error(\"Cannot backpaginate event search any further\"));\n    }\n    if (searchResults.pendingRequest) {\n      // already a request in progress - return the existing promise\n      return searchResults.pendingRequest;\n    }\n    var searchOpts = {\n      body: searchResults._query,\n      next_batch: searchResults.next_batch\n    };\n    var promise = this.search(searchOpts, searchResults.abortSignal).then(res => this.processRoomEventsSearch(searchResults, res)).finally(() => {\n      searchResults.pendingRequest = undefined;\n    });\n    searchResults.pendingRequest = promise;\n    return promise;\n  }\n\n  /**\n   * helper for searchRoomEvents and backPaginateRoomEventsSearch. Processes the\n   * response from the API call and updates the searchResults\n   *\n   * @returns searchResults\n   * @internal\n   */\n  // XXX: Intended private, used in code\n  processRoomEventsSearch(searchResults, response) {\n    var _roomEvents$results$l, _roomEvents$results;\n    var roomEvents = response.search_categories.room_events;\n    searchResults.count = roomEvents.count;\n    searchResults.next_batch = roomEvents.next_batch;\n\n    // combine the highlight list with our existing list;\n    var highlights = new Set(roomEvents.highlights);\n    searchResults.highlights.forEach(hl => {\n      highlights.add(hl);\n    });\n\n    // turn it back into a list.\n    searchResults.highlights = Array.from(highlights);\n    var mapper = this.getEventMapper();\n\n    // append the new results to our existing results\n    var resultsLength = (_roomEvents$results$l = (_roomEvents$results = roomEvents.results) === null || _roomEvents$results === void 0 ? void 0 : _roomEvents$results.length) !== null && _roomEvents$results$l !== void 0 ? _roomEvents$results$l : 0;\n    for (var i = 0; i < resultsLength; i++) {\n      var sr = SearchResult.fromJson(roomEvents.results[i], mapper);\n      var _room6 = this.getRoom(sr.context.getEvent().getRoomId());\n      if (_room6) {\n        for (var ev of sr.context.getTimeline()) {\n          ev.setMetadata(_room6.currentState, false);\n        }\n      }\n      searchResults.results.push(sr);\n    }\n    return searchResults;\n  }\n\n  /**\n   * Populate the store with rooms the user has left.\n   * @returns Promise which resolves: TODO - Resolved when the rooms have\n   * been added to the data store.\n   * @returns Rejects: with an error response.\n   */\n  syncLeftRooms() {\n    // Guard against multiple calls whilst ongoing and multiple calls post success\n    if (this.syncedLeftRooms) {\n      return Promise.resolve([]); // don't call syncRooms again if it succeeded.\n    }\n    if (this.syncLeftRoomsPromise) {\n      return this.syncLeftRoomsPromise; // return the ongoing request\n    }\n    var syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n    this.syncLeftRoomsPromise = syncApi.syncLeftRooms();\n\n    // cleanup locks\n    this.syncLeftRoomsPromise.then(() => {\n      this.logger.debug(\"Marking success of sync left room request\");\n      this.syncedLeftRooms = true; // flip the bit on success\n    }).finally(() => {\n      this.syncLeftRoomsPromise = undefined; // cleanup ongoing request state\n    });\n    return this.syncLeftRoomsPromise;\n  }\n\n  /**\n   * Create a new filter.\n   * @param content - The HTTP body for the request\n   * @returns Promise which resolves to a Filter object.\n   * @returns Rejects: with an error response.\n   */\n  createFilter(content) {\n    var path = utils.encodeUri(\"/user/$userId/filter\", {\n      $userId: this.credentials.userId\n    });\n    return this.http.authedRequest(Method.Post, path, undefined, content).then(response => {\n      // persist the filter\n      var filter = Filter.fromJson(this.credentials.userId, response.filter_id, content);\n      this.store.storeFilter(filter);\n      return filter;\n    });\n  }\n\n  /**\n   * Retrieve a filter.\n   * @param userId - The user ID of the filter owner\n   * @param filterId - The filter ID to retrieve\n   * @param allowCached - True to allow cached filters to be returned.\n   * Default: True.\n   * @returns Promise which resolves: a Filter object\n   * @returns Rejects: with an error response.\n   */\n  getFilter(userId, filterId, allowCached) {\n    if (allowCached) {\n      var filter = this.store.getFilter(userId, filterId);\n      if (filter) {\n        return Promise.resolve(filter);\n      }\n    }\n    var path = utils.encodeUri(\"/user/$userId/filter/$filterId\", {\n      $userId: userId,\n      $filterId: filterId\n    });\n    return this.http.authedRequest(Method.Get, path).then(response => {\n      // persist the filter\n      var filter = Filter.fromJson(userId, filterId, response);\n      this.store.storeFilter(filter);\n      return filter;\n    });\n  }\n\n  /**\n   * @returns Filter ID\n   */\n  getOrCreateFilter(filterName, filter) {\n    var _this43 = this;\n    return _asyncToGenerator(function* () {\n      var filterId = _this43.store.getFilterIdByName(filterName);\n      var existingId;\n      if (filterId) {\n        // check that the existing filter matches our expectations\n        try {\n          var existingFilter = yield _this43.getFilter(_this43.credentials.userId, filterId, true);\n          if (existingFilter) {\n            var oldDef = existingFilter.getDefinition();\n            var newDef = filter.getDefinition();\n            if (utils.deepCompare(oldDef, newDef)) {\n              // super, just use that.\n              // debuglog(\"Using existing filter ID %s: %s\", filterId,\n              //          JSON.stringify(oldDef));\n              existingId = filterId;\n            }\n          }\n        } catch (error) {\n          // Synapse currently returns the following when the filter cannot be found:\n          // {\n          //     errcode: \"M_UNKNOWN\",\n          //     name: \"M_UNKNOWN\",\n          //     message: \"No row found\",\n          // }\n          if (error.errcode !== \"M_UNKNOWN\" && error.errcode !== \"M_NOT_FOUND\") {\n            throw error;\n          }\n        }\n        // if the filter doesn't exist anymore on the server, remove from store\n        if (!existingId) {\n          _this43.store.setFilterIdByName(filterName, undefined);\n        }\n      }\n      if (existingId) {\n        return existingId;\n      }\n\n      // create a new filter\n      var createdFilter = yield _this43.createFilter(filter.getDefinition());\n      _this43.store.setFilterIdByName(filterName, createdFilter.filterId);\n      return createdFilter.filterId;\n    })();\n  }\n\n  /**\n   * Gets a bearer token from the homeserver that the user can\n   * present to a third party in order to prove their ownership\n   * of the Matrix account they are logged into.\n   * @returns Promise which resolves: Token object\n   * @returns Rejects: with an error response.\n   */\n  getOpenIdToken() {\n    var path = utils.encodeUri(\"/user/$userId/openid/request_token\", {\n      $userId: this.credentials.userId\n    });\n    return this.http.authedRequest(Method.Post, path, undefined, {});\n  }\n  /**\n   * @returns Promise which resolves: ITurnServerResponse object\n   * @returns Rejects: with an error response.\n   */\n  turnServer() {\n    return this.http.authedRequest(Method.Get, \"/voip/turnServer\");\n  }\n\n  /**\n   * Get the TURN servers for this homeserver.\n   * @returns The servers or an empty list.\n   */\n  getTurnServers() {\n    return this.turnServers || [];\n  }\n\n  /**\n   * Get the unix timestamp (in milliseconds) at which the current\n   * TURN credentials (from getTurnServers) expire\n   * @returns The expiry timestamp in milliseconds\n   */\n  getTurnServersExpiry() {\n    return this.turnServersExpiry;\n  }\n  get pollingTurnServers() {\n    return this.checkTurnServersIntervalID !== undefined;\n  }\n\n  // XXX: Intended private, used in code.\n  checkTurnServers() {\n    var _this44 = this;\n    return _asyncToGenerator(function* () {\n      if (!_this44.supportsVoip()) {\n        return;\n      }\n      var credentialsGood = false;\n      var remainingTime = _this44.turnServersExpiry - Date.now();\n      if (remainingTime > TURN_CHECK_INTERVAL) {\n        _this44.logger.debug(\"TURN creds are valid for another \" + remainingTime + \" ms: not fetching new ones.\");\n        credentialsGood = true;\n      } else {\n        _this44.logger.debug(\"Fetching new TURN credentials\");\n        try {\n          var res = yield _this44.turnServer();\n          if (res.uris) {\n            _this44.logger.debug(\"Got TURN URIs: \" + res.uris + \" refresh in \" + res.ttl + \" secs\");\n            // map the response to a format that can be fed to RTCPeerConnection\n            var servers = {\n              urls: res.uris,\n              username: res.username,\n              credential: res.password\n            };\n            _this44.turnServers = [servers];\n            // The TTL is in seconds but we work in ms\n            _this44.turnServersExpiry = Date.now() + res.ttl * 1000;\n            credentialsGood = true;\n            _this44.emit(ClientEvent.TurnServers, _this44.turnServers);\n          }\n        } catch (err) {\n          _this44.logger.error(\"Failed to get TURN URIs\", err);\n          if (err.httpStatus === 403) {\n            // We got a 403, so there's no point in looping forever.\n            _this44.logger.info(\"TURN access unavailable for this account: stopping credentials checks\");\n            if (_this44.checkTurnServersIntervalID !== null) {\n              globalThis.clearInterval(_this44.checkTurnServersIntervalID);\n            }\n            _this44.checkTurnServersIntervalID = undefined;\n            _this44.emit(ClientEvent.TurnServersError, err, true); // fatal\n          } else {\n            // otherwise, if we failed for whatever reason, try again the next time we're called.\n            _this44.emit(ClientEvent.TurnServersError, err, false); // non-fatal\n          }\n        }\n      }\n      return credentialsGood;\n    })();\n  }\n\n  /**\n   * Set whether to allow a fallback ICE server should be used for negotiating a\n   * WebRTC connection if the homeserver doesn't provide any servers. Defaults to\n   * false.\n   *\n   */\n  setFallbackICEServerAllowed(allow) {\n    this.fallbackICEServerAllowed = allow;\n  }\n\n  /**\n   * Get whether to allow a fallback ICE server should be used for negotiating a\n   * WebRTC connection if the homeserver doesn't provide any servers. Defaults to\n   * false.\n   *\n   * @returns\n   */\n  isFallbackICEServerAllowed() {\n    return this.fallbackICEServerAllowed;\n  }\n\n  /**\n   * Determines if the current user is an administrator of the Synapse homeserver.\n   * Returns false if untrue or the homeserver does not appear to be a Synapse\n   * homeserver. <strong>This function is implementation specific and may change\n   * as a result.</strong>\n   * @returns true if the user appears to be a Synapse administrator.\n   */\n  isSynapseAdministrator() {\n    var path = utils.encodeUri(\"/_synapse/admin/v1/users/$userId/admin\", {\n      $userId: this.getUserId()\n    });\n    return this.http.authedRequest(Method.Get, path, undefined, undefined, {\n      prefix: \"\"\n    }).then(r => r.admin); // pull out the specific boolean we want\n  }\n\n  /**\n   * Performs a whois lookup on a user using Synapse's administrator API.\n   * <strong>This function is implementation specific and may change as a\n   * result.</strong>\n   * @param userId - the User ID to look up.\n   * @returns the whois response - see Synapse docs for information.\n   */\n  whoisSynapseUser(userId) {\n    var path = utils.encodeUri(\"/_synapse/admin/v1/whois/$userId\", {\n      $userId: userId\n    });\n    return this.http.authedRequest(Method.Get, path, undefined, undefined, {\n      prefix: \"\"\n    });\n  }\n\n  /**\n   * Deactivates a user using Synapse's administrator API. <strong>This\n   * function is implementation specific and may change as a result.</strong>\n   * @param userId - the User ID to deactivate.\n   * @returns the deactivate response - see Synapse docs for information.\n   */\n  deactivateSynapseUser(userId) {\n    var path = utils.encodeUri(\"/_synapse/admin/v1/deactivate/$userId\", {\n      $userId: userId\n    });\n    return this.http.authedRequest(Method.Post, path, undefined, undefined, {\n      prefix: \"\"\n    });\n  }\n  fetchClientWellKnown() {\n    var _this45 = this;\n    return _asyncToGenerator(function* () {\n      var _this45$getDomain;\n      // `getRawClientConfig` does not throw or reject on network errors, instead\n      // it absorbs errors and returns `{}`.\n      _this45.clientWellKnownPromise = AutoDiscovery.getRawClientConfig((_this45$getDomain = _this45.getDomain()) !== null && _this45$getDomain !== void 0 ? _this45$getDomain : undefined);\n      _this45.clientWellKnown = yield _this45.clientWellKnownPromise;\n      _this45.emit(ClientEvent.ClientWellKnown, _this45.clientWellKnown);\n    })();\n  }\n  getClientWellKnown() {\n    return this.clientWellKnown;\n  }\n  waitForClientWellKnown() {\n    if (!this.clientRunning) {\n      throw new Error(\"Client is not running\");\n    }\n    return this.clientWellKnownPromise;\n  }\n\n  /**\n   * store client options with boolean/string/numeric values\n   * to know in the next session what flags the sync data was\n   * created with (e.g. lazy loading)\n   * @returns for store operation\n   */\n  storeClientOptions() {\n    // XXX: Intended private, used in code\n    var primTypes = [\"boolean\", \"string\", \"number\"];\n    var serializableOpts = Object.entries(this.clientOpts).filter(_ref7 => {\n      var [key, value] = _ref7;\n      return primTypes.includes(typeof value);\n    }).reduce((obj, _ref8) => {\n      var [key, value] = _ref8;\n      obj[key] = value;\n      return obj;\n    }, {});\n    return this.store.storeClientOptions(serializableOpts);\n  }\n\n  /**\n   * Gets a set of room IDs in common with another user.\n   *\n   * Note: This endpoint is unstable, and can throw an `Error`.\n   *   Check progress on [MSC2666](https://github.com/matrix-org/matrix-spec-proposals/pull/2666) for more details.\n   *\n   * @param userId - The userId to check.\n   * @returns Promise which resolves to an array of rooms\n   * @returns Rejects: with an error response.\n   */\n  // TODO: on spec release, rename this to getMutualRooms\n  // eslint-disable-next-line\n  _unstable_getSharedRooms(userId) {\n    var _this46 = this;\n    return _asyncToGenerator(function* () {\n      // Initial variant of the MSC\n      var sharedRoomsSupport = yield _this46.doesServerSupportUnstableFeature(UNSTABLE_MSC2666_SHARED_ROOMS);\n\n      // Newer variant that renamed shared rooms to mutual rooms\n      var mutualRoomsSupport = yield _this46.doesServerSupportUnstableFeature(UNSTABLE_MSC2666_MUTUAL_ROOMS);\n\n      // Latest variant that changed from path elements to query elements\n      var queryMutualRoomsSupport = yield _this46.doesServerSupportUnstableFeature(UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS);\n      if (!sharedRoomsSupport && !mutualRoomsSupport && !queryMutualRoomsSupport) {\n        throw Error(\"Server does not support the Mutual Rooms API\");\n      }\n      var path;\n      var query;\n\n      // Cascading unstable support switching.\n      if (queryMutualRoomsSupport) {\n        path = \"/uk.half-shot.msc2666/user/mutual_rooms\";\n        query = {\n          user_id: userId\n        };\n      } else {\n        path = utils.encodeUri(\"/uk.half-shot.msc2666/user/\".concat(mutualRoomsSupport ? \"mutual_rooms\" : \"shared_rooms\", \"/$userId\"), {\n          $userId: userId\n        });\n        query = {};\n      }\n\n      // Accumulated rooms\n      var rooms = [];\n      var token = null;\n      do {\n        var tokenQuery = {};\n        if (token != null && queryMutualRoomsSupport) {\n          tokenQuery[\"batch_token\"] = token;\n        }\n        var res = yield _this46.http.authedRequest(Method.Get, path, _objectSpread(_objectSpread({}, query), tokenQuery), undefined, {\n          prefix: ClientPrefix.Unstable\n        });\n        rooms.push(...res.joined);\n        if (res.next_batch_token !== undefined) {\n          token = res.next_batch_token;\n        } else {\n          token = null;\n        }\n      } while (token != null);\n      return rooms;\n    })();\n  }\n\n  /**\n   * Returns a set of configured RTC transports supported by the homeserver.\n   * Requires homeserver support for MSC4143.\n   * @throws A M_NOT_FOUND error if not supported by the homeserver.\n   */\n  // eslint-disable-next-line @typescript-eslint/naming-convention\n  _unstable_getRTCTransports() {\n    var _this47 = this;\n    return _asyncToGenerator(function* () {\n      // There is no /versions endpoint to check for support, so we just have to attempt a request.\n      return (yield _this47.http.authedRequest(Method.Get, \"/rtc/transports\", undefined, undefined, {\n        prefix: \"\".concat(ClientPrefix.Unstable, \"/org.matrix.msc4143\")\n      })).rtc_transports;\n    })();\n  }\n\n  /**\n   * Get the API versions supported by the server, along with any\n   * unstable APIs it supports\n   * @returns The server /versions response\n   */\n  getVersions() {\n    var _this48 = this;\n    return _asyncToGenerator(function* () {\n      if (_this48.serverVersionsPromise) {\n        return _this48.serverVersionsPromise;\n      }\n\n      // We send an authenticated request as of MSC4026\n      _this48.serverVersionsPromise = _this48.http.authedRequest(Method.Get, \"/_matrix/client/versions\", undefined, undefined, {\n        prefix: \"\"\n      }).catch(e => {\n        // Need to unset this if it fails, otherwise we'll never retry\n        _this48.serverVersionsPromise = undefined;\n        // but rethrow the exception to anything that was waiting\n        throw e;\n      });\n      var serverVersions = yield _this48.serverVersionsPromise;\n      _this48.canSupport = yield buildFeatureSupportMap(serverVersions);\n      return _this48.serverVersionsPromise;\n    })();\n  }\n\n  /**\n   * Check if a particular spec version is supported by the server.\n   * @param version - The spec version (such as \"r0.5.0\") to check for.\n   * @returns Whether it is supported\n   */\n  isVersionSupported(version) {\n    var _this49 = this;\n    return _asyncToGenerator(function* () {\n      var {\n        versions\n      } = yield _this49.getVersions();\n      return versions && versions.includes(version);\n    })();\n  }\n\n  /**\n   * Query the server to see if it lists support for an unstable feature\n   * in the /versions response\n   * @param feature - the feature name\n   * @returns true if the feature is supported\n   */\n  doesServerSupportUnstableFeature(feature) {\n    var _this50 = this;\n    return _asyncToGenerator(function* () {\n      var response = yield _this50.getVersions();\n      if (!response) return false;\n      var unstableFeatures = response[\"unstable_features\"];\n      return unstableFeatures && !!unstableFeatures[feature];\n    })();\n  }\n\n  /**\n   * Query the server to see if it is forcing encryption to be enabled for\n   * a given room preset, based on the /versions response.\n   * @param presetName - The name of the preset to check.\n   * @returns true if the server is forcing encryption\n   * for the preset.\n   */\n  doesServerForceEncryptionForPreset(presetName) {\n    var _this51 = this;\n    return _asyncToGenerator(function* () {\n      var response = yield _this51.getVersions();\n      if (!response) return false;\n      var unstableFeatures = response[\"unstable_features\"];\n\n      // The preset name in the versions response will be without the _chat suffix.\n      var versionsPresetName = presetName.includes(\"_chat\") ? presetName.substring(0, presetName.indexOf(\"_chat\")) : presetName;\n      return unstableFeatures && !!unstableFeatures[\"io.element.e2ee_forced.\".concat(versionsPresetName)];\n    })();\n  }\n  doesServerSupportThread() {\n    var _this52 = this;\n    return _asyncToGenerator(function* () {\n      if (yield _this52.isVersionSupported(\"v1.4\")) {\n        return {\n          threads: FeatureSupport.Stable,\n          list: FeatureSupport.Stable,\n          fwdPagination: FeatureSupport.Stable\n        };\n      }\n      try {\n        var [threadUnstable, threadStable, listUnstable, listStable, fwdPaginationUnstable, fwdPaginationStable] = yield Promise.all([_this52.doesServerSupportUnstableFeature(\"org.matrix.msc3440\"), _this52.doesServerSupportUnstableFeature(\"org.matrix.msc3440.stable\"), _this52.doesServerSupportUnstableFeature(\"org.matrix.msc3856\"), _this52.doesServerSupportUnstableFeature(\"org.matrix.msc3856.stable\"), _this52.doesServerSupportUnstableFeature(\"org.matrix.msc3715\"), _this52.doesServerSupportUnstableFeature(\"org.matrix.msc3715.stable\")]);\n        return {\n          threads: determineFeatureSupport(threadStable, threadUnstable),\n          list: determineFeatureSupport(listStable, listUnstable),\n          fwdPagination: determineFeatureSupport(fwdPaginationStable, fwdPaginationUnstable)\n        };\n      } catch (_unused2) {\n        return {\n          threads: FeatureSupport.None,\n          list: FeatureSupport.None,\n          fwdPagination: FeatureSupport.None\n        };\n      }\n    })();\n  }\n\n  /**\n   * Get if lazy loading members is being used.\n   * @returns Whether or not members are lazy loaded by this client\n   */\n  hasLazyLoadMembersEnabled() {\n    var _this$clientOpts3;\n    return !!((_this$clientOpts3 = this.clientOpts) !== null && _this$clientOpts3 !== void 0 && _this$clientOpts3.lazyLoadMembers);\n  }\n\n  /**\n   * Set a function which is called when /sync returns a 'limited' response.\n   * It is called with a room ID and returns a boolean. It should return 'true' if the SDK\n   * can SAFELY remove events from this room. It may not be safe to remove events if there\n   * are other references to the timelines for this room, e.g because the client is\n   * actively viewing events in this room.\n   * Default: returns false.\n   * @param cb - The callback which will be invoked.\n   */\n  setCanResetTimelineCallback(cb) {\n    this.canResetTimelineCallback = cb;\n  }\n\n  /**\n   * Get the callback set via `setCanResetTimelineCallback`.\n   * @returns The callback or null\n   */\n  getCanResetTimelineCallback() {\n    return this.canResetTimelineCallback;\n  }\n\n  /**\n   * Returns relations for a given event. Handles encryption transparently,\n   * with the caveat that the amount of events returned might be 0, even though you get a nextBatch.\n   * When the returned promise resolves, all messages should have finished trying to decrypt.\n   * @param roomId - the room of the event\n   * @param eventId - the id of the event\n   * @param relationType - the rel_type of the relations requested\n   * @param eventType - the event type of the relations requested\n   * @param opts - options with optional values for the request.\n   * @returns an object with `events` as `MatrixEvent[]` and optionally `nextBatch` if more relations are available.\n   */\n  relations(roomId, eventId, relationType, eventType) {\n    var _arguments12 = arguments,\n      _this53 = this;\n    return _asyncToGenerator(function* () {\n      var _result$next_batch, _result$prev_batch;\n      var opts = _arguments12.length > 4 && _arguments12[4] !== undefined ? _arguments12[4] : {\n        dir: Direction.Backward\n      };\n      var fetchedEventType = eventType ? _this53.getEncryptedIfNeededEventType(roomId, eventType) : null;\n      var [eventResult, result] = yield Promise.all([_this53.fetchRoomEvent(roomId, eventId), _this53.fetchRelations(roomId, eventId, relationType, fetchedEventType, opts)]);\n      var mapper = _this53.getEventMapper();\n      var originalEvent = eventResult ? mapper(eventResult) : undefined;\n      var events = result.chunk.map(mapper);\n      if (fetchedEventType === EventType.RoomMessageEncrypted) {\n        var allEvents = originalEvent ? events.concat(originalEvent) : events;\n        yield Promise.all(allEvents.map(e => _this53.decryptEventIfNeeded(e)));\n        if (eventType !== null) {\n          events = events.filter(e => e.getType() === eventType);\n        }\n      }\n      if (originalEvent && relationType === RelationType.Replace) {\n        events = events.filter(e => e.getSender() === originalEvent.getSender());\n      }\n      return {\n        originalEvent: originalEvent !== null && originalEvent !== void 0 ? originalEvent : null,\n        events,\n        nextBatch: (_result$next_batch = result.next_batch) !== null && _result$next_batch !== void 0 ? _result$next_batch : null,\n        prevBatch: (_result$prev_batch = result.prev_batch) !== null && _result$prev_batch !== void 0 ? _result$prev_batch : null\n      };\n    })();\n  }\n\n  /**\n   * Generates a random string suitable for use as a client secret. <strong>This\n   * method is experimental and may change.</strong>\n   * @returns A new client secret\n   */\n  generateClientSecret() {\n    return secureRandomString(32);\n  }\n\n  /**\n   * Attempts to decrypt an event\n   * @param event - The event to decrypt\n   * @returns A decryption promise\n   */\n  decryptEventIfNeeded(event, options) {\n    if (event.isState() && !this.enableEncryptedStateEvents) {\n      return Promise.resolve();\n    }\n    if (event.shouldAttemptDecryption() && this.getCrypto()) {\n      event.attemptDecryption(this.cryptoBackend, options);\n    }\n    if (event.isBeingDecrypted()) {\n      return event.getDecryptionPromise();\n    } else {\n      return Promise.resolve();\n    }\n  }\n  termsUrlForService(serviceType, baseUrl) {\n    switch (serviceType) {\n      case SERVICE_TYPES.IS:\n        return this.http.getUrl(\"/terms\", undefined, IdentityPrefix.V2, baseUrl);\n      case SERVICE_TYPES.IM:\n        return this.http.getUrl(\"/terms\", undefined, \"/_matrix/integrations/v1\", baseUrl);\n      default:\n        throw new Error(\"Unsupported service type\");\n    }\n  }\n\n  /**\n   * Get the Homeserver URL of this client\n   * @returns Homeserver URL of this client\n   */\n  getHomeserverUrl() {\n    return this.baseUrl;\n  }\n\n  /**\n   * Get the identity server URL of this client\n   * @param stripProto - whether or not to strip the protocol from the URL\n   * @returns Identity server URL of this client\n   */\n  getIdentityServerUrl() {\n    var _this$idBaseUrl, _this$idBaseUrl2;\n    var stripProto = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n    if (stripProto && ((_this$idBaseUrl = this.idBaseUrl) !== null && _this$idBaseUrl !== void 0 && _this$idBaseUrl.startsWith(\"http://\") || (_this$idBaseUrl2 = this.idBaseUrl) !== null && _this$idBaseUrl2 !== void 0 && _this$idBaseUrl2.startsWith(\"https://\"))) {\n      return this.idBaseUrl.split(\"://\")[1];\n    }\n    return this.idBaseUrl;\n  }\n\n  /**\n   * Set the identity server URL of this client\n   * @param url - New identity server URL\n   */\n  setIdentityServerUrl(url) {\n    this.idBaseUrl = utils.ensureNoTrailingSlash(url);\n    this.http.setIdBaseUrl(this.idBaseUrl);\n  }\n\n  /**\n   * Get the access token associated with this account.\n   * @returns The access_token or null\n   */\n  getAccessToken() {\n    return this.http.opts.accessToken || null;\n  }\n\n  /**\n   * Get the refresh token associated with this account.\n   * @returns The refresh_token or null\n   */\n  getRefreshToken() {\n    var _this$http$opts$refre;\n    return (_this$http$opts$refre = this.http.opts.refreshToken) !== null && _this$http$opts$refre !== void 0 ? _this$http$opts$refre : null;\n  }\n\n  /**\n   * Set the access token associated with this account.\n   * @param token - The new access token.\n   */\n  setAccessToken(token) {\n    this.http.opts.accessToken = token;\n    // The /versions response can vary for different users so clear the cache\n    this.serverVersionsPromise = undefined;\n  }\n\n  /**\n   * @returns true if there is a valid access_token for this client.\n   */\n  isLoggedIn() {\n    return this.http.opts.accessToken !== undefined;\n  }\n\n  /**\n   * Make up a new transaction id\n   *\n   * @returns a new, unique, transaction id\n   */\n  makeTxnId() {\n    return \"m\" + new Date().getTime() + \".\" + this.txnCtr++;\n  }\n\n  /**\n   * Check whether a username is available prior to registration. An error response\n   * indicates an invalid/unavailable username.\n   * @param username - The username to check the availability of.\n   * @returns Promise which resolves: to boolean of whether the username is available.\n   */\n  isUsernameAvailable(username) {\n    return this.http.authedRequest(Method.Get, \"/register/available\", {\n      username\n    }).then(response => {\n      return response.available;\n    }).catch(response => {\n      if (response.errcode === \"M_USER_IN_USE\") {\n        return false;\n      }\n      return Promise.reject(response);\n    });\n  }\n\n  /**\n   * @param bindThreepids - Set key 'email' to true to bind any email\n   *     threepid uses during registration in the identity server. Set 'msisdn' to\n   *     true to bind msisdn.\n   * @returns Promise which resolves to a RegisterResponse object\n   * @returns Rejects: with an error response.\n   */\n  register(username, password, sessionId, auth, bindThreepids, guestAccessToken, inhibitLogin) {\n    if (sessionId) {\n      auth.session = sessionId;\n    }\n    var params = {\n      auth: auth,\n      refresh_token: true // always ask for a refresh token - does nothing if unsupported\n    };\n    if (username !== undefined && username !== null) {\n      params.username = username;\n    }\n    if (password !== undefined && password !== null) {\n      params.password = password;\n    }\n    if (guestAccessToken !== undefined && guestAccessToken !== null) {\n      params.guest_access_token = guestAccessToken;\n    }\n    if (inhibitLogin !== undefined && inhibitLogin !== null) {\n      params.inhibit_login = inhibitLogin;\n    }\n    return this.registerRequest(params);\n  }\n\n  /**\n   * Register a guest account.\n   * This method returns the auth info needed to create a new authenticated client,\n   * Remember to call `setGuest(true)` on the (guest-)authenticated client, e.g:\n   * ```javascript\n   * const tmpClient = await sdk.createClient(MATRIX_INSTANCE);\n   * const { user_id, device_id, access_token } = tmpClient.registerGuest();\n   * const client = createClient({\n   *   baseUrl: MATRIX_INSTANCE,\n   *   accessToken: access_token,\n   *   userId: user_id,\n   *   deviceId: device_id,\n   * })\n   * client.setGuest(true);\n   * ```\n   *\n   * @param body - JSON HTTP body to provide.\n   * @returns Promise which resolves: JSON object that contains:\n   *                   `{ user_id, device_id, access_token, home_server }`\n   * @returns Rejects: with an error response.\n   */\n  registerGuest() {\n    var {\n      body\n    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n    return this.registerRequest(body || {}, \"guest\");\n  }\n\n  /**\n   * @param data - parameters for registration request\n   * @param kind - type of user to register. may be \"guest\"\n   * @returns Promise which resolves: to the /register response\n   * @returns Rejects: with an error response.\n   */\n  registerRequest(data, kind) {\n    var params = {};\n    if (kind) {\n      params.kind = kind;\n    }\n    return this.http.request(Method.Post, \"/register\", params, data);\n  }\n\n  /**\n   * Refreshes an access token using a provided refresh token. The refresh token\n   * must be valid for the current access token known to the client instance.\n   *\n   * Note that this function will not cause a logout if the token is deemed\n   * unknown by the server - the caller is responsible for managing logout\n   * actions on error.\n   * @param refreshToken - The refresh token.\n   * @returns Promise which resolves to the new token.\n   * @returns Rejects with an error response.\n   */\n  refreshToken(refreshToken) {\n    var performRefreshRequestWithPrefix = prefix => this.http.authedRequest(Method.Post, \"/refresh\", undefined, {\n      refresh_token: refreshToken\n    }, {\n      prefix,\n      inhibitLogoutEmit: true // we don't want to cause logout loops\n    });\n\n    // First try with the (specced) /v3/ prefix.\n    // However, before Synapse 1.72.0, Synapse incorrectly required a /v1/ prefix, so we fall\n    // back to that if the request fails, for backwards compatibility.\n    return performRefreshRequestWithPrefix(ClientPrefix.V3).catch(e => {\n      if (e.errcode === \"M_UNRECOGNIZED\") {\n        return performRefreshRequestWithPrefix(ClientPrefix.V1);\n      }\n      throw e;\n    });\n  }\n\n  /**\n   * @returns Promise which resolves to the available login flows\n   * @returns Rejects: with an error response.\n   */\n  loginFlows() {\n    return this.http.request(Method.Get, \"/login\");\n  }\n\n  /**\n   * @returns Promise which resolves to a LoginResponse object\n   * @returns Rejects: with an error response.\n   *\n   * @deprecated This method has unintuitive behaviour: it updates the `MatrixClient` instance with *some* of the\n   *    returned credentials. Instead, call {@link loginRequest} and create a new `MatrixClient` instance using the\n   *    results. See https://github.com/matrix-org/matrix-js-sdk/issues/4502.\n   */\n  login(loginType, data) {\n    return this.loginRequest(_objectSpread(_objectSpread({}, data), {}, {\n      type: loginType\n    })).then(response => {\n      if (response.access_token && response.user_id) {\n        this.http.opts.accessToken = response.access_token;\n        this.credentials = {\n          userId: response.user_id\n        };\n      }\n      return response;\n    });\n  }\n\n  /**\n   * @returns Promise which resolves to a LoginResponse object\n   * @returns Rejects: with an error response.\n   *\n   * @deprecated This method has unintuitive behaviour: it updates the `MatrixClient` instance with *some* of the\n   *   returned credentials. Instead, call {@link loginRequest} with `data.type: \"m.login.password\"`, and create a new\n   *   `MatrixClient` instance using the results. See https://github.com/matrix-org/matrix-js-sdk/issues/4502.\n   */\n  loginWithPassword(user, password) {\n    return this.login(\"m.login.password\", {\n      user: user,\n      password: password\n    });\n  }\n\n  /**\n   * @param redirectUrl - The URL to redirect to after the HS\n   * authenticates with CAS.\n   * @returns The HS URL to hit to begin the CAS login process.\n   */\n  getCasLoginUrl(redirectUrl) {\n    return this.getSsoLoginUrl(redirectUrl, \"cas\");\n  }\n\n  /**\n   * @param redirectUrl - The URL to redirect to after the HS\n   *     authenticates with the SSO.\n   * @param loginType - The type of SSO login we are doing (sso or cas).\n   *     Defaults to 'sso'.\n   * @param idpId - The ID of the Identity Provider being targeted, optional.\n   * @param action - the SSO flow to indicate to the IdP, optional.\n   * @returns The HS URL to hit to begin the SSO login process.\n   */\n  getSsoLoginUrl(redirectUrl) {\n    var loginType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : \"sso\";\n    var idpId = arguments.length > 2 ? arguments[2] : undefined;\n    var action = arguments.length > 3 ? arguments[3] : undefined;\n    var url = \"/login/\" + loginType + \"/redirect\";\n    if (idpId) {\n      url += \"/\" + idpId;\n    }\n    var params = {\n      redirectUrl,\n      [SSO_ACTION_PARAM.stable]: action,\n      [SSO_ACTION_PARAM.unstable]: action\n    };\n    return this.http.getUrl(url, params).href;\n  }\n\n  /**\n   * @param token - Login token previously received from homeserver\n   * @returns Promise which resolves to a LoginResponse object\n   * @returns Rejects: with an error response.\n   *\n   * @deprecated This method has unintuitive behaviour: it updates the `MatrixClient` instance with *some* of the\n   *   returned credentials. Instead, call {@link loginRequest} with `data.type: \"m.login.token\"`, and create a new\n   *   `MatrixClient` instance using the results. See https://github.com/matrix-org/matrix-js-sdk/issues/4502.\n   */\n  loginWithToken(token) {\n    return this.login(\"m.login.token\", {\n      token: token\n    });\n  }\n\n  /**\n   * Sends a `POST /login` request to the server.\n   *\n   * If successful, this will create a new device and access token for the user.\n   *\n   * @see {@link MatrixClient.loginFlows} which makes a `GET /login` request.\n   * @see https://spec.matrix.org/v1.13/client-server-api/#post_matrixclientv3login\n   *\n   * @param data - Credentials and other details for the login request.\n   */\n  loginRequest(data) {\n    var _this54 = this;\n    return _asyncToGenerator(function* () {\n      return yield _this54.http.authedRequest(Method.Post, \"/login\", undefined, data);\n    })();\n  }\n\n  /**\n   * Logs out the current session.\n   * Obviously, further calls that require authorisation should fail after this\n   * method is called. The state of the MatrixClient object is not affected:\n   * it is up to the caller to either reset or destroy the MatrixClient after\n   * this method succeeds.\n   * @param stopClient - whether to stop the client before calling /logout to prevent invalid token errors.\n   * @returns Promise which resolves: On success, the empty object `{}`\n   */\n  logout() {\n    var _arguments13 = arguments,\n      _this55 = this;\n    return _asyncToGenerator(function* () {\n      var stopClient = _arguments13.length > 0 && _arguments13[0] !== undefined ? _arguments13[0] : false;\n      if (stopClient) {\n        _this55.stopClient();\n        _this55.http.abort();\n      }\n      return _this55.http.authedRequest(Method.Post, \"/logout\");\n    })();\n  }\n\n  /**\n   * Deactivates the logged-in account.\n   * Obviously, further calls that require authorisation should fail after this\n   * method is called. The state of the MatrixClient object is not affected:\n   * it is up to the caller to either reset or destroy the MatrixClient after\n   * this method succeeds.\n   * @param auth - Optional. Auth data to supply for User-Interactive auth.\n   * @param erase - Optional. If set, send as `erase` attribute in the\n   * JSON request body, indicating whether the account should be erased. Defaults\n   * to false.\n   * @returns Promise which resolves: On success, the empty object\n   */\n  deactivateAccount(auth, erase) {\n    var body = {};\n    if (auth) {\n      body.auth = auth;\n    }\n    if (erase !== undefined) {\n      body.erase = erase;\n    }\n    return this.http.authedRequest(Method.Post, \"/account/deactivate\", undefined, body);\n  }\n\n  /**\n   * Make a request for an `m.login.token` to be issued as per\n   * https://spec.matrix.org/v1.7/client-server-api/#post_matrixclientv1loginget_token\n   *\n   * The server may require User-Interactive auth.\n   *\n   * @param auth - Optional. Auth data to supply for User-Interactive auth.\n   * @returns Promise which resolves: On success, the token response\n   * or UIA auth data.\n   */\n  requestLoginToken(auth) {\n    var _this56 = this;\n    return _asyncToGenerator(function* () {\n      var body = {\n        auth\n      };\n      return _this56.http.authedRequest(Method.Post, \"/login/get_token\", undefined,\n      // no query params\n      body, {\n        prefix: ClientPrefix.V1\n      });\n    })();\n  }\n\n  /**\n   * Get the fallback URL to use for unknown interactive-auth stages.\n   *\n   * @param loginType -     the type of stage being attempted\n   * @param authSessionId - the auth session ID provided by the homeserver\n   *\n   * @returns HS URL to hit to for the fallback interface\n   */\n  getFallbackAuthUrl(loginType, authSessionId) {\n    var path = utils.encodeUri(\"/auth/$loginType/fallback/web\", {\n      $loginType: loginType\n    });\n    return this.http.getUrl(path, {\n      session: authSessionId\n    }).href;\n  }\n\n  /**\n   * Create a new room.\n   * @param options - a list of options to pass to the /createRoom API.\n   * @returns Promise which resolves: `{room_id: {string}}`\n   * @returns Rejects: with an error response.\n   */\n  createRoom(options) {\n    var _this57 = this;\n    return _asyncToGenerator(function* () {\n      var _this57$identityServe;\n      // eslint-disable-line camelcase\n      // some valid options include: room_alias_name, visibility, invite\n\n      // inject the id_access_token if inviting 3rd party addresses\n      var invitesNeedingToken = (options.invite_3pid || []).filter(i => !i.id_access_token);\n      if (invitesNeedingToken.length > 0 && (_this57$identityServe = _this57.identityServer) !== null && _this57$identityServe !== void 0 && _this57$identityServe.getAccessToken) {\n        var identityAccessToken = yield _this57.identityServer.getAccessToken();\n        if (identityAccessToken) {\n          for (var invite of invitesNeedingToken) {\n            invite.id_access_token = identityAccessToken;\n          }\n        }\n      }\n      return _this57.http.authedRequest(Method.Post, \"/createRoom\", undefined, options);\n    })();\n  }\n\n  /**\n   * Fetches relations for a given event\n   * @param roomId - the room of the event\n   * @param eventId - the id of the event\n   * @param relationType - the rel_type of the relations requested\n   * @param eventType - the event type of the relations requested\n   * @param opts - options with optional values for the request.\n   * @returns the response, with chunk, prev_batch and, next_batch.\n   */\n  fetchRelations(roomId, eventId, relationType, eventType) {\n    var opts = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {\n      dir: Direction.Backward\n    };\n    var params = opts;\n    if (Thread.hasServerSideFwdPaginationSupport === FeatureSupport.Experimental) {\n      params = replaceParam(\"dir\", \"org.matrix.msc3715.dir\", params);\n    }\n    if (this.canSupport.get(Feature.RelationsRecursion) === ServerSupport.Unstable) {\n      params = replaceParam(\"recurse\", \"org.matrix.msc3981.recurse\", params);\n    }\n    var queryString = utils.encodeParams(params);\n    var templatedUrl = \"/rooms/$roomId/relations/$eventId\";\n    if (relationType !== null) {\n      templatedUrl += \"/$relationType\";\n      if (eventType !== null) {\n        templatedUrl += \"/$eventType\";\n      }\n    } else if (eventType !== null) {\n      this.logger.warn(\"eventType: \".concat(eventType, \" ignored when fetching\\n            relations as relationType is null\"));\n      eventType = null;\n    }\n    var path = utils.encodeUri(templatedUrl + \"?\" + queryString, {\n      $roomId: roomId,\n      $eventId: eventId,\n      $relationType: relationType,\n      $eventType: eventType\n    });\n    return this.http.authedRequest(Method.Get, path, undefined, undefined, {\n      prefix: ClientPrefix.V1\n    });\n  }\n\n  /**\n   * @returns Promise which resolves: TODO\n   * @returns Rejects: with an error response.\n   */\n  roomState(roomId) {\n    var path = utils.encodeUri(\"/rooms/$roomId/state\", {\n      $roomId: roomId\n    });\n    return this.http.authedRequest(Method.Get, path);\n  }\n\n  /**\n   * Get an event in a room by its event id.\n   *\n   * @returns Promise which resolves to an object containing the event.\n   * @returns Rejects: with an error response.\n   */\n  fetchRoomEvent(roomId, eventId) {\n    var path = utils.encodeUri(\"/rooms/$roomId/event/$eventId\", {\n      $roomId: roomId,\n      $eventId: eventId\n    });\n    return this.http.authedRequest(Method.Get, path);\n  }\n\n  /**\n   * @param includeMembership - the membership type to include in the response\n   * @param excludeMembership - the membership type to exclude from the response\n   * @param atEventId - the id of the event for which moment in the timeline the members should be returned for\n   * @returns Promise which resolves: dictionary of userid to profile information\n   * @returns Rejects: with an error response.\n   */\n  members(roomId, includeMembership, excludeMembership, atEventId) {\n    var queryParams = {};\n    if (includeMembership) {\n      queryParams.membership = includeMembership;\n    }\n    if (excludeMembership) {\n      queryParams.not_membership = excludeMembership;\n    }\n    if (atEventId) {\n      queryParams.at = atEventId;\n    }\n    var queryString = utils.encodeParams(queryParams);\n    var path = utils.encodeUri(\"/rooms/$roomId/members?\" + queryString, {\n      $roomId: roomId\n    });\n    return this.http.authedRequest(Method.Get, path);\n  }\n\n  /**\n   * Upgrades a room to a new protocol version\n   * @param newVersion - The target version to upgrade to\n   * @param additionalCreators - an optional list of user IDs of users who\n   *        should have the same permissions as the user performing the\n   *        upgrade\n   * @returns Promise which resolves: Object with key 'replacement_room'\n   * @returns Rejects: with an error response.\n   */\n  upgradeRoom(roomId, newVersion, additionalCreators) {\n    // eslint-disable-line camelcase\n    var path = utils.encodeUri(\"/rooms/$roomId/upgrade\", {\n      $roomId: roomId\n    });\n    return this.http.authedRequest(Method.Post, path, undefined, {\n      new_version: newVersion,\n      additional_creators: additionalCreators\n    });\n  }\n\n  /**\n   * Retrieve a state event.\n   * @returns Promise which resolves: TODO\n   * @returns Rejects: with an error response.\n   */\n  getStateEvent(roomId, eventType, stateKey) {\n    var pathParams = {\n      $roomId: roomId,\n      $eventType: eventType,\n      $stateKey: stateKey\n    };\n    var path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n    if (stateKey !== undefined) {\n      path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n    }\n    return this.http.authedRequest(Method.Get, path);\n  }\n\n  /**\n   * Send a state event into a room\n   * @param roomId - ID of the room to send the event into\n   * @param eventType - type of the state event to send\n   * @param content - content of the event to send\n   * @param stateKey - the stateKey to send into the room\n   * @param opts - Options for the request function.\n   * @returns Promise which resolves: TODO\n   * @returns Rejects: with an error response.\n   */\n  sendStateEvent(roomId, eventType, content) {\n    var _arguments14 = arguments,\n      _this58 = this;\n    return _asyncToGenerator(function* () {\n      var stateKey = _arguments14.length > 3 && _arguments14[3] !== undefined ? _arguments14[3] : \"\";\n      var opts = _arguments14.length > 4 && _arguments14[4] !== undefined ? _arguments14[4] : {};\n      var room = _this58.getRoom(roomId);\n      var event = new MatrixEvent({\n        room_id: roomId,\n        type: eventType,\n        state_key: stateKey,\n        // Cast safety: StateEvents[K] is a stronger bound than IContent, which has [key: string]: any\n        content: content\n      });\n      yield _this58.encryptStateEventIfNeeded(event, room !== null && room !== void 0 ? room : undefined);\n      var pathParams = {\n        $roomId: roomId,\n        $eventType: event.getWireType(),\n        $stateKey: event.getWireStateKey()\n      };\n      var path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n      if (stateKey !== undefined) {\n        path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n      }\n      return _this58.http.authedRequest(Method.Put, path, undefined, event.getWireContent(), opts);\n    })();\n  }\n  encryptStateEventIfNeeded(event, room) {\n    var _this59 = this;\n    return _asyncToGenerator(function* () {\n      if (!_this59.enableEncryptedStateEvents) {\n        return;\n      }\n\n      // If the room is unknown, we cannot encrypt for it\n      if (!room) return;\n      if (!_this59.cryptoBackend && _this59.usingExternalCrypto) {\n        // The client has opted to allow sending messages to encrypted\n        // rooms even if the room is encrypted, and we haven't set up\n        // crypto. This is useful for users of matrix-org/pantalaimon\n        return;\n      }\n      if (!_this59.cryptoBackend) {\n        throw new Error(\"This room is configured to use encryption, but your client does not support encryption.\");\n      }\n\n      // Check regular encryption conditions.\n      if (!(yield _this59.shouldEncryptEventForRoom(event, room))) {\n        return;\n      }\n\n      // If the crypto impl thinks we shouldn't encrypt, then we shouldn't.\n      // Safety: we checked the crypto impl exists above.\n      if (!(yield _this59.cryptoBackend.isStateEncryptionEnabledInRoom(room.roomId))) {\n        return;\n      }\n\n      // Check if the event is excluded under MSC4362\n      if ([\"m.room.create\", \"m.room.member\", \"m.room.join_rules\", \"m.room.power_levels\", \"m.room.third_party_invite\", \"m.room.history_visibility\", \"m.room.guest_access\", \"m.room.encryption\"].includes(event.getType())) {\n        return;\n      }\n      yield _this59.cryptoBackend.encryptEvent(event, room);\n    })();\n  }\n\n  /**\n   * @returns Promise which resolves: TODO\n   * @returns Rejects: with an error response.\n   */\n  roomInitialSync(roomId, limit) {\n    var _limit$toString;\n    var path = utils.encodeUri(\"/rooms/$roomId/initialSync\", {\n      $roomId: roomId\n    });\n    return this.http.authedRequest(Method.Get, path, {\n      limit: (_limit$toString = limit === null || limit === void 0 ? void 0 : limit.toString()) !== null && _limit$toString !== void 0 ? _limit$toString : \"30\"\n    });\n  }\n\n  /**\n   * Set a marker to indicate the point in a room before which the user has read every\n   * event. This can be retrieved from room account data (the event type is `m.fully_read`)\n   * and displayed as a horizontal line in the timeline that is visually distinct to the\n   * position of the user's own read receipt.\n   * @param roomId - ID of the room that has been read\n   * @param rmEventId - ID of the event that has been read\n   * @param rrEventId - ID of the event tracked by the read receipt. This is here\n   * for convenience because the RR and the RM are commonly updated at the same time as\n   * each other. Optional.\n   * @param rpEventId - rpEvent the m.read.private read receipt event for when we\n   * don't want other users to see the read receipts. This is experimental. Optional.\n   * @returns Promise which resolves: the empty object, `{}`.\n   */\n  setRoomReadMarkersHttpRequest(roomId, rmEventId, rrEventId, rpEventId) {\n    var _this60 = this;\n    return _asyncToGenerator(function* () {\n      var path = utils.encodeUri(\"/rooms/$roomId/read_markers\", {\n        $roomId: roomId\n      });\n      var content = {\n        [ReceiptType.FullyRead]: rmEventId,\n        [ReceiptType.Read]: rrEventId\n      };\n      if ((yield _this60.doesServerSupportUnstableFeature(\"org.matrix.msc2285.stable\")) || (yield _this60.isVersionSupported(\"v1.4\"))) {\n        content[ReceiptType.ReadPrivate] = rpEventId;\n      }\n      return _this60.http.authedRequest(Method.Post, path, undefined, content);\n    })();\n  }\n\n  /**\n   * @returns Promise which resolves: A list of the user's current rooms\n   * @returns Rejects: with an error response.\n   */\n  getJoinedRooms() {\n    var path = utils.encodeUri(\"/joined_rooms\", {});\n    return this.http.authedRequest(Method.Get, path);\n  }\n\n  /**\n   * Retrieve membership info. for a room.\n   * @param roomId - ID of the room to get membership for\n   * @returns Promise which resolves: A list of currently joined users\n   *                                 and their profile data.\n   * @returns Rejects: with an error response.\n   */\n  getJoinedRoomMembers(roomId) {\n    var path = utils.encodeUri(\"/rooms/$roomId/joined_members\", {\n      $roomId: roomId\n    });\n    return this.http.authedRequest(Method.Get, path);\n  }\n\n  /**\n   * Get the public rooms list from the server. Supports pagination\n   * @param params - Options for this request\n   * @returns Promise which resolves: IPublicRoomsResponse\n   * @returns Rejects: with an error response.\n   * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n   * @see MatrixSafetyError\n   */\n  publicRooms() {\n    var _ref9 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n    var {\n        server,\n        limit,\n        since\n      } = _ref9,\n      options = _objectWithoutProperties(_ref9, _excluded);\n    if (Object.keys(options).length === 0) {\n      var queryParams = {\n        server,\n        limit,\n        since\n      };\n      return this.http.authedRequest(Method.Get, \"/publicRooms\", queryParams);\n    } else {\n      var _queryParams = {\n        server\n      };\n      var _body = _objectSpread({\n        limit,\n        since\n      }, options);\n      return this.http.authedRequest(Method.Post, \"/publicRooms\", _queryParams, _body);\n    }\n  }\n\n  /**\n   * Create an alias to room ID mapping.\n   * @param alias - The room alias to create.\n   * @param roomId - The room ID to link the alias to.\n   * @returns Promise which resolves: an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n  createAlias(alias, roomId) {\n    var path = utils.encodeUri(\"/directory/room/$alias\", {\n      $alias: alias\n    });\n    var data = {\n      room_id: roomId\n    };\n    return this.http.authedRequest(Method.Put, path, undefined, data);\n  }\n\n  /**\n   * Delete an alias to room ID mapping. This alias must be on your local server,\n   * and you must have sufficient access to do this operation.\n   * @param alias - The room alias to delete.\n   * @returns Promise which resolves: an empty object `{}`.\n   * @returns Rejects: with an error response.\n   */\n  deleteAlias(alias) {\n    var path = utils.encodeUri(\"/directory/room/$alias\", {\n      $alias: alias\n    });\n    return this.http.authedRequest(Method.Delete, path);\n  }\n\n  /**\n   * Gets the local aliases for the room. Note: this includes all local aliases, unlike the\n   * curated list from the m.room.canonical_alias state event.\n   * @param roomId - The room ID to get local aliases for.\n   * @returns Promise which resolves: an object with an `aliases` property, containing an array of local aliases\n   * @returns Rejects: with an error response.\n   */\n  getLocalAliases(roomId) {\n    var path = utils.encodeUri(\"/rooms/$roomId/aliases\", {\n      $roomId: roomId\n    });\n    var prefix = ClientPrefix.V3;\n    return this.http.authedRequest(Method.Get, path, undefined, undefined, {\n      prefix\n    });\n  }\n\n  /**\n   * Get room info for the given alias.\n   * @param alias - The room alias to resolve.\n   * @returns Promise which resolves: Object with room_id and servers.\n   * @returns Rejects: with an error response.\n   */\n  getRoomIdForAlias(alias) {\n    // eslint-disable-line camelcase\n    var path = utils.encodeUri(\"/directory/room/$alias\", {\n      $alias: alias\n    });\n    return this.http.authedRequest(Method.Get, path);\n  }\n\n  /**\n   * Get the visibility of a room in the current HS's room directory\n   * @returns Promise which resolves: TODO\n   * @returns Rejects: with an error response.\n   */\n  getRoomDirectoryVisibility(roomId) {\n    var path = utils.encodeUri(\"/directory/list/room/$roomId\", {\n      $roomId: roomId\n    });\n    return this.http.authedRequest(Method.Get, path);\n  }\n\n  /**\n   * Set the visibility of a room in the current HS's room directory\n   * @param visibility - \"public\" to make the room visible\n   *                 in the public directory, or \"private\" to make\n   *                 it invisible.\n   * @returns Promise which resolves: to an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n  setRoomDirectoryVisibility(roomId, visibility) {\n    var path = utils.encodeUri(\"/directory/list/room/$roomId\", {\n      $roomId: roomId\n    });\n    return this.http.authedRequest(Method.Put, path, undefined, {\n      visibility\n    });\n  }\n\n  /**\n   * Query the user directory with a term matching user IDs, display names and domains.\n   * @param options\n   * @param options.term - the term with which to search.\n   * @param options.limit - the maximum number of results to return. The server will apply a limit if unspecified.\n   * @returns Promise which resolves: an array of results.\n   */\n  searchUserDirectory(_ref0) {\n    var {\n      term,\n      limit\n    } = _ref0;\n    var body = {\n      search_term: term\n    };\n    if (limit !== undefined) {\n      body.limit = limit;\n    }\n    return this.http.authedRequest(Method.Post, \"/user_directory/search\", undefined, body);\n  }\n\n  /**\n   * Upload a file to the media repository on the homeserver.\n   *\n   * @param file - The object to upload. On a browser, something that\n   *   can be sent to XMLHttpRequest.send (typically a File).  Under node.js,\n   *   a a Buffer, String or ReadStream.\n   *\n   * @param opts -  options object\n   *\n   * @returns Promise which resolves to response object, or rejects with an error (usually a MatrixError).\n   */\n  uploadContent(file, opts) {\n    return this.http.uploadContent(file, opts);\n  }\n\n  /**\n   * Cancel a file upload in progress\n   * @param upload - The object returned from uploadContent\n   * @returns true if canceled, otherwise false\n   */\n  cancelUpload(upload) {\n    return this.http.cancelUpload(upload);\n  }\n\n  /**\n   * Get a list of all file uploads in progress\n   * @returns Array of objects representing current uploads.\n   * Currently in progress is element 0. Keys:\n   *  - promise: The promise associated with the upload\n   *  - loaded: Number of bytes uploaded\n   *  - total: Total number of bytes to upload\n   */\n  getCurrentUploads() {\n    return this.http.getCurrentUploads();\n  }\n\n  /**\n   * @param info - The kind of info to retrieve (e.g. 'displayname',\n   * 'avatar_url').\n   * @returns Promise which resolves: TODO\n   * @returns Rejects: with an error response.\n   */\n  getProfileInfo(userId, info\n  // eslint-disable-next-line camelcase\n  ) {\n    var path = info ? utils.encodeUri(\"/profile/$userId/$info\", {\n      $userId: userId,\n      $info: info\n    }) : utils.encodeUri(\"/profile/$userId\", {\n      $userId: userId\n    });\n    return this.http.authedRequest(Method.Get, path);\n  }\n\n  /**\n   * Determine if the server supports extended profiles, as described by MSC4133.\n   *\n   * @returns `true` if supported, otherwise `false`\n   */\n  doesServerSupportExtendedProfiles() {\n    var _this61 = this;\n    return _asyncToGenerator(function* () {\n      return (yield _this61.isVersionSupported(\"v1.16\")) || (yield _this61.doesServerSupportUnstableFeature(UNSTABLE_MSC4133_EXTENDED_PROFILES)) || (yield _this61.doesServerSupportUnstableFeature(STABLE_MSC4133_EXTENDED_PROFILES));\n    })();\n  }\n\n  /**\n   * Get the prefix used for extended profile requests.\n   *\n   * @returns The prefix for use with `authedRequest`\n   */\n  getExtendedProfileRequestPrefix() {\n    var _this62 = this;\n    return _asyncToGenerator(function* () {\n      if ((yield _this62.isVersionSupported(\"v1.16\")) || (yield _this62.doesServerSupportUnstableFeature(\"uk.tcpip.msc4133.stable\"))) {\n        return ClientPrefix.V3;\n      }\n      return \"/_matrix/client/unstable/uk.tcpip.msc4133\";\n    })();\n  }\n\n  /**\n   * Fetch a user's *extended* profile, which may include additional keys.\n   *\n   * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n   * @param userId The user ID to fetch the profile of.\n   * @returns A set of keys to property values.\n   *\n   * @throws An error if the server does not support MSC4133.\n   * @throws A M_NOT_FOUND error if the profile could not be found.\n   */\n  getExtendedProfile(userId) {\n    var _this63 = this;\n    return _asyncToGenerator(function* () {\n      if (!(yield _this63.doesServerSupportExtendedProfiles())) {\n        throw new Error(\"Server does not support extended profiles\");\n      }\n      return _this63.http.authedRequest(Method.Get, utils.encodeUri(\"/profile/$userId\", {\n        $userId: userId\n      }), undefined, undefined, {\n        prefix: yield _this63.getExtendedProfileRequestPrefix()\n      });\n    })();\n  }\n\n  /**\n   * Fetch a specific key from the user's *extended* profile.\n   *\n   * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n   * @param userId The user ID to fetch the profile of.\n   * @param key The key of the property to fetch.\n   * @returns The property value.\n   *\n   * @throws An error if the server does not support MSC4133.\n   * @throws A M_NOT_FOUND error if the key was not set OR the profile could not be found.\n   */\n  getExtendedProfileProperty(userId, key) {\n    var _this64 = this;\n    return _asyncToGenerator(function* () {\n      if (!(yield _this64.doesServerSupportExtendedProfiles())) {\n        throw new Error(\"Server does not support extended profiles\");\n      }\n      var profile = yield _this64.http.authedRequest(Method.Get, utils.encodeUri(\"/profile/$userId/$key\", {\n        $userId: userId,\n        $key: key\n      }), undefined, undefined, {\n        prefix: yield _this64.getExtendedProfileRequestPrefix()\n      });\n      return profile[key];\n    })();\n  }\n\n  /**\n   * Set a property on your *extended* profile.\n   *\n   * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n   * @param key The key of the property to set.\n   * @param value The value to set on the property.\n   *\n   * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n   */\n  setExtendedProfileProperty(key, value) {\n    var _this65 = this;\n    return _asyncToGenerator(function* () {\n      if (!(yield _this65.doesServerSupportExtendedProfiles())) {\n        throw new Error(\"Server does not support extended profiles\");\n      }\n      var userId = _this65.getUserId();\n      yield _this65.http.authedRequest(Method.Put, utils.encodeUri(\"/profile/$userId/$key\", {\n        $userId: userId,\n        $key: key\n      }), undefined, {\n        [key]: value\n      }, {\n        prefix: yield _this65.getExtendedProfileRequestPrefix()\n      });\n    })();\n  }\n\n  /**\n   * Delete a property on your *extended* profile.\n   *\n   * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n   * @param key The key of the property to delete.\n   *\n   * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n   */\n  deleteExtendedProfileProperty(key) {\n    var _this66 = this;\n    return _asyncToGenerator(function* () {\n      if (!(yield _this66.doesServerSupportExtendedProfiles())) {\n        throw new Error(\"Server does not support extended profiles\");\n      }\n      var userId = _this66.getUserId();\n      yield _this66.http.authedRequest(Method.Delete, utils.encodeUri(\"/profile/$userId/$key\", {\n        $userId: userId,\n        $key: key\n      }), undefined, undefined, {\n        prefix: yield _this66.getExtendedProfileRequestPrefix()\n      });\n    })();\n  }\n\n  /**\n   * Update multiple properties on your *extended* profile. This will\n   * merge with any existing keys.\n   *\n   * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n   * @param profile The profile object to merge with the existing profile.\n   * @returns The newly merged profile.\n   *\n   * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n   */\n  patchExtendedProfile(profile) {\n    var _this67 = this;\n    return _asyncToGenerator(function* () {\n      if (!(yield _this67.doesServerSupportExtendedProfiles())) {\n        throw new Error(\"Server does not support extended profiles\");\n      }\n      var userId = _this67.getUserId();\n      return _this67.http.authedRequest(Method.Patch, utils.encodeUri(\"/profile/$userId\", {\n        $userId: userId\n      }), {}, profile, {\n        prefix: yield _this67.getExtendedProfileRequestPrefix()\n      });\n    })();\n  }\n\n  /**\n   * Set multiple properties on your *extended* profile. This will completely\n   * replace the existing profile, removing any unspecified keys.\n   *\n   * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n   * @param profile The profile object to set.\n   *\n   * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n   */\n  setExtendedProfile(profile) {\n    var _this68 = this;\n    return _asyncToGenerator(function* () {\n      if (!(yield _this68.doesServerSupportExtendedProfiles())) {\n        throw new Error(\"Server does not support extended profiles\");\n      }\n      var userId = _this68.getUserId();\n      yield _this68.http.authedRequest(Method.Put, utils.encodeUri(\"/profile/$userId\", {\n        $userId: userId\n      }), {}, profile, {\n        prefix: yield _this68.getExtendedProfileRequestPrefix()\n      });\n    })();\n  }\n\n  /**\n   * @returns Promise which resolves to a list of the user's threepids.\n   * @returns Rejects: with an error response.\n   */\n  getThreePids() {\n    return this.http.authedRequest(Method.Get, \"/account/3pid\");\n  }\n\n  /**\n   * Add a 3PID to your homeserver account. This API does not use an identity\n   * server, as the homeserver is expected to handle 3PID ownership validation.\n   *\n   * @param data - A object with 3PID validation data from having called\n   * `account/3pid/<medium>/requestToken` on the homeserver.\n   * @returns Promise which resolves: to an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n  addThreePidOnly(data) {\n    var _this69 = this;\n    return _asyncToGenerator(function* () {\n      var path = \"/account/3pid/add\";\n      return _this69.http.authedRequest(Method.Post, path, undefined, data);\n    })();\n  }\n\n  /**\n   * Bind a 3PID for discovery onto an identity server via the homeserver. The\n   * identity server handles 3PID ownership validation and the homeserver records\n   * the new binding to track where all 3PIDs for the account are bound.\n   *\n   * @param data - A object with 3PID validation data from having called\n   * `validate/<medium>/requestToken` on the identity server. It should also\n   * contain `id_server` and `id_access_token` fields as well.\n   * @returns Promise which resolves: to an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n  bindThreePid(data) {\n    var _this70 = this;\n    return _asyncToGenerator(function* () {\n      var path = \"/account/3pid/bind\";\n      return _this70.http.authedRequest(Method.Post, path, undefined, data);\n    })();\n  }\n\n  /**\n   * Unbind a 3PID for discovery on an identity server via the homeserver. The\n   * homeserver removes its record of the binding to keep an updated record of\n   * where all 3PIDs for the account are bound.\n   *\n   * @param medium - The threepid medium (eg. 'email')\n   * @param address - The threepid address (eg. 'bob\\@example.com')\n   *        this must be as returned by getThreePids.\n   * @returns Promise which resolves: on success\n   * @returns Rejects: with an error response.\n   */\n  unbindThreePid(medium, address\n  // eslint-disable-next-line camelcase\n  ) {\n    var _this71 = this;\n    return _asyncToGenerator(function* () {\n      var path = \"/account/3pid/unbind\";\n      var data = {\n        medium,\n        address,\n        id_server: _this71.getIdentityServerUrl(true)\n      };\n      return _this71.http.authedRequest(Method.Post, path, undefined, data);\n    })();\n  }\n\n  /**\n   * @param medium - The threepid medium (eg. 'email')\n   * @param address - The threepid address (eg. 'bob\\@example.com')\n   *        this must be as returned by getThreePids.\n   * @returns Promise which resolves: The server response on success\n   *     (generally the empty JSON object)\n   * @returns Rejects: with an error response.\n   */\n  deleteThreePid(medium, address\n  // eslint-disable-next-line camelcase\n  ) {\n    var path = \"/account/3pid/delete\";\n    return this.http.authedRequest(Method.Post, path, undefined, {\n      medium,\n      address\n    });\n  }\n\n  /**\n   * Make a request to change your password.\n   * @param newPassword - The new desired password.\n   * @param logoutDevices - Should all sessions be logged out after the password change. Defaults to true.\n   * @returns Promise which resolves: to an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n  setPassword(authDict, newPassword, logoutDevices) {\n    var path = \"/account/password\";\n    var data = {\n      auth: authDict,\n      new_password: newPassword,\n      logout_devices: logoutDevices\n    };\n    return this.http.authedRequest(Method.Post, path, undefined, data);\n  }\n\n  /**\n   * Gets all devices recorded for the logged-in user\n   * @returns Promise which resolves: result object\n   * @returns Rejects: with an error response.\n   */\n  getDevices() {\n    return this.http.authedRequest(Method.Get, \"/devices\");\n  }\n\n  /**\n   * Gets specific device details for the logged-in user\n   * @param deviceId -  device to query\n   * @returns Promise which resolves: result object\n   * @returns Rejects: with an error response.\n   */\n  getDevice(deviceId) {\n    var path = utils.encodeUri(\"/devices/$device_id\", {\n      $device_id: deviceId\n    });\n    return this.http.authedRequest(Method.Get, path);\n  }\n\n  /**\n   * Update the given device\n   *\n   * @param deviceId -  device to update\n   * @param body -       body of request\n   * @returns Promise which resolves: to an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n  // eslint-disable-next-line camelcase\n  setDeviceDetails(deviceId, body) {\n    var path = utils.encodeUri(\"/devices/$device_id\", {\n      $device_id: deviceId\n    });\n    return this.http.authedRequest(Method.Put, path, undefined, body);\n  }\n\n  /**\n   * Delete the given device\n   *\n   * @param deviceId -  device to delete\n   * @param auth - Optional. Auth data to supply for User-Interactive auth.\n   * @returns Promise which resolves: result object\n   * @returns Rejects: with an error response.\n   */\n  deleteDevice(deviceId, auth) {\n    var path = utils.encodeUri(\"/devices/$device_id\", {\n      $device_id: deviceId\n    });\n    var body = {};\n    if (auth) {\n      body.auth = auth;\n    }\n    return this.http.authedRequest(Method.Delete, path, undefined, body);\n  }\n\n  /**\n   * Delete multiple device\n   *\n   * @param devices - IDs of the devices to delete\n   * @param auth - Optional. Auth data to supply for User-Interactive auth.\n   * @returns Promise which resolves: result object\n   * @returns Rejects: with an error response.\n   */\n  deleteMultipleDevices(devices, auth) {\n    var body = {\n      devices\n    };\n    if (auth) {\n      body.auth = auth;\n    }\n    var path = \"/delete_devices\";\n    return this.http.authedRequest(Method.Post, path, undefined, body);\n  }\n\n  /**\n   * Gets all pushers registered for the logged-in user\n   *\n   * @returns Promise which resolves: Array of objects representing pushers\n   * @returns Rejects: with an error response.\n   */\n  getPushers() {\n    var _this72 = this;\n    return _asyncToGenerator(function* () {\n      var response = yield _this72.http.authedRequest(Method.Get, \"/pushers\");\n\n      // Migration path for clients that connect to a homeserver that does not support\n      // MSC3881 yet, see https://github.com/matrix-org/matrix-spec-proposals/blob/kerry/remote-push-toggle/proposals/3881-remote-push-notification-toggling.md#migration\n      if (!(yield _this72.doesServerSupportUnstableFeature(\"org.matrix.msc3881\"))) {\n        response.pushers = response.pushers.map(pusher => {\n          if (!pusher.hasOwnProperty(PUSHER_ENABLED.name)) {\n            pusher[PUSHER_ENABLED.name] = true;\n          }\n          return pusher;\n        });\n      }\n      return response;\n    })();\n  }\n\n  /**\n   * Adds a new pusher or updates an existing pusher\n   *\n   * @param pusher - Object representing a pusher\n   * @returns Promise which resolves: Empty json object on success\n   * @returns Rejects: with an error response.\n   */\n  setPusher(pusher) {\n    var path = \"/pushers/set\";\n    return this.http.authedRequest(Method.Post, path, undefined, pusher);\n  }\n\n  /**\n   * Removes an existing pusher\n   * @param pushKey - pushkey of pusher to remove\n   * @param appId - app_id of pusher to remove\n   * @returns Promise which resolves: Empty json object on success\n   * @returns Rejects: with an error response.\n   */\n  removePusher(pushKey, appId) {\n    var path = \"/pushers/set\";\n    var body = {\n      pushkey: pushKey,\n      app_id: appId,\n      kind: null // marks pusher for removal\n    };\n    return this.http.authedRequest(Method.Post, path, undefined, body);\n  }\n\n  /**\n   * Persists local notification settings\n   * @returns Promise which resolves: an empty object\n   * @returns Rejects: with an error response.\n   */\n  setLocalNotificationSettings(deviceId, notificationSettings) {\n    var key = \"\".concat(LOCAL_NOTIFICATION_SETTINGS_PREFIX.name, \".\").concat(deviceId);\n    return this.setAccountData(key, notificationSettings);\n  }\n\n  /**\n   * Get the push rules for the account from the server.\n   * @returns Promise which resolves to the push rules.\n   * @returns Rejects: with an error response.\n   */\n  getPushRules() {\n    return this.http.authedRequest(Method.Get, \"/pushrules/\").then(rules => {\n      this.setPushRules(rules);\n      return this.pushRules;\n    });\n  }\n\n  /**\n   * Update the push rules for the account. This should be called whenever\n   * updated push rules are available.\n   */\n  setPushRules(rules) {\n    // Fix-up defaults, if applicable.\n    this.pushRules = PushProcessor.rewriteDefaultRules(this.logger, rules, this.getUserId());\n    // Pre-calculate any necessary caches.\n    this.pushProcessor.updateCachedPushRuleKeys(this.pushRules);\n  }\n\n  /**\n   * @returns Promise which resolves: an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n  addPushRule(scope, kind, ruleId, body) {\n    // NB. Scope not uri encoded because devices need the '/'\n    var path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId\", {\n      $kind: kind,\n      $ruleId: ruleId\n    });\n    return this.http.authedRequest(Method.Put, path, undefined, body);\n  }\n\n  /**\n   * @returns Promise which resolves: an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n  deletePushRule(scope, kind, ruleId) {\n    // NB. Scope not uri encoded because devices need the '/'\n    var path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId\", {\n      $kind: kind,\n      $ruleId: ruleId\n    });\n    return this.http.authedRequest(Method.Delete, path);\n  }\n\n  /**\n   * Enable or disable a push notification rule.\n   * @returns Promise which resolves: to an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n  setPushRuleEnabled(scope, kind, ruleId, enabled) {\n    var path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId/enabled\", {\n      $kind: kind,\n      $ruleId: ruleId\n    });\n    return this.http.authedRequest(Method.Put, path, undefined, {\n      enabled: enabled\n    });\n  }\n\n  /**\n   * Set the actions for a push notification rule.\n   * @returns Promise which resolves: to an empty object `{}`\n   * @returns Rejects: with an error response.\n   */\n  setPushRuleActions(scope, kind, ruleId, actions) {\n    var path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId/actions\", {\n      $kind: kind,\n      $ruleId: ruleId\n    });\n    return this.http.authedRequest(Method.Put, path, undefined, {\n      actions: actions\n    });\n  }\n\n  /**\n   * Perform a server-side search.\n   * @param params\n   * @param params.next_batch - the batch token to pass in the query string\n   * @param params.body - the JSON object to pass to the request body.\n   * @param abortSignal - optional signal used to cancel the http request.\n   * @returns Promise which resolves to the search response object.\n   * @returns Rejects: with an error response.\n   */\n  search(_ref1, abortSignal) {\n    var {\n      body,\n      next_batch: nextBatch\n    } = _ref1;\n    var queryParams = {};\n    if (nextBatch) {\n      queryParams.next_batch = nextBatch;\n    }\n    return this.http.authedRequest(Method.Post, \"/search\", queryParams, body, {\n      abortSignal\n    });\n  }\n\n  /**\n   * Upload keys\n   *\n   * @param content -  body of upload request\n   *\n   * @param opts - this method no longer takes any opts,\n   *  used to take opts.device_id but this was not removed from the spec as a redundant parameter\n   *\n   * @returns Promise which resolves: result object. Rejects: with\n   *     an error response ({@link MatrixError}).\n   */\n  uploadKeysRequest(content, opts) {\n    return this.http.authedRequest(Method.Post, \"/keys/upload\", undefined, content);\n  }\n  uploadKeySignatures(content) {\n    return this.http.authedRequest(Method.Post, \"/keys/signatures/upload\", undefined, content);\n  }\n\n  /**\n   * Download device keys\n   *\n   * @param userIds -  list of users to get keys for\n   *\n   * @param token - sync token to pass in the query request, to help\n   *   the HS give the most recent results\n   *\n   * @returns Promise which resolves: result object. Rejects: with\n   *     an error response ({@link MatrixError}).\n   */\n  downloadKeysForUsers(userIds) {\n    var {\n      token\n    } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n    var content = {\n      device_keys: {}\n    };\n    if (token !== undefined) {\n      content.token = token;\n    }\n    userIds.forEach(u => {\n      content.device_keys[u] = [];\n    });\n    return this.http.authedRequest(Method.Post, \"/keys/query\", undefined, content);\n  }\n\n  /**\n   * Claim one-time keys\n   *\n   * @param devices -  a list of [userId, deviceId] pairs\n   *\n   * @param keyAlgorithm -  desired key type\n   *\n   * @param timeout - the time (in milliseconds) to wait for keys from remote\n   *     servers\n   *\n   * @returns Promise which resolves: result object. Rejects: with\n   *     an error response ({@link MatrixError}).\n   */\n  claimOneTimeKeys(devices) {\n    var keyAlgorithm = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : \"signed_curve25519\";\n    var timeout = arguments.length > 2 ? arguments[2] : undefined;\n    var queries = {};\n    if (keyAlgorithm === undefined) {\n      keyAlgorithm = \"signed_curve25519\";\n    }\n    for (var [userId, _deviceId] of devices) {\n      var query = queries[userId] || {};\n      safeSet(queries, userId, query);\n      safeSet(query, _deviceId, keyAlgorithm);\n    }\n    var content = {\n      one_time_keys: queries\n    };\n    if (timeout) {\n      content.timeout = timeout;\n    }\n    var path = \"/keys/claim\";\n    return this.http.authedRequest(Method.Post, path, undefined, content);\n  }\n\n  /**\n   * Ask the server for a list of users who have changed their device lists\n   * between a pair of sync tokens\n   *\n   *\n   * @returns Promise which resolves: result object. Rejects: with\n   *     an error response ({@link MatrixError}).\n   */\n  getKeyChanges(oldToken, newToken) {\n    var qps = {\n      from: oldToken,\n      to: newToken\n    };\n    return this.http.authedRequest(Method.Get, \"/keys/changes\", qps);\n  }\n  uploadDeviceSigningKeys(auth, keys) {\n    // API returns empty object\n    var data = Object.assign({}, keys);\n    if (auth) Object.assign(data, {\n      auth\n    });\n    return this.http.authedRequest(Method.Post, \"/keys/device_signing/upload\", undefined, data, {\n      prefix: ClientPrefix.Unstable\n    });\n  }\n\n  /**\n   * Register with an identity server using the OpenID token from the user's\n   * Homeserver, which can be retrieved via\n   * {@link MatrixClient#getOpenIdToken}.\n   *\n   * Note that the `/account/register` endpoint (as well as IS authentication in\n   * general) was added as part of the v2 API version.\n   *\n   * @returns Promise which resolves: with object containing an Identity\n   * Server access token.\n   * @returns Rejects: with an error response.\n   */\n  registerWithIdentityServer(hsOpenIdToken) {\n    if (!this.idBaseUrl) {\n      throw new Error(\"No identity server base URL set\");\n    }\n    var uri = this.http.getUrl(\"/account/register\", undefined, IdentityPrefix.V2, this.idBaseUrl);\n    return this.http.requestOtherUrl(Method.Post, uri, hsOpenIdToken);\n  }\n\n  /**\n   * Requests an email verification token directly from an identity server.\n   *\n   * This API is used as part of binding an email for discovery on an identity\n   * server. The validation data that results should be passed to the\n   * `bindThreePid` method to complete the binding process.\n   *\n   * @param email - The email address to request a token for\n   * @param clientSecret - A secret binary string generated by the client.\n   *                 It is recommended this be around 16 ASCII characters.\n   * @param sendAttempt - If an identity server sees a duplicate request\n   *                 with the same sendAttempt, it will not send another email.\n   *                 To request another email to be sent, use a larger value for\n   *                 the sendAttempt param as was used in the previous request.\n   * @param nextLink - Optional If specified, the client will be redirected\n   *                 to this link after validation.\n   * @param identityAccessToken - The `access_token` field of the identity\n   * server `/account/register` response (see {@link registerWithIdentityServer}).\n   *\n   * @returns Promise which resolves: TODO\n   * @returns Rejects: with an error response.\n   * @throws Error if no identity server is set\n   */\n  requestEmailToken(email, clientSecret, sendAttempt, nextLink, identityAccessToken) {\n    var params = {\n      client_secret: clientSecret,\n      email: email,\n      send_attempt: sendAttempt === null || sendAttempt === void 0 ? void 0 : sendAttempt.toString()\n    };\n    if (nextLink) {\n      params.next_link = nextLink;\n    }\n    return this.http.idServerRequest(Method.Post, \"/validate/email/requestToken\", params, IdentityPrefix.V2, identityAccessToken);\n  }\n\n  /**\n   * Requests a MSISDN verification token directly from an identity server.\n   *\n   * This API is used as part of binding a MSISDN for discovery on an identity\n   * server. The validation data that results should be passed to the\n   * `bindThreePid` method to complete the binding process.\n   *\n   * @param phoneCountry - The ISO 3166-1 alpha-2 code for the country in\n   *                 which phoneNumber should be parsed relative to.\n   * @param phoneNumber - The phone number, in national or international\n   *                 format\n   * @param clientSecret - A secret binary string generated by the client.\n   *                 It is recommended this be around 16 ASCII characters.\n   * @param sendAttempt - If an identity server sees a duplicate request\n   *                 with the same sendAttempt, it will not send another SMS.\n   *                 To request another SMS to be sent, use a larger value for\n   *                 the sendAttempt param as was used in the previous request.\n   * @param nextLink - Optional If specified, the client will be redirected\n   *                 to this link after validation.\n   * @param identityAccessToken - The `access_token` field of the Identity\n   * Server `/account/register` response (see {@link registerWithIdentityServer}).\n   *\n   * @returns Promise which resolves to an object with a sid string\n   * @returns Rejects: with an error response.\n   * @throws Error if no identity server is set\n   */\n  requestMsisdnToken(phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink, identityAccessToken) {\n    var params = {\n      client_secret: clientSecret,\n      country: phoneCountry,\n      phone_number: phoneNumber,\n      send_attempt: sendAttempt === null || sendAttempt === void 0 ? void 0 : sendAttempt.toString()\n    };\n    if (nextLink) {\n      params.next_link = nextLink;\n    }\n    return this.http.idServerRequest(Method.Post, \"/validate/msisdn/requestToken\", params, IdentityPrefix.V2, identityAccessToken);\n  }\n\n  /**\n   * Submits a MSISDN token to the identity server\n   *\n   * This is used when submitting the code sent by SMS to a phone number.\n   * The identity server has an equivalent API for email but the js-sdk does\n   * not expose this, since email is normally validated by the user clicking\n   * a link rather than entering a code.\n   *\n   * @param sid - The sid given in the response to requestToken\n   * @param clientSecret - A secret binary string generated by the client.\n   *                 This must be the same value submitted in the requestToken call.\n   * @param msisdnToken - The MSISDN token, as entered by the user.\n   * @param identityAccessToken - The `access_token` field of the Identity\n   * Server `/account/register` response (see {@link registerWithIdentityServer}).\n   * Some legacy identity servers had no authentication here.\n   *\n   * @returns Promise which resolves: Object, containing success boolean.\n   * @returns Rejects: with an error response.\n   * @throws Error if No identity server is set\n   */\n  submitMsisdnToken(sid, clientSecret, msisdnToken, identityAccessToken) {\n    var params = {\n      sid: sid,\n      client_secret: clientSecret,\n      token: msisdnToken\n    };\n    return this.http.idServerRequest(Method.Post, \"/validate/msisdn/submitToken\", params, IdentityPrefix.V2, identityAccessToken !== null && identityAccessToken !== void 0 ? identityAccessToken : undefined);\n  }\n\n  /**\n   * Submits a MSISDN token to an arbitrary URL.\n   *\n   * This is used when submitting the code sent by SMS to a phone number in the\n   * newer 3PID flow where the homeserver validates 3PID ownership (as part of\n   * `requestAdd3pidMsisdnToken`). The homeserver response may include a\n   * `submit_url` to specify where the token should be sent, and this helper can\n   * be used to pass the token to this URL.\n   *\n   * @param url - The URL to submit the token to\n   * @param sid - The sid given in the response to requestToken\n   * @param clientSecret - A secret binary string generated by the client.\n   *                 This must be the same value submitted in the requestToken call.\n   * @param msisdnToken - The MSISDN token, as entered by the user.\n   *\n   * @returns Promise which resolves: Object, containing success boolean.\n   * @returns Rejects: with an error response.\n   */\n  submitMsisdnTokenOtherUrl(url, sid, clientSecret, msisdnToken) {\n    var params = {\n      sid: sid,\n      client_secret: clientSecret,\n      token: msisdnToken\n    };\n    return this.http.requestOtherUrl(Method.Post, url, params);\n  }\n\n  /**\n   * Gets the V2 hashing information from the identity server. Primarily useful for\n   * lookups.\n   * @param identityAccessToken - The access token for the identity server.\n   * @returns The hashing information for the identity server.\n   */\n  getIdentityHashDetails(identityAccessToken) {\n    return this.http.idServerRequest(Method.Get, \"/hash_details\", undefined, IdentityPrefix.V2, identityAccessToken);\n  }\n\n  /**\n   * Performs a hashed lookup of addresses against the identity server. This is\n   * only supported on identity servers which have at least the version 2 API.\n   * @param addressPairs - An array of 2 element arrays.\n   * The first element of each pair is the address, the second is the 3PID medium.\n   * Eg: `[\"email@example.org\", \"email\"]`\n   * @param identityAccessToken - The access token for the identity server.\n   * @returns A collection of address mappings to\n   * found MXIDs. Results where no user could be found will not be listed.\n   */\n  identityHashedLookup(addressPairs, identityAccessToken) {\n    var _this73 = this;\n    return _asyncToGenerator(function* () {\n      var params = {\n        // addresses: [\"email@example.org\", \"10005550000\"],\n        // algorithm: \"sha256\",\n        // pepper: \"abc123\"\n      };\n\n      // Get hash information first before trying to do a lookup\n      var hashes = yield _this73.getIdentityHashDetails(identityAccessToken);\n      if (!hashes || !hashes[\"lookup_pepper\"] || !hashes[\"algorithms\"]) {\n        throw new Error(\"Unsupported identity server: bad response\");\n      }\n      params[\"pepper\"] = hashes[\"lookup_pepper\"];\n      var localMapping = {\n        // hashed identifier => plain text address\n        // For use in this function's return format\n      };\n\n      // When picking an algorithm, we pick the hashed over no hashes\n      if (hashes[\"algorithms\"].includes(\"sha256\")) {\n        params[\"addresses\"] = yield Promise.all(addressPairs.map(/*#__PURE__*/function () {\n          var _ref10 = _asyncToGenerator(function* (p) {\n            var addr = p[0].toLowerCase(); // lowercase to get consistent hashes\n            var med = p[1].toLowerCase();\n            var hashBuffer = yield sha256(\"\".concat(addr, \" \").concat(med, \" \").concat(params[\"pepper\"]));\n            var hashed = encodeUnpaddedBase64Url(hashBuffer);\n\n            // Map the hash to a known (case-sensitive) address. We use the case\n            // sensitive version because the caller might be expecting that.\n            localMapping[hashed] = p[0];\n            return hashed;\n          });\n          return function (_x4) {\n            return _ref10.apply(this, arguments);\n          };\n        }()));\n        params[\"algorithm\"] = \"sha256\";\n      } else if (hashes[\"algorithms\"].includes(\"none\")) {\n        params[\"addresses\"] = addressPairs.map(p => {\n          var addr = p[0].toLowerCase(); // lowercase to get consistent hashes\n          var med = p[1].toLowerCase();\n          var unhashed = \"\".concat(addr, \" \").concat(med);\n          // Map the unhashed values to a known (case-sensitive) address. We use\n          // the case-sensitive version because the caller might be expecting that.\n          localMapping[unhashed] = p[0];\n          return unhashed;\n        });\n        params[\"algorithm\"] = \"none\";\n      } else {\n        throw new Error(\"Unsupported identity server: unknown hash algorithm\");\n      }\n      var response = yield _this73.http.idServerRequest(Method.Post, \"/lookup\", params, IdentityPrefix.V2, identityAccessToken);\n      if (!(response !== null && response !== void 0 && response[\"mappings\"])) return []; // no results\n\n      var foundAddresses = [];\n      for (var hashed of Object.keys(response[\"mappings\"])) {\n        var mxid = response[\"mappings\"][hashed];\n        var plainAddress = localMapping[hashed];\n        if (!plainAddress) {\n          throw new Error(\"Identity server returned more results than expected\");\n        }\n        foundAddresses.push({\n          address: plainAddress,\n          mxid\n        });\n      }\n      return foundAddresses;\n    })();\n  }\n\n  /**\n   * Looks up the public Matrix ID mapping for a given 3rd party\n   * identifier from the identity server\n   *\n   * @param medium - The medium of the threepid, eg. 'email'\n   * @param address - The textual address of the threepid\n   * @param identityAccessToken - The `access_token` field of the Identity\n   * Server `/account/register` response (see {@link registerWithIdentityServer}).\n   *\n   * @returns Promise which resolves: A threepid mapping\n   *                                 object or the empty object if no mapping\n   *                                 exists\n   * @returns Rejects: with an error response.\n   */\n  lookupThreePid(medium, address, identityAccessToken) {\n    var _this74 = this;\n    return _asyncToGenerator(function* () {\n      // Note: we're using the V2 API by calling this function, but our\n      // function contract requires a V1 response. We therefore have to\n      // convert it manually.\n      var response = yield _this74.identityHashedLookup([[address, medium]], identityAccessToken);\n      var result = response.find(p => p.address === address);\n      if (!result) {\n        return {};\n      }\n      var mapping = {\n        address,\n        medium,\n        mxid: result.mxid\n\n        // We can't reasonably fill these parameters:\n        // not_before\n        // not_after\n        // ts\n        // signatures\n      };\n      return mapping;\n    })();\n  }\n\n  /**\n   * Looks up the public Matrix ID mappings for multiple 3PIDs.\n   *\n   * @param query - Array of arrays containing\n   * [medium, address]\n   * @param identityAccessToken - The `access_token` field of the Identity\n   * Server `/account/register` response (see {@link registerWithIdentityServer}).\n   *\n   * @returns Promise which resolves: Lookup results from IS.\n   * @returns Rejects: with an error response.\n   */\n  bulkLookupThreePids(query, identityAccessToken) {\n    var _this75 = this;\n    return _asyncToGenerator(function* () {\n      // Note: we're using the V2 API by calling this function, but our\n      // function contract requires a V1 response. We therefore have to\n      // convert it manually.\n      var response = yield _this75.identityHashedLookup(\n      // We have to reverse the query order to get [address, medium] pairs\n      query.map(p => [p[1], p[0]]), identityAccessToken);\n      var v1results = [];\n      var _loop2 = function* _loop2(mapping) {\n        var originalQuery = query.find(p => p[1] === mapping.address);\n        if (!originalQuery) {\n          throw new Error(\"Identity sever returned unexpected results\");\n        }\n        v1results.push([originalQuery[0],\n        // medium\n        mapping.address, mapping.mxid]);\n      };\n      for (var mapping of response) {\n        yield* _loop2(mapping);\n      }\n      return {\n        threepids: v1results\n      };\n    })();\n  }\n\n  /**\n   * Get account info from the identity server. This is useful as a neutral check\n   * to verify that other APIs are likely to approve access by testing that the\n   * token is valid, terms have been agreed, etc.\n   *\n   * @param identityAccessToken - The `access_token` field of the Identity\n   * Server `/account/register` response (see {@link registerWithIdentityServer}).\n   *\n   * @returns Promise which resolves: an object with account info.\n   * @returns Rejects: with an error response.\n   */\n  getIdentityAccount(identityAccessToken) {\n    return this.http.idServerRequest(Method.Get, \"/account\", undefined, IdentityPrefix.V2, identityAccessToken);\n  }\n\n  /**\n   * Send an event to a specific list of devices.\n   * This is a low-level API that simply wraps the HTTP API\n   * call to send to-device messages. We recommend using\n   * queueToDevice() which is a higher level API.\n   *\n   * @param eventType -  type of event to send\n   *    content to send. Map from user_id to device_id to content object.\n   * @param txnId -     transaction id. One will be made up if not\n   *    supplied.\n   * @returns Promise which resolves: to an empty object `{}`\n   */\n  sendToDevice(eventType, contentMap, txnId) {\n    var path = utils.encodeUri(\"/sendToDevice/$eventType/$txnId\", {\n      $eventType: eventType,\n      $txnId: txnId ? txnId : this.makeTxnId()\n    });\n    var body = {\n      messages: utils.recursiveMapToObject(contentMap)\n    };\n    var targets = new Map();\n    for (var [userId, deviceMessages] of contentMap) {\n      targets.set(userId, Array.from(deviceMessages.keys()));\n    }\n    this.logger.debug(\"PUT \".concat(path), targets);\n    return this.http.authedRequest(Method.Put, path, undefined, body);\n  }\n\n  /**\n   * This will encrypt the payload for all devices in the list and will queue it.\n   * The type of the sent to-device message will be `m.room.encrypted`.\n   * @param eventType - The type of event to send\n   * @param devices - The list of devices to send the event to.\n   * @param payload - The payload to send. This will be encrypted.\n   * @returns Promise which resolves once queued there is no error feedback when sending fails.\n   */\n  encryptAndSendToDevice(eventType, devices, payload) {\n    var _this76 = this;\n    return _asyncToGenerator(function* () {\n      if (!_this76.cryptoBackend) {\n        throw new Error(\"Cannot encrypt to device event, your client does not support encryption.\");\n      }\n      var batch = yield _this76.cryptoBackend.encryptToDeviceMessages(eventType, devices, payload);\n\n      // TODO The batch mechanism removes all possibility to get error feedbacks..\n      // We might want instead to do the API call directly and pass the errors back.\n      yield _this76.queueToDevice(batch);\n    })();\n  }\n\n  /**\n   * Sends events directly to specific devices using Matrix's to-device\n   * messaging system. The batch will be split up into appropriately sized\n   * batches for sending and stored in the store so they can be retried\n   * later if they fail to send. Retries will happen automatically.\n   * @param batch - The to-device messages to send\n   */\n  queueToDevice(batch) {\n    return this.toDeviceMessageQueue.queueBatch(batch);\n  }\n\n  /**\n   * Get the third party protocols that can be reached using\n   * this HS\n   * @returns Promise which resolves to the result object\n   */\n  getThirdpartyProtocols() {\n    return this.http.authedRequest(Method.Get, \"/thirdparty/protocols\").then(response => {\n      // sanity check\n      if (!response || typeof response !== \"object\") {\n        throw new Error(\"/thirdparty/protocols did not return an object: \".concat(response));\n      }\n      return response;\n    });\n  }\n\n  /**\n   * Get information on how a specific place on a third party protocol\n   * may be reached.\n   * @param protocol - The protocol given in getThirdpartyProtocols()\n   * @param params - Protocol-specific parameters, as given in the\n   *                        response to getThirdpartyProtocols()\n   * @returns Promise which resolves to the result object\n   */\n  getThirdpartyLocation(protocol, params) {\n    var path = utils.encodeUri(\"/thirdparty/location/$protocol\", {\n      $protocol: protocol\n    });\n    return this.http.authedRequest(Method.Get, path, params);\n  }\n\n  /**\n   * Get information on how a specific user on a third party protocol\n   * may be reached.\n   * @param protocol - The protocol given in getThirdpartyProtocols()\n   * @param params - Protocol-specific parameters, as given in the\n   *                        response to getThirdpartyProtocols()\n   * @returns Promise which resolves to the result object\n   */\n  getThirdpartyUser(protocol, params) {\n    var path = utils.encodeUri(\"/thirdparty/user/$protocol\", {\n      $protocol: protocol\n    });\n    return this.http.authedRequest(Method.Get, path, params);\n  }\n  getTerms(serviceType, baseUrl) {\n    var url = this.termsUrlForService(serviceType, baseUrl);\n    return this.http.requestOtherUrl(Method.Get, url);\n  }\n  agreeToTerms(serviceType, baseUrl, accessToken, termsUrls) {\n    var url = this.termsUrlForService(serviceType, baseUrl);\n    var headers = {\n      Authorization: \"Bearer \" + accessToken\n    };\n    return this.http.requestOtherUrl(Method.Post, url, {\n      user_accepts: termsUrls\n    }, {\n      headers\n    });\n  }\n\n  /**\n   * Reports an event as inappropriate to the server, which may then notify the appropriate people.\n   * @param roomId - The room in which the event being reported is located.\n   * @param eventId - The event to report.\n   * @param score - The score to rate this content as where -100 is most offensive and 0 is inoffensive.\n   * @param reason - The reason the content is being reported. May be blank.\n   * @returns Promise which resolves to an empty object if successful\n   */\n  reportEvent(roomId, eventId, score, reason) {\n    var path = utils.encodeUri(\"/rooms/$roomId/report/$eventId\", {\n      $roomId: roomId,\n      $eventId: eventId\n    });\n    return this.http.authedRequest(Method.Post, path, undefined, {\n      score,\n      reason\n    });\n  }\n\n  /**\n   * Reports a room as inappropriate to the server, which may then notify the appropriate people.\n   *\n   * This API was introduced in Matrix v1.13.\n   *\n   * @param roomId - The room being reported.\n   * @param reason - The reason the room is being reported. May be blank.\n   * @returns Promise which resolves to an empty object if successful\n   */\n  reportRoom(roomId, reason) {\n    var path = utils.encodeUri(\"/rooms/$roomId/report\", {\n      $roomId: roomId\n    });\n    return this.http.authedRequest(Method.Post, path, undefined, {\n      reason\n    });\n  }\n\n  /**\n   * Fetches or paginates a room hierarchy asmatrix-js-sdk/spec/unit/matrix-client.spec.ts defined by MSC2946.\n   * Falls back gracefully to sourcing its data from `getSpaceSummary` if this API is not yet supported by the server.\n   * @param roomId - The ID of the space-room to use as the root of the summary.\n   * @param limit - The maximum number of rooms to return per page.\n   * @param maxDepth - The maximum depth in the tree from the root room to return.\n   * @param suggestedOnly - Whether to only return rooms with suggested=true.\n   * @param fromToken - The opaque token to paginate a previous request.\n   * @returns the response, with next_batch & rooms fields.\n   */\n  getRoomHierarchy(roomId, limit, maxDepth) {\n    var suggestedOnly = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n    var fromToken = arguments.length > 4 ? arguments[4] : undefined;\n    var path = utils.encodeUri(\"/rooms/$roomId/hierarchy\", {\n      $roomId: roomId\n    });\n    var queryParams = {\n      suggested_only: String(suggestedOnly),\n      max_depth: maxDepth === null || maxDepth === void 0 ? void 0 : maxDepth.toString(),\n      from: fromToken,\n      limit: limit === null || limit === void 0 ? void 0 : limit.toString()\n    };\n    return this.http.authedRequest(Method.Get, path, queryParams, undefined, {\n      prefix: ClientPrefix.V1\n    }).catch(e => {\n      if (e.errcode === \"M_UNRECOGNIZED\") {\n        // fall back to the prefixed hierarchy API.\n        return this.http.authedRequest(Method.Get, path, queryParams, undefined, {\n          prefix: \"/_matrix/client/unstable/org.matrix.msc2946\"\n        });\n      }\n      throw e;\n    });\n  }\n\n  /**\n   * Creates a new file tree space with the given name. The client will pick\n   * defaults for how it expects to be able to support the remaining API offered\n   * by the returned class.\n   *\n   * Note that this is UNSTABLE and may have breaking changes without notice.\n   * @param name - The name of the tree space.\n   * @returns Promise which resolves to the created space.\n   */\n  unstableCreateFileTree(name) {\n    var _this77 = this;\n    return _asyncToGenerator(function* () {\n      var {\n        room_id: roomId\n      } = yield _this77.createRoom({\n        name: name,\n        preset: Preset.PrivateChat,\n        power_level_content_override: _objectSpread(_objectSpread({}, DEFAULT_TREE_POWER_LEVELS_TEMPLATE), {}, {\n          users: {\n            [_this77.getUserId()]: 100\n          }\n        }),\n        creation_content: {\n          [RoomCreateTypeField]: RoomType.Space\n        },\n        initial_state: [{\n          type: UNSTABLE_MSC3088_PURPOSE.name,\n          state_key: UNSTABLE_MSC3089_TREE_SUBTYPE.name,\n          content: {\n            [UNSTABLE_MSC3088_ENABLED.name]: true\n          }\n        }, {\n          type: EventType.RoomEncryption,\n          state_key: \"\",\n          content: {\n            algorithm: \"m.megolm.v1.aes-sha2\"\n          }\n        }]\n      });\n      return new MSC3089TreeSpace(_this77, roomId);\n    })();\n  }\n\n  /**\n   * Gets a reference to a tree space, if the room ID given is a tree space. If the room\n   * does not appear to be a tree space then null is returned.\n   *\n   * Note that this is UNSTABLE and may have breaking changes without notice.\n   * @param roomId - The room ID to get a tree space reference for.\n   * @returns The tree space, or null if not a tree space.\n   */\n  unstableGetFileTreeSpace(roomId) {\n    var _purposeEvent$getCont, _createEvent$getConte;\n    var room = this.getRoom(roomId);\n    if ((room === null || room === void 0 ? void 0 : room.getMyMembership()) !== KnownMembership.Join) return null;\n    var createEvent = room.currentState.getStateEvents(EventType.RoomCreate, \"\");\n    var purposeEvent = room.currentState.getStateEvents(UNSTABLE_MSC3088_PURPOSE.name, UNSTABLE_MSC3089_TREE_SUBTYPE.name);\n    if (!createEvent) throw new Error(\"Expected single room create event\");\n    if (!(purposeEvent !== null && purposeEvent !== void 0 && (_purposeEvent$getCont = purposeEvent.getContent()) !== null && _purposeEvent$getCont !== void 0 && _purposeEvent$getCont[UNSTABLE_MSC3088_ENABLED.name])) return null;\n    if (((_createEvent$getConte = createEvent.getContent()) === null || _createEvent$getConte === void 0 ? void 0 : _createEvent$getConte[RoomCreateTypeField]) !== RoomType.Space) return null;\n    return new MSC3089TreeSpace(this, roomId);\n  }\n\n  /**\n   * Perform a single MSC3575 sliding sync request.\n   * @param req - The request to make.\n   * @param proxyBaseUrl - The base URL for the sliding sync proxy.\n   * @param abortSignal - Optional signal to abort request mid-flight.\n   * @returns The sliding sync response, or a standard error.\n   * @throws on non 2xx status codes with an object with a field \"httpStatus\":number.\n   */\n  slidingSync(req, proxyBaseUrl, abortSignal) {\n    var qps = {};\n    if (req.pos) {\n      qps.pos = req.pos;\n      delete req.pos;\n    }\n    if (req.timeout) {\n      qps.timeout = req.timeout;\n      delete req.timeout;\n    }\n    var clientTimeout = req.clientTimeout;\n    delete req.clientTimeout;\n    return this.http.authedRequest(Method.Post, \"/sync\", qps, req, {\n      prefix: \"/_matrix/client/unstable/org.matrix.simplified_msc3575\",\n      baseUrl: proxyBaseUrl,\n      localTimeoutMs: clientTimeout,\n      abortSignal\n    });\n  }\n\n  /**\n   * A helper to determine thread support\n   * @returns a boolean to determine if threads are enabled\n   */\n  supportsThreads() {\n    var _this$clientOpts4;\n    return ((_this$clientOpts4 = this.clientOpts) === null || _this$clientOpts4 === void 0 ? void 0 : _this$clientOpts4.threadSupport) || false;\n  }\n\n  /**\n   * A helper to determine intentional mentions support\n   * @returns a boolean to determine if intentional mentions are enabled on the server\n   * @experimental\n   */\n  supportsIntentionalMentions() {\n    return this.canSupport.get(Feature.IntentionalMentions) !== ServerSupport.Unsupported;\n  }\n\n  /**\n   * Fetches the summary of a room as defined by an initial version of MSC3266 and implemented in Synapse\n   * Proposed at https://github.com/matrix-org/matrix-doc/pull/3266\n   * @param roomIdOrAlias - The ID or alias of the room to get the summary of.\n   * @param via - The list of servers which know about the room if only an ID was provided.\n   */\n  getRoomSummary(roomIdOrAlias, via) {\n    var _this78 = this;\n    return _asyncToGenerator(function* () {\n      var paramOpts = {\n        prefix: \"/_matrix/client/unstable/im.nheko.summary\"\n      };\n      try {\n        var path = utils.encodeUri(\"/summary/$roomid\", {\n          $roomid: roomIdOrAlias\n        });\n        return yield _this78.http.authedRequest(Method.Get, path, {\n          via\n        }, undefined, paramOpts);\n      } catch (e) {\n        if (e instanceof MatrixError && e.errcode === \"M_UNRECOGNIZED\") {\n          var _path = utils.encodeUri(\"/rooms/$roomid/summary\", {\n            $roomid: roomIdOrAlias\n          });\n          return yield _this78.http.authedRequest(Method.Get, _path, {\n            via\n          }, undefined, paramOpts);\n        } else {\n          throw e;\n        }\n      }\n    })();\n  }\n\n  /**\n   * Processes a list of threaded events and adds them to their respective timelines\n   * @param room - the room the adds the threaded events\n   * @param threadedEvents - an array of the threaded events\n   * @param toStartOfTimeline - the direction in which we want to add the events\n   */\n  processThreadEvents(room, threadedEvents, toStartOfTimeline) {\n    room.processThreadedEvents(threadedEvents, toStartOfTimeline);\n  }\n\n  /**\n   * Processes a list of thread roots and creates a thread model\n   * @param room - the room to create the threads in\n   * @param threadedEvents - an array of thread roots\n   * @param toStartOfTimeline - the direction\n   */\n  processThreadRoots(room, threadedEvents, toStartOfTimeline) {\n    if (!this.supportsThreads()) return;\n    room.processThreadRoots(threadedEvents, toStartOfTimeline);\n  }\n  processBeaconEvents(room, events) {\n    this.processAggregatedTimelineEvents(room, events);\n  }\n\n  /**\n   * Calls aggregation functions for event types that are aggregated\n   * Polls and location beacons\n   * @param room - room the events belong to\n   * @param events - timeline events to be processed\n   * @returns\n   */\n  processAggregatedTimelineEvents(room, events) {\n    if (!(events !== null && events !== void 0 && events.length)) return;\n    if (!room) return;\n    room.currentState.processBeaconEvents(events, this);\n    room.processPollEvents(events);\n  }\n\n  /**\n   * Fetches information about the user for the configured access token.\n   */\n  whoami() {\n    var _this79 = this;\n    return _asyncToGenerator(function* () {\n      return _this79.http.authedRequest(Method.Get, \"/account/whoami\");\n    })();\n  }\n\n  /**\n   * Find the event_id closest to the given timestamp in the given direction.\n   * @returns Resolves: A promise of an object containing the event_id and\n   *    origin_server_ts of the closest event to the timestamp in the given direction\n   * @returns Rejects: when the request fails (module:http-api.MatrixError)\n   */\n  timestampToEvent(roomId, timestamp, dir) {\n    var _this80 = this;\n    return _asyncToGenerator(function* () {\n      var path = utils.encodeUri(\"/rooms/$roomId/timestamp_to_event\", {\n        $roomId: roomId\n      });\n      var queryParams = {\n        ts: timestamp.toString(),\n        dir: dir\n      };\n      try {\n        return yield _this80.http.authedRequest(Method.Get, path, queryParams, undefined, {\n          prefix: ClientPrefix.V1\n        });\n      } catch (err) {\n        // Fallback to the prefixed unstable endpoint. Since the stable endpoint is\n        // new, we should also try the unstable endpoint before giving up. We can\n        // remove this fallback request in a year (remove after 2023-11-28).\n        if (err.errcode === \"M_UNRECOGNIZED\" && (\n        // XXX: The 400 status code check should be removed in the future\n        // when Synapse is compliant with MSC3743.\n        err.httpStatus === 400 ||\n        // This the correct standard status code for an unsupported\n        // endpoint according to MSC3743. Not Found and Method Not Allowed\n        // both indicate that this endpoint+verb combination is\n        // not supported.\n        err.httpStatus === 404 || err.httpStatus === 405)) {\n          return yield _this80.http.authedRequest(Method.Get, path, queryParams, undefined, {\n            prefix: \"/_matrix/client/unstable/org.matrix.msc3030\"\n          });\n        }\n        throw err;\n      }\n    })();\n  }\n\n  /**\n   * Discover and validate the auth metadata for the OAuth 2.0 API.\n   *\n   * Fetches /auth_metadata falling back to legacy implementation using /auth_issuer followed by\n   * https://oidc-issuer.example.com/.well-known/openid-configuration and other files linked therein.\n   * When successful, validated metadata is returned.\n   *\n   * @returns validated authentication metadata and optionally signing keys\n   * @throws when delegated auth config is invalid or unreachable\n   */\n  getAuthMetadata() {\n    var _this81 = this;\n    return _asyncToGenerator(function* () {\n      var authMetadata;\n      try {\n        var useStable = yield _this81.isVersionSupported(\"v1.15\");\n        authMetadata = yield _this81.http.request(Method.Get, \"/auth_metadata\", undefined, undefined, {\n          prefix: useStable ? ClientPrefix.V1 : ClientPrefix.Unstable + \"/org.matrix.msc2965\"\n        });\n      } catch (e) {\n        if (e instanceof MatrixError && e.errcode === \"M_UNRECOGNIZED\") {\n          // Fall back to older variant of MSC2965\n          var {\n            issuer\n          } = yield _this81.http.request(Method.Get, \"/auth_issuer\", undefined, undefined, {\n            prefix: ClientPrefix.Unstable + \"/org.matrix.msc2965\"\n          });\n          return discoverAndValidateOIDCIssuerWellKnown(issuer);\n        }\n        throw e;\n      }\n      return validateAuthMetadataAndKeys(authMetadata);\n    })();\n  }\n}\n_defineProperty(MatrixClient, \"RESTORE_BACKUP_ERROR_BAD_KEY\", \"RESTORE_BACKUP_ERROR_BAD_KEY\");\nfunction getUnstableDelayQueryOpts(delayOpts) {\n  return Object.fromEntries(Object.entries(delayOpts).map(_ref11 => {\n    var [k, v] = _ref11;\n    return [\"\".concat(UNSTABLE_MSC4140_DELAYED_EVENTS, \".\").concat(k), v];\n  }));\n}\n\n/**\n * recalculates an accurate notifications count on event decryption.\n * Servers do not have enough knowledge about encrypted events to calculate an\n * accurate notification_count\n */\nexport function fixNotificationCountOnDecryption(cli, event) {\n  var _actions$tweaks;\n  var ourUserId = cli.getUserId();\n  var eventId = event.getId();\n  var room = cli.getRoom(event.getRoomId());\n  if (!room || !ourUserId || !eventId) return;\n\n  // Due to threads, we can get relation events (eg. edits & reactions) that never get\n  // added to a timeline and so cannot be found in their own room (their edit / reaction\n  // still applies to the event it needs to, so it doesn't matter too much). However, if\n  // we try to process notification about this event, we'll get very confused because we\n  // won't be able to find the event in the room, so will assume it must be unread, even\n  // if it's actually read. We therefore skip anything that isn't in the room. This isn't\n  // *great*, so if we can fix the homeless events (eg. with MSC4023) then we should probably\n  // remove this workaround.\n  if (!room.findEventById(eventId)) {\n    logger.info(\"Decrypted event \".concat(event.getId(), \" is not in room \").concat(room.roomId, \": ignoring\"));\n    return;\n  }\n  var isThreadEvent = !!event.threadRootId && !event.isThreadRoot;\n  var hasReadEvent;\n  if (isThreadEvent) {\n    var thread = room.getThread(event.threadRootId);\n    hasReadEvent = thread ? thread.hasUserReadEvent(ourUserId, eventId) :\n    // If the thread object does not exist in the room yet, we don't\n    // want to calculate notification for this event yet. We have not\n    // restored the read receipts yet and can't accurately calculate\n    // notifications at this stage.\n    //\n    // This issue can likely go away when MSC3874 is implemented\n    true;\n  } else {\n    hasReadEvent = room.hasUserReadEvent(ourUserId, eventId);\n  }\n  if (hasReadEvent) {\n    // If the event has been read, ignore it.\n    return;\n  }\n  var actions = cli.getPushActionsForEvent(event, true);\n\n  // Ensure the unread counts are kept up to date if the event is encrypted\n  // We also want to make sure that the notification count goes up if we already\n  // have encrypted events to avoid other code from resetting 'highlight' to zero.\n  var newHighlight = !!(actions !== null && actions !== void 0 && (_actions$tweaks = actions.tweaks) !== null && _actions$tweaks !== void 0 && _actions$tweaks.highlight);\n  if (newHighlight) {\n    // TODO: Handle mentions received while the client is offline\n    // See also https://github.com/vector-im/element-web/issues/9069\n    var newCount = room.getUnreadCountForEventContext(NotificationCountType.Highlight, event) + 1;\n    if (isThreadEvent) {\n      room.setThreadUnreadNotificationCount(event.threadRootId, NotificationCountType.Highlight, newCount);\n    } else {\n      room.setUnreadNotificationCount(NotificationCountType.Highlight, newCount);\n    }\n  }\n\n  // `notify` is used in practice for incrementing the total count\n  var newNotify = !!(actions !== null && actions !== void 0 && actions.notify);\n\n  // The room total count is NEVER incremented by the server for encrypted rooms. We basically ignore\n  // the server here as it's always going to tell us to increment for encrypted events.\n  if (newNotify) {\n    // Total count is used to typically increment a room notification counter, but not loudly highlight it.\n    var _newCount = room.getUnreadCountForEventContext(NotificationCountType.Total, event) + 1;\n    if (isThreadEvent) {\n      room.setThreadUnreadNotificationCount(event.threadRootId, NotificationCountType.Total, _newCount);\n    } else {\n      room.setUnreadNotificationCount(NotificationCountType.Total, _newCount);\n    }\n  }\n}\n\n/**\n * Given an event, figure out the thread ID we should use for it in a receipt.\n *\n * This will either be \"main\", or event.threadRootId. For the thread root, or\n * e.g. reactions to the thread root, this will be main. For events inside the\n * thread, or e.g. reactions to them, this will be event.threadRootId.\n *\n * (Exported for test.)\n */\nexport function threadIdForReceipt(event) {\n  return inMainTimelineForReceipt(event) ? MAIN_ROOM_TIMELINE : event.threadRootId;\n}\n\n/**\n * a) True for non-threaded messages, thread roots and non-thread relations to thread roots.\n * b) False for messages with thread relations to the thread root.\n * c) False for messages with any kind of relation to a message from case b.\n *\n * Note: true for redactions of messages that are in threads. Redacted messages\n * are not really in threads (because their relations are gone), so if they look\n * like they are in threads, that is a sign of a bug elsewhere. (At time of\n * writing, this bug definitely exists - messages are not moved to another\n * thread when they are redacted.)\n *\n * @returns true if this event is considered to be in the main timeline as far\n *               as receipts are concerned.\n */\nexport function inMainTimelineForReceipt(event) {\n  if (!event.threadRootId) {\n    // Not in a thread: then it is in the main timeline\n    return true;\n  }\n  if (event.isThreadRoot) {\n    // Thread roots are in the main timeline. Note: the spec is ambiguous (or\n    // wrong) on this - see\n    // https://github.com/matrix-org/matrix-spec-proposals/pull/4037\n    return true;\n  }\n  if (!event.isRelation()) {\n    // If it's not related to anything, it can't be related via a chain of\n    // relations to a thread root.\n    //\n    // Note: this is a bug, because how does it have a threadRootId if it is\n    // neither a thread root, nor related to one?\n    logger.warn(\"Event is not a relation or a thread root, but still has a threadRootId! id=\".concat(event.getId()));\n    return true;\n  }\n  if (event.isRelation(THREAD_RELATION_TYPE.name)) {\n    // It's a message in a thread - definitely not in the main timeline.\n    return false;\n  }\n  var isRelatedToRoot = event.relationEventId === event.threadRootId;\n\n  // If it's related to the thread root (and we already know it's not a thread\n  // relation) then it's in the main timeline. If it's related to something\n  // else, then it's in the thread (because it has a thread ID).\n  return isRelatedToRoot;\n}\n//# sourceMappingURL=client.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction 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; }\nfunction _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; }\n/*\nCopyright 2021 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { PendingEventOrdering } from \"../client.js\";\nimport { TypedReEmitter } from \"../ReEmitter.js\";\nimport { RelationType } from \"../@types/event.js\";\nimport { MatrixEvent, MatrixEventEvent } from \"./event.js\";\nimport { Direction, EventTimeline } from \"./event-timeline.js\";\nimport { EventTimelineSet } from \"./event-timeline-set.js\";\nimport { RoomEvent } from \"./room.js\";\nimport { ServerControlledNamespacedValue } from \"../NamespacedValue.js\";\nimport { logger } from \"../logger.js\";\nimport { ReadReceipt } from \"./read-receipt.js\";\nimport { ReceiptType } from \"../@types/read_receipts.js\";\nimport { Feature, ServerSupport } from \"../feature.js\";\nexport var ThreadEvent = /*#__PURE__*/function (ThreadEvent) {\n  ThreadEvent[\"New\"] = \"Thread.new\";\n  ThreadEvent[\"Update\"] = \"Thread.update\";\n  ThreadEvent[\"NewReply\"] = \"Thread.newReply\";\n  ThreadEvent[\"ViewThread\"] = \"Thread.viewThread\";\n  ThreadEvent[\"Delete\"] = \"Thread.delete\";\n  return ThreadEvent;\n}({});\nexport var FeatureSupport = /*#__PURE__*/function (FeatureSupport) {\n  FeatureSupport[FeatureSupport[\"None\"] = 0] = \"None\";\n  FeatureSupport[FeatureSupport[\"Experimental\"] = 1] = \"Experimental\";\n  FeatureSupport[FeatureSupport[\"Stable\"] = 2] = \"Stable\";\n  return FeatureSupport;\n}({});\nexport function determineFeatureSupport(stable, unstable) {\n  if (stable) {\n    return FeatureSupport.Stable;\n  } else if (unstable) {\n    return FeatureSupport.Experimental;\n  } else {\n    return FeatureSupport.None;\n  }\n}\nexport class Thread extends ReadReceipt {\n  constructor(id, rootEvent, opts) {\n    var _this, _opts$pendingEventOrd;\n    // each Event in the thread adds a reemitter, so we could hit the listener limit.\n    super();\n    _this = this;\n    this.id = id;\n    this.rootEvent = rootEvent;\n    /**\n     * A reference to all the events ID at the bottom of the threads\n     */\n    _defineProperty(this, \"timelineSet\", void 0);\n    _defineProperty(this, \"_currentUserParticipated\", false);\n    _defineProperty(this, \"reEmitter\", void 0);\n    /**\n     * The last event in this thread, if we don't yet have this in the timeline.\n     *\n     * When we run {@link processRootEvent} (which I think happens during the\n     * setting-up of the thread), we set this to the event pointed to by the\n     * server in `latest_event` [1] that came through with the thread root.\n     *\n     * [1]: https://spec.matrix.org/v1.8/client-server-api/#server-side-aggregation-of-mthread-relationships\n     *\n     * Later, when we have populated the timeline, this is set to undefined, so\n     * that methods like {@link replyToEvent} fall through to use lastReply,\n     * which looks in the timeline for the latest event that is a \"thread reply\"\n     * i.e. directly refers to the thread root with an m.thread relation.\n     *\n     * So it looks like this is only really relevant when initialEventsFetched\n     * is false, because as soon as the initial events have been fetched, we\n     * should have a proper chunk of timeline from the pagination fetch.\n     *\n     * If all replies in this thread are redacted, this is set to the root\n     * event. I'm not clear what the meaning of this is, since usually after the\n     * initial events have been fetched, lastEvent should be undefined.\n     * In fact, the whole usage inside onRedaction looks suspect - it may be\n     * that we were thinking lastEvent always refers to the actual last event,\n     * but it only does so before initialEventsFetched becomes true.\n     *\n     * The usage of lastEvent inside {@link onEcho} looks suspicious, since I'd\n     * think we probably mean {@link replyToEvent} there - we are trying not to\n     * echo a duplicate event, and we probably want that behaviour even after\n     * initialEventsFetched has become true.\n     *\n     * -- andyb\n     */\n    _defineProperty(this, \"lastEvent\", void 0);\n    _defineProperty(this, \"replyCount\", 0);\n    _defineProperty(this, \"lastPendingEvent\", void 0);\n    _defineProperty(this, \"pendingReplyCount\", 0);\n    _defineProperty(this, \"room\", void 0);\n    _defineProperty(this, \"client\", void 0);\n    _defineProperty(this, \"pendingEventOrdering\", void 0);\n    _defineProperty(this, \"processRootEventPromise\", void 0);\n    /**\n     * Whether or not we need to fetch the initial set of events for the thread. We can\n     * only do this if the server has support for it, so if it doesn't we just pretend\n     * that we've already fetched them.\n     */\n    _defineProperty(this, \"initialEventsFetched\", !Thread.hasServerSideSupport);\n    _defineProperty(this, \"initalEventFetchProm\", void 0);\n    /**\n     * An array of events to add to the timeline once the thread has been initialised\n     * with server suppport.\n     */\n    _defineProperty(this, \"replayEvents\", []);\n    _defineProperty(this, \"onTimelineReset\", /*#__PURE__*/_asyncToGenerator(function* () {\n      // We hit a gappy sync, ask the server for an update\n      yield _this.processRootEventPromise;\n      _this.processRootEventPromise = undefined;\n    }));\n    _defineProperty(this, \"onBeforeRedaction\", (event, redaction) => {\n      if (event !== null && event !== void 0 && event.isRelation(THREAD_RELATION_TYPE.name) && this.room.eventShouldLiveIn(event).threadId === this.id && event.getId() !== this.id &&\n      // the root event isn't counted in the length so ignore this redaction\n      !redaction.status // only respect it when it succeeds\n      ) {\n        this.replyCount--;\n        this.updatePendingReplyCount();\n        this.emit(ThreadEvent.Update, this);\n      }\n    });\n    _defineProperty(this, \"onRedaction\", /*#__PURE__*/function () {\n      var _ref2 = _asyncToGenerator(function* (event, room, threadRootId) {\n        if (threadRootId !== _this.id) return; // ignore redactions for other timelines\n        if (_this.replyCount <= 0) {\n          for (var threadEvent of _this.timeline) {\n            _this.clearEventMetadata(threadEvent);\n          }\n          _this.lastEvent = _this.rootEvent;\n          _this._currentUserParticipated = false;\n          _this.emit(ThreadEvent.Delete, _this);\n        } else {\n          var _this$lastEvent;\n          if (((_this$lastEvent = _this.lastEvent) === null || _this$lastEvent === void 0 ? void 0 : _this$lastEvent.getId()) === event.getAssociatedId()) {\n            // XXX: If our last event got redacted we query the server for the last event once again\n            yield _this.processRootEventPromise;\n            _this.processRootEventPromise = undefined;\n          }\n          yield _this.updateThreadMetadata();\n        }\n      });\n      return function (_x, _x2, _x3) {\n        return _ref2.apply(this, arguments);\n      };\n    }());\n    _defineProperty(this, \"onTimelineEvent\", (event, room, toStartOfTimeline) => {\n      // Add a synthesized receipt when paginating forward in the timeline\n      if (!toStartOfTimeline) {\n        var sender = event.getSender();\n        if (sender && room && this.shouldSendLocalEchoReceipt(sender, event)) {\n          room.addLocalEchoReceipt(sender, event, ReceiptType.Read);\n        }\n        if (event.getId() !== this.id && event.isRelation(THREAD_RELATION_TYPE.name)) {\n          this.replyCount++;\n        }\n      }\n      this.onEcho(event, toStartOfTimeline !== null && toStartOfTimeline !== void 0 ? toStartOfTimeline : false);\n    });\n    _defineProperty(this, \"onLocalEcho\", event => {\n      this.onEcho(event, false);\n    });\n    _defineProperty(this, \"onEcho\", /*#__PURE__*/function () {\n      var _ref3 = _asyncToGenerator(function* (event, toStartOfTimeline) {\n        if (event.threadRootId !== _this.id) return; // ignore echoes for other timelines\n        if (_this.lastEvent === event) return; // ignore duplicate events\n        yield _this.updateThreadMetadata();\n        if (!event.isRelation(THREAD_RELATION_TYPE.name)) return; // don't send a new reply event for reactions or edits\n        if (toStartOfTimeline) return; // ignore messages added to the start of the timeline\n        // Clear the lastEvent and instead start tracking locally using lastReply\n        _this.lastEvent = undefined;\n        _this.emit(ThreadEvent.NewReply, _this, event);\n      });\n      return function (_x4, _x5) {\n        return _ref3.apply(this, arguments);\n      };\n    }());\n    this.setMaxListeners(1000);\n    if (!(opts !== null && opts !== void 0 && opts.room)) {\n      // Logging/debugging for https://github.com/vector-im/element-web/issues/22141\n      // Hope is that we end up with a more obvious stack trace.\n      throw new Error(\"element-web#22141: A thread requires a room in order to function\");\n    }\n    this.room = opts.room;\n    this.client = opts.client;\n    this.pendingEventOrdering = (_opts$pendingEventOrd = opts.pendingEventOrdering) !== null && _opts$pendingEventOrd !== void 0 ? _opts$pendingEventOrd : PendingEventOrdering.Chronological;\n    this.timelineSet = new EventTimelineSet(this.room, {\n      timelineSupport: true,\n      pendingEvents: true\n    }, this.client, this);\n    this.reEmitter = new TypedReEmitter(this);\n    this.reEmitter.reEmit(this.timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n    this.room.on(MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction);\n    this.room.on(RoomEvent.Redaction, this.onRedaction);\n    this.room.on(RoomEvent.LocalEchoUpdated, this.onLocalEcho);\n    this.room.on(RoomEvent.TimelineReset, this.onTimelineReset);\n    this.timelineSet.on(RoomEvent.Timeline, this.onTimelineEvent);\n    this.processReceipts(opts.receipts);\n\n    // even if this thread is thought to be originating from this client, we initialise it as we may be in a\n    // gappy sync and a thread around this event may already exist.\n    this.updateThreadMetadata();\n    this.setEventMetadata(this.rootEvent);\n  }\n  fetchRootEvent() {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      // Always fetch the root event, even if we already have it, so we can get the latest\n      // state (via unsigned).\n      try {\n        var eventData = yield _this2.client.fetchRoomEvent(_this2.roomId, _this2.id);\n        var mapper = _this2.client.getEventMapper();\n        _this2.rootEvent = mapper(eventData); // will merge with existing event object if such is known\n      } catch (e) {\n        logger.error(\"Failed to fetch thread root to construct thread with\", e);\n      }\n      yield _this2.processEvent(_this2.rootEvent);\n    })();\n  }\n  static setServerSideSupport(status) {\n    Thread.hasServerSideSupport = status;\n    // XXX: This global latching behaviour is really unexpected and means that you can't undo when moving to a server without support\n    if (status !== FeatureSupport.Stable) {\n      FILTER_RELATED_BY_SENDERS.setPreferUnstable(true);\n      FILTER_RELATED_BY_REL_TYPES.setPreferUnstable(true);\n      THREAD_RELATION_TYPE.setPreferUnstable(true);\n    }\n  }\n  static setServerSideListSupport(status) {\n    Thread.hasServerSideListSupport = status;\n  }\n  static setServerSideFwdPaginationSupport(status) {\n    Thread.hasServerSideFwdPaginationSupport = status;\n  }\n  shouldSendLocalEchoReceipt(sender, event) {\n    var _this$client$canSuppo;\n    var recursionSupport = (_this$client$canSuppo = this.client.canSupport.get(Feature.RelationsRecursion)) !== null && _this$client$canSuppo !== void 0 ? _this$client$canSuppo : ServerSupport.Unsupported;\n    if (recursionSupport === ServerSupport.Unsupported) {\n      var _this$getReadReceiptF;\n      // Normally we add a local receipt, but if we don't have\n      // recursion support, then events may arrive out of order, so we\n      // only create a receipt if it's after our existing receipt.\n      var oldReceiptEventId = (_this$getReadReceiptF = this.getReadReceiptForUserId(sender)) === null || _this$getReadReceiptF === void 0 ? void 0 : _this$getReadReceiptF.eventId;\n      if (oldReceiptEventId) {\n        var receiptEvent = this.findEventById(oldReceiptEventId);\n        if (receiptEvent && receiptEvent.getTs() > event.getTs()) {\n          return false;\n        }\n      }\n    }\n    return true;\n  }\n  get roomState() {\n    return this.room.getLiveTimeline().getState(EventTimeline.FORWARDS);\n  }\n  addEventToTimeline(event, toStartOfTimeline) {\n    if (!this.findEventById(event.getId())) {\n      this.timelineSet.addEventToTimeline(event, this.liveTimeline, {\n        toStartOfTimeline,\n        fromCache: false,\n        roomState: this.roomState,\n        addToState: false\n      });\n    }\n  }\n\n  /**\n   * TEMPORARY. Only call this when MSC3981 is not available, and we have some\n   * late-arriving events to insert, because we recursively found them as part\n   * of populating a thread. When we have MSC3981 we won't need it, because\n   * they will all be supplied by the homeserver in one request, and they will\n   * already be in the right order in that response.\n   * This is a copy of addEventToTimeline above, modified to call\n   * insertEventIntoTimeline so this event is inserted into our best guess of\n   * the right place based on timestamp. (We should be using Sync Order but we\n   * don't have it.)\n   *\n   * @internal\n   */\n  insertEventIntoTimeline(event) {\n    var eventId = event.getId();\n    if (!eventId) {\n      return;\n    }\n    // If the event is already in this thread, bail out\n    if (this.findEventById(eventId)) {\n      return;\n    }\n    this.timelineSet.insertEventIntoTimeline(event, this.liveTimeline, this.roomState, false);\n  }\n  addEvents(events, toStartOfTimeline) {\n    events.forEach(ev => this.addEvent(ev, toStartOfTimeline, false));\n    this.updateThreadMetadata();\n  }\n\n  /**\n   * Add an event to the thread and updates\n   * the tail/root references if needed\n   * Will fire \"Thread.update\"\n   * @param event - The event to add\n   * @param toStartOfTimeline - whether the event is being added\n   * to the start (and not the end) of the timeline.\n   * @param emit - whether to emit the Update event if the thread was updated or not.\n   */\n  addEvent(event, toStartOfTimeline) {\n    var emit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n    // Modify this event to point at our room's state, and mark its thread\n    // as this.\n    this.setEventMetadata(event);\n\n    // Decide whether this event is going to be added at the end of the timeline.\n    var lastReply = this.lastReply();\n    var isNewestReply = !lastReply || event.localTimestamp >= lastReply.localTimestamp;\n    if (!Thread.hasServerSideSupport) {\n      // When there's no server-side support, just add it to the end of the timeline.\n      this.addEventToTimeline(event, toStartOfTimeline);\n      this.client.decryptEventIfNeeded(event);\n    } else if (event.isRelation(RelationType.Annotation) || event.isRelation(RelationType.Replace)) {\n      this.addRelatedThreadEvent(event, toStartOfTimeline);\n      return;\n    } else if (!toStartOfTimeline && isNewestReply) {\n      // When we've asked for the event to be added to the end,\n      // and this event belongs at the end, add it.\n      this.addEventToTimeline(event, false);\n      this.fetchEditsWhereNeeded(event);\n    } else {\n      // Otherwise, we should add it, but we suspect it is out of order.\n      // This may be because we've just created the thread object and are\n      // still fetching events, in which case add it where we think is sensible\n      // and it will be removed and replaced with the events from the pagination\n      // request once that completes.\n      if (toStartOfTimeline) {\n        // If we're adding at the start of the timeline, it doesn't\n        // matter that it's out of order.\n        this.addEventToTimeline(event, toStartOfTimeline);\n      } else {\n        // We think this event might be out of order, because isNewestReply\n        // is false (otherwise we would have gone into the earlier if\n        // clause), so try to insert it in the right place based on\n        // timestamp.\n        this.insertEventIntoTimeline(event);\n      }\n    }\n    if (event.getId() !== this.id && event.isRelation(THREAD_RELATION_TYPE.name) && !toStartOfTimeline && isNewestReply) {\n      // Clear the last event as we have the latest end of the timeline\n      this.lastEvent = undefined;\n    }\n    if (emit) {\n      this.emit(ThreadEvent.NewReply, this, event);\n      this.updateThreadMetadata();\n    }\n  }\n  addRelatedThreadEvent(event, toStartOfTimeline) {\n    // If this event is not a direct member of the thread, but is a\n    // reference to something that is, then we have two cases:\n\n    if (!this.initialEventsFetched) {\n      var _this$replayEvents;\n      // Case 1: we haven't yet fetched events from the server. In\n      // this case, when we do, the events we get back might only be\n      // the first-order ones, so this event (which is second-order -\n      // a reference to something directly in the thread) needs to be\n      // kept so we can replay it when the first-order ones turn up.\n\n      /**\n       * A thread can be fully discovered via a single sync response\n       * And when that's the case we still ask the server to do an initialisation\n       * as it's the safest to ensure we have everything.\n       * However when we are in that scenario we might loose annotation or edits\n       *\n       * This fix keeps a reference to those events and replay them once the thread\n       * has been initialised properly.\n       */\n      (_this$replayEvents = this.replayEvents) === null || _this$replayEvents === void 0 || _this$replayEvents.push(event);\n\n      // For annotations (reactions), aggregate immediately (pre-init) to keep\n      // reaction counts/summary visible while the thread is still initialising.\n      // Only aggregate as child: parent aggregation is unnecessary here.\n      if (event.isRelation(RelationType.Annotation)) {\n        var _this$timelineSet$rel;\n        (_this$timelineSet$rel = this.timelineSet.relations) === null || _this$timelineSet$rel === void 0 || _this$timelineSet$rel.aggregateChildEvent(event, this.timelineSet);\n      }\n    } else {\n      var _this$client$canSuppo2;\n      // Case 2: this is happening later, and we have a timeline. In\n      // this case, these events might be out-of order.\n      //\n      // Specifically, if the server doesn't support recursion, so we\n      // only get these events through sync, they might be coming\n      // later than the first-order ones, so we insert them based on\n      // timestamp (despite the problems with this documented in\n      // #3325).\n      //\n      // If the server does support recursion, we should have got all\n      // the interspersed events from the server when we fetched the\n      // initial events, so if they are coming via sync they should be\n      // the latest ones, so we can add them as normal.\n      //\n      // (Note that both insertEventIntoTimeline and addEventToTimeline\n      // do nothing if we have seen this event before.)\n\n      var recursionSupport = (_this$client$canSuppo2 = this.client.canSupport.get(Feature.RelationsRecursion)) !== null && _this$client$canSuppo2 !== void 0 ? _this$client$canSuppo2 : ServerSupport.Unsupported;\n      if (recursionSupport === ServerSupport.Unsupported) {\n        this.insertEventIntoTimeline(event);\n      } else {\n        this.addEventToTimeline(event, toStartOfTimeline);\n      }\n      // Aggregation is handled by EventTimelineSet when inserting/adding.\n    }\n  }\n  processEvent(event) {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      if (event) {\n        _this3.setEventMetadata(event);\n        yield _this3.fetchEditsWhereNeeded(event);\n      }\n    })();\n  }\n\n  /**\n   * Processes the receipts that were caught during initial sync\n   * When clients become aware of a thread, they try to retrieve those read receipts\n   * and apply them to the current thread\n   * @param receipts - A collection of the receipts cached from initial sync\n   */\n  processReceipts() {\n    var receipts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n    for (var {\n      eventId,\n      receiptType,\n      userId,\n      receipt,\n      synthetic\n    } of receipts) {\n      this.addReceiptToStructure(eventId, receiptType, userId, receipt, synthetic);\n    }\n  }\n  getRootEventBundledRelationship() {\n    var rootEvent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.rootEvent;\n    return rootEvent === null || rootEvent === void 0 ? void 0 : rootEvent.getServerAggregatedRelation(THREAD_RELATION_TYPE.name);\n  }\n  processRootEvent() {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      var bundledRelationship = _this4.getRootEventBundledRelationship();\n      if (Thread.hasServerSideSupport && bundledRelationship) {\n        _this4.replyCount = bundledRelationship.count;\n        _this4._currentUserParticipated = !!bundledRelationship.current_user_participated;\n        var mapper = _this4.client.getEventMapper();\n        // re-insert roomId\n        _this4.lastEvent = mapper(_objectSpread(_objectSpread({}, bundledRelationship.latest_event), {}, {\n          room_id: _this4.roomId\n        }));\n        _this4.updatePendingReplyCount();\n        yield _this4.processEvent(_this4.lastEvent);\n      }\n    })();\n  }\n  updatePendingReplyCount() {\n    var unfilteredPendingEvents = this.pendingEventOrdering === PendingEventOrdering.Detached ? this.room.getPendingEvents() : this.events;\n    var pendingEvents = unfilteredPendingEvents.filter(ev => {\n      var _this$lastEvent2;\n      return ev.threadRootId === this.id && ev.isRelation(THREAD_RELATION_TYPE.name) && ev.status !== null && ev.getId() !== ((_this$lastEvent2 = this.lastEvent) === null || _this$lastEvent2 === void 0 ? void 0 : _this$lastEvent2.getId());\n    });\n    this.lastPendingEvent = pendingEvents.length ? pendingEvents[pendingEvents.length - 1] : undefined;\n    this.pendingReplyCount = pendingEvents.length;\n  }\n\n  /**\n   * Reset the live timeline of all timelineSets, and start new ones.\n   *\n   * <p>This is used when /sync returns a 'limited' timeline. 'Limited' means that there's a gap between the messages\n   * /sync returned, and the last known message in our timeline. In such a case, our live timeline isn't live anymore\n   * and has to be replaced by a new one. To make sure we can continue paginating our timelines correctly, we have to\n   * set new pagination tokens on the old and the new timeline.\n   *\n   * @param backPaginationToken -   token for back-paginating the new timeline\n   * @param forwardPaginationToken - token for forward-paginating the old live timeline,\n   * if absent or null, all timelines are reset, removing old ones (including the previous live\n   * timeline which would otherwise be unable to paginate forwards without this token).\n   * Removing just the old live timeline whilst preserving previous ones is not supported.\n   */\n  resetLiveTimeline(backPaginationToken, forwardPaginationToken) {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      var oldLive = _this5.liveTimeline;\n      _this5.timelineSet.resetLiveTimeline(backPaginationToken !== null && backPaginationToken !== void 0 ? backPaginationToken : undefined, forwardPaginationToken !== null && forwardPaginationToken !== void 0 ? forwardPaginationToken : undefined);\n      var newLive = _this5.liveTimeline;\n\n      // FIXME: Remove the following as soon as https://github.com/matrix-org/synapse/issues/14830 is resolved.\n      //\n      // The pagination API for thread timelines currently can't handle the type of pagination tokens returned by sync\n      //\n      // To make this work anyway, we'll have to transform them into one of the types that the API can handle.\n      // One option is passing the tokens to /messages, which can handle sync tokens, and returns the right format.\n      // /messages does not return new tokens on requests with a limit of 0.\n      // This means our timelines might overlap a slight bit, but that's not an issue, as we deduplicate messages\n      // anyway.\n\n      var newBackward;\n      var oldForward;\n      if (backPaginationToken) {\n        var res = yield _this5.client.createMessagesRequest(_this5.roomId, backPaginationToken, 1, Direction.Forward);\n        newBackward = res.end;\n      }\n      if (forwardPaginationToken) {\n        var _res = yield _this5.client.createMessagesRequest(_this5.roomId, forwardPaginationToken, 1, Direction.Backward);\n        oldForward = _res.start;\n      }\n      // Only replace the token if we don't have paginated away from this position already. This situation doesn't\n      // occur today, but if the above issue is resolved, we'd have to go down this path.\n      if (forwardPaginationToken && oldLive.getPaginationToken(Direction.Forward) === forwardPaginationToken) {\n        oldLive.setPaginationToken(oldForward !== null && oldForward !== void 0 ? oldForward : null, Direction.Forward);\n      }\n      if (backPaginationToken && newLive.getPaginationToken(Direction.Backward) === backPaginationToken) {\n        newLive.setPaginationToken(newBackward !== null && newBackward !== void 0 ? newBackward : null, Direction.Backward);\n      }\n    })();\n  }\n  updateThreadFromRootEvent() {\n    var _this6 = this;\n    return _asyncToGenerator(function* () {\n      if (Thread.hasServerSideSupport) {\n        // Ensure we show *something* as soon as possible, we'll update it as soon as we get better data, but we\n        // don't want the thread preview to be empty if we can avoid it\n        if (!_this6.initialEventsFetched && !_this6.lastEvent) {\n          yield _this6.processRootEvent();\n        }\n        yield _this6.fetchRootEvent();\n      }\n      yield _this6.processRootEvent();\n    })();\n  }\n  updateThreadMetadata() {\n    var _this7 = this;\n    return _asyncToGenerator(function* () {\n      _this7.updatePendingReplyCount();\n      if (!_this7.processRootEventPromise) {\n        // We only want to do this once otherwise we end up rolling back to the last unsigned summary we have for the thread\n        _this7.processRootEventPromise = _this7.updateThreadFromRootEvent();\n      }\n      yield _this7.processRootEventPromise;\n      if (!_this7.initialEventsFetched) {\n        if (_this7.initalEventFetchProm) {\n          yield _this7.initalEventFetchProm;\n        } else {\n          // fetch initial events to allow proper pagination\n          try {\n            // clear out any events that were added before the pagination request\n            // completed (eg. from sync). They'll be replaced by those from the pagination.\n            // Really, we should do this after the pagination request completes, but\n            // paginateEventTimeline does the request and adds the events in one go, so\n            // this would need a refactor in order to do. It's therefore possible there's\n            // a remaining race where an event comes in while the pagination request is\n            // happening.\n            _this7.timelineSet.resetLiveTimeline();\n            // if the thread has regular events, this will just load the last reply.\n            // if the thread is newly created, this will load the root event.\n            if (_this7.replyCount === 0 && _this7.rootEvent) {\n              _this7.timelineSet.addEventsToTimeline([_this7.rootEvent], true, false, _this7.liveTimeline, null);\n              _this7.liveTimeline.setPaginationToken(null, Direction.Backward);\n            } else {\n              _this7.initalEventFetchProm = _this7.client.paginateEventTimeline(_this7.liveTimeline, {\n                backwards: true\n              });\n              yield _this7.initalEventFetchProm;\n            }\n            // We have now fetched the initial events, so set the flag. We need to do this before\n            // we actually add the events, so `this.addEvents` knows that it can now safely add\n            // them rather than buffer them in the pending event list. The main thing is that this\n            // must remain false while the async fetch happens, so we don't try to add events before\n            // the pagination has finished. The important thing is that we're not await-ing anything\n            // else between setting this and adding events, so no races.\n            _this7.initialEventsFetched = true;\n            for (var event of _this7.replayEvents) {\n              _this7.addEvent(event, false);\n            }\n            _this7.replayEvents = null;\n            // just to make sure that, if we've created a timeline window for this thread before the thread itself\n            // existed (e.g. when creating a new thread), we'll make sure the panel is force refreshed correctly.\n            _this7.emit(RoomEvent.TimelineReset, _this7.room, _this7.timelineSet, true);\n          } catch (e) {\n            logger.error(\"Failed to load start of newly created thread: \", e);\n            _this7.initialEventsFetched = false;\n          }\n        }\n      }\n      _this7.emit(ThreadEvent.Update, _this7);\n    })();\n  }\n\n  // XXX: Workaround for https://github.com/matrix-org/matrix-spec-proposals/pull/2676/files#r827240084\n  fetchEditsWhereNeeded() {\n    var _arguments = arguments,\n      _this8 = this;\n    return _asyncToGenerator(function* () {\n      var _this8$client$canSupp;\n      var recursionSupport = (_this8$client$canSupp = _this8.client.canSupport.get(Feature.RelationsRecursion)) !== null && _this8$client$canSupp !== void 0 ? _this8$client$canSupp : ServerSupport.Unsupported;\n      if (recursionSupport === ServerSupport.Unsupported) {\n        for (var _len = _arguments.length, events = new Array(_len), _key = 0; _key < _len; _key++) {\n          events[_key] = _arguments[_key];\n        }\n        return Promise.all(events.filter(isAnEncryptedThreadMessage).map(/*#__PURE__*/function () {\n          var _ref4 = _asyncToGenerator(function* (event) {\n            try {\n              var relations = yield _this8.client.relations(_this8.roomId, event.getId(), RelationType.Replace, event.getType(), {\n                limit: 1\n              });\n              if (relations.events.length) {\n                var editEvent = relations.events[0];\n                event.makeReplaced(editEvent);\n                _this8.insertEventIntoTimeline(editEvent);\n              }\n            } catch (e) {\n              logger.error(\"Failed to load edits for encrypted thread event\", e);\n            }\n          });\n          return function (_x6) {\n            return _ref4.apply(this, arguments);\n          };\n        }()));\n      }\n    })();\n  }\n  setEventMetadata(event) {\n    if (event) {\n      EventTimeline.setEventMetadata(event, this.roomState, false);\n      event.setThread(this);\n    }\n  }\n  clearEventMetadata(event) {\n    if (event) {\n      var _event$event;\n      event.setThread(undefined);\n      (_event$event = event.event) === null || _event$event === void 0 || (_event$event = _event$event.unsigned) === null || _event$event === void 0 || (_event$event = _event$event[\"m.relations\"]) === null || _event$event === void 0 || delete _event$event[THREAD_RELATION_TYPE.name];\n    }\n  }\n\n  /**\n   * Finds an event by ID in the current thread\n   */\n  findEventById(eventId) {\n    return this.timelineSet.findEventById(eventId);\n  }\n\n  /**\n   * Return last reply to the thread, if known.\n   */\n  lastReply() {\n    var matches = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ev => ev.isRelation(THREAD_RELATION_TYPE.name);\n    for (var i = this.timeline.length - 1; i >= 0; i--) {\n      var event = this.timeline[i];\n      if (matches(event)) {\n        return event;\n      }\n    }\n    return null;\n  }\n  get roomId() {\n    return this.room.roomId;\n  }\n\n  /**\n   * The number of messages in the thread\n   * Only count rel_type=m.thread as we want to\n   * exclude annotations from that number\n   */\n  get length() {\n    return this.replyCount + this.pendingReplyCount;\n  }\n\n  /**\n   * A getter for the last event of the thread.\n   * This might be a synthesized event, if so, it will not emit any events to listeners.\n   */\n  get replyToEvent() {\n    var _ref5, _this$lastPendingEven;\n    return (_ref5 = (_this$lastPendingEven = this.lastPendingEvent) !== null && _this$lastPendingEven !== void 0 ? _this$lastPendingEven : this.lastEvent) !== null && _ref5 !== void 0 ? _ref5 : this.lastReply();\n  }\n\n  /**\n   * The live event timeline for this thread.\n   * @deprecated Present for backwards compatibility.\n   *             Use this.events instead\n   * @returns The live event timeline for this thread.\n   */\n  get timeline() {\n    return this.events;\n  }\n  get events() {\n    return this.liveTimeline.getEvents();\n  }\n  has(eventId) {\n    return this.timelineSet.findEventById(eventId) instanceof MatrixEvent;\n  }\n  get hasCurrentUserParticipated() {\n    return this._currentUserParticipated;\n  }\n  get liveTimeline() {\n    return this.timelineSet.getLiveTimeline();\n  }\n  getUnfilteredTimelineSet() {\n    return this.timelineSet;\n  }\n  addReceipt(event, synthetic) {\n    throw new Error(\"Unsupported function on the thread model\");\n  }\n\n  /**\n   * Get the ID of the event that a given user has read up to within this thread,\n   * or null if we have received no read receipt (at all) from them.\n   * @param userId - The user ID to get read receipt event ID for\n   * @param ignoreSynthesized - If true, return only receipts that have been\n   *                            sent by the server, not implicit ones generated\n   *                            by the JS SDK.\n   * @returns ID of the latest event that the given user has read, or null.\n   */\n  getEventReadUpTo(userId, ignoreSynthesized) {\n    // TODO: we think the implementation here is not right. Here is a sketch\n    // of the right answer:\n    //\n    // for event in timeline.events.reversed():\n    //     if room.hasUserReadEvent(event):\n    //         return event\n    // return null\n    //\n    // If this is too slow, we might be able to improve it by trying walking\n    // forward from the threaded receipt in this thread. We could alternate\n    // between backwards-from-front and forwards-from-threaded-receipt to\n    // improve our chances of hitting the right answer sooner.\n    //\n    // Either way, it's still fundamentally slow because we have to walk\n    // events.\n    //\n    // We also might just want to limit the time we spend on this by giving\n    // up after, say, 100 events.\n    //\n    // --- andyb\n\n    var isCurrentUser = userId === this.client.getUserId();\n    var lastReply = this.timeline[this.timeline.length - 1];\n    if (isCurrentUser && lastReply) {\n      // If the last activity in a thread is prior to the first threaded read receipt\n      // sent in the room (suggesting that it was sent before the user started\n      // using a client that supported threaded read receipts), we want to\n      // consider this thread as read.\n      var beforeFirstThreadedReceipt = lastReply.getTs() < this.room.getOldestThreadedReceiptTs();\n      var lastReplyId = lastReply.getId();\n      // Some unsent events do not have an ID, we do not want to consider them read\n      if (beforeFirstThreadedReceipt && lastReplyId) {\n        return lastReplyId;\n      }\n    }\n    var readUpToId = super.getEventReadUpTo(userId, ignoreSynthesized);\n\n    // Check whether the unthreaded read receipt for that user is more recent\n    // than the read receipt inside that thread.\n    if (lastReply) {\n      var unthreadedReceipt = this.room.getLastUnthreadedReceiptFor(userId);\n      if (!unthreadedReceipt) {\n        return readUpToId;\n      }\n      for (var i = ((_this$timeline = this.timeline) === null || _this$timeline === void 0 ? void 0 : _this$timeline.length) - 1; i >= 0; --i) {\n        var _this$timeline, _ev$getId;\n        var ev = this.timeline[i];\n        // If we encounter the `readUpToId` we do not need to look further\n        // there is no \"more recent\" unthreaded read receipt\n        if (ev.getId() === readUpToId) return readUpToId;\n\n        // Inspecting events from most recent to oldest, we're checking\n        // whether an unthreaded read receipt is more recent that the current event.\n        // We usually prefer relying on the order of the DAG but in this scenario\n        // it is not possible and we have to rely on timestamp\n        if (ev.getTs() < unthreadedReceipt.ts) return (_ev$getId = ev.getId()) !== null && _ev$getId !== void 0 ? _ev$getId : readUpToId;\n      }\n    }\n    return readUpToId;\n  }\n\n  /**\n   * Determine if the given user has read a particular event.\n   *\n   * It is invalid to call this method with an event that is not part of this thread.\n   *\n   * This is not a definitive check as it only checks the events that have been\n   * loaded client-side at the time of execution.\n   * @param userId - The user ID to check the read state of.\n   * @param eventId - The event ID to check if the user read.\n   * @returns True if the user has read the event, false otherwise.\n   */\n  hasUserReadEvent(userId, eventId) {\n    if (userId === this.client.getUserId()) {\n      var _this$lastReply$getTs, _this$lastReply, _this$room$getLastUnt, _this$room$getLastUnt2, _this$lastReply$getTs2, _this$lastReply2;\n      // Consider an event read if it's part of a thread that is before the\n      // first threaded receipt sent in that room. It is likely that it is\n      // part of a thread that was created before MSC3771 was implemented.\n      // Or before the last unthreaded receipt for the logged in user\n      var beforeFirstThreadedReceipt = ((_this$lastReply$getTs = (_this$lastReply = this.lastReply()) === null || _this$lastReply === void 0 ? void 0 : _this$lastReply.getTs()) !== null && _this$lastReply$getTs !== void 0 ? _this$lastReply$getTs : 0) < this.room.getOldestThreadedReceiptTs();\n      var unthreadedReceiptTs = (_this$room$getLastUnt = (_this$room$getLastUnt2 = this.room.getLastUnthreadedReceiptFor(userId)) === null || _this$room$getLastUnt2 === void 0 ? void 0 : _this$room$getLastUnt2.ts) !== null && _this$room$getLastUnt !== void 0 ? _this$room$getLastUnt : 0;\n      var beforeLastUnthreadedReceipt = ((_this$lastReply$getTs2 = this === null || this === void 0 || (_this$lastReply2 = this.lastReply()) === null || _this$lastReply2 === void 0 ? void 0 : _this$lastReply2.getTs()) !== null && _this$lastReply$getTs2 !== void 0 ? _this$lastReply$getTs2 : 0) < unthreadedReceiptTs;\n      if (beforeFirstThreadedReceipt || beforeLastUnthreadedReceipt) {\n        return true;\n      }\n    }\n    return this.room.hasUserReadEvent(userId, eventId);\n  }\n  setUnread(type, count) {\n    return this.room.setThreadUnreadNotificationCount(this.id, type, count);\n  }\n\n  /**\n   * Returns the most recent unthreaded receipt for a given user\n   * @param userId - the MxID of the User\n   * @returns an unthreaded Receipt. Can be undefined if receipts have been disabled\n   * or a user chooses to use private read receipts (or we have simply not received\n   * a receipt from this user yet).\n   */\n  getLastUnthreadedReceiptFor(userId) {\n    return this.room.getLastUnthreadedReceiptFor(userId);\n  }\n}\n\n/**\n * Decide whether an event deserves to have its potential edits fetched.\n *\n * @returns true if this event is encrypted and is a message that is part of a\n * thread - either inside it, or a root.\n */\n_defineProperty(Thread, \"hasServerSideSupport\", FeatureSupport.None);\n_defineProperty(Thread, \"hasServerSideListSupport\", FeatureSupport.None);\n_defineProperty(Thread, \"hasServerSideFwdPaginationSupport\", FeatureSupport.None);\nfunction isAnEncryptedThreadMessage(event) {\n  return event.isEncrypted() && (event.isRelation(THREAD_RELATION_TYPE.name) || event.isThreadRoot);\n}\nexport var FILTER_RELATED_BY_SENDERS = new ServerControlledNamespacedValue(\"related_by_senders\", \"io.element.relation_senders\");\nexport var FILTER_RELATED_BY_REL_TYPES = new ServerControlledNamespacedValue(\"related_by_rel_types\", \"io.element.relation_types\");\nexport var THREAD_RELATION_TYPE = new ServerControlledNamespacedValue(\"m.thread\", \"io.element.thread\");\nexport var ThreadFilterType = /*#__PURE__*/function (ThreadFilterType) {\n  ThreadFilterType[ThreadFilterType[\"My\"] = 0] = \"My\";\n  ThreadFilterType[ThreadFilterType[\"All\"] = 1] = \"All\";\n  return ThreadFilterType;\n}({});\nexport function threadFilterTypeToFilter(type) {\n  switch (type) {\n    case ThreadFilterType.My:\n      return \"participated\";\n    default:\n      return \"all\";\n  }\n}\n//# sourceMappingURL=thread.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Common interface for the crypto implementations\n *\n * @internal\n */\n\n/** The methods which crypto implementations should expose to the Sync api\n *\n * @internal\n */\n\n/**\n * @internal\n */\n\n/**\n * The result of a (successful) call to {@link CryptoBackend.decryptEvent}\n */\n\n/**\n * Responsible for decrypting megolm session data retrieved from a remote backup.\n * The result of {@link CryptoBackend#getBackupDecryptor}.\n */\n\n/**\n * Exception thrown when decryption fails\n *\n * @param code - Reason code for the failure.\n *\n * @param msg - user-visible message describing the problem\n *\n * @param details - key/value pairs reported in the logs but not shown\n *   to the user.\n */\nexport class DecryptionError extends Error {\n  constructor(code, msg, details) {\n    super(msg);\n    this.code = code;\n    _defineProperty(this, \"detailedString\", void 0);\n    this.name = \"DecryptionError\";\n    this.detailedString = detailedStringForDecryptionError(this, details);\n  }\n}\nfunction detailedStringForDecryptionError(err, details) {\n  var result = err.name + \"[msg: \" + err.message;\n  if (details) {\n    result += \", \" + Object.keys(details).map(k => k + \": \" + details[k]).join(\", \");\n  }\n  result += \"]\";\n  return result;\n}\n//# sourceMappingURL=CryptoBackend.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2015 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixEvent} and {@link RoomEvent} for\n * the public classes.\n */\n\nimport { ExtensibleEvents } from \"matrix-events-sdk\";\nimport { logger } from \"../logger.js\";\nimport { EVENT_VISIBILITY_CHANGE_TYPE, EventType, RelationType, ToDeviceMessageId, UNSIGNED_THREAD_ID_FIELD, UNSIGNED_MEMBERSHIP_FIELD } from \"../@types/event.js\";\nimport { deepSortedObjectEntries, internaliseString } from \"../utils.js\";\nimport { THREAD_RELATION_TYPE, ThreadEvent } from \"./thread.js\";\nimport { TypedReEmitter } from \"../ReEmitter.js\";\nimport { TypedEventEmitter } from \"./typed-event-emitter.js\";\nimport { DecryptionError } from \"../common-crypto/CryptoBackend.js\";\nimport { EventTimeline } from \"./event-timeline.js\";\nimport { DecryptionFailureCode } from \"../crypto-api/index.js\";\nexport { EventStatus } from \"./event-status.js\";\n\n/* eslint-disable camelcase */\n\n/**\n * When an event is a visibility change event, as per MSC3531,\n * the visibility change implied by the event.\n */\n\n/* eslint-enable camelcase */\n\n/**\n * Message hiding, as specified by https://github.com/matrix-org/matrix-doc/pull/3531.\n */\n\n/**\n * Variant of `MessageVisibility` for the case in which the message should be displayed.\n */\n\n/**\n * Variant of `MessageVisibility` for the case in which the message should be hidden.\n */\n\n// A singleton implementing `IMessageVisibilityVisible`.\nvar MESSAGE_VISIBLE = Object.freeze({\n  visible: true\n});\nexport var MAX_STICKY_DURATION_MS = 3600000;\nexport var MatrixEventEvent = /*#__PURE__*/function (MatrixEventEvent) {\n  /**\n   * An event has been decrypted, or we have failed to decrypt it.\n   *\n   * The payload consists of:\n   *\n   *  * `event` - The {@link MatrixEvent} which we attempted to decrypt.\n   *\n   *  * `err` - The error that occurred during decryption, or `undefined` if no error occurred.\n   *     Avoid use of this: {@link MatrixEvent.decryptionFailureReason} is more useful.\n   */\n  MatrixEventEvent[\"Decrypted\"] = \"Event.decrypted\";\n  MatrixEventEvent[\"BeforeRedaction\"] = \"Event.beforeRedaction\";\n  MatrixEventEvent[\"VisibilityChange\"] = \"Event.visibilityChange\";\n  MatrixEventEvent[\"LocalEventIdReplaced\"] = \"Event.localEventIdReplaced\";\n  MatrixEventEvent[\"Status\"] = \"Event.status\";\n  MatrixEventEvent[\"Replaced\"] = \"Event.replaced\";\n  MatrixEventEvent[\"RelationsCreated\"] = \"Event.relationsCreated\";\n  MatrixEventEvent[\"SentinelUpdated\"] = \"Event.sentinelUpdated\";\n  return MatrixEventEvent;\n}({});\nexport class MatrixEvent extends TypedEventEmitter {\n  /**\n   * Update the sentinels and forwardLooking flag for this event.\n   * @param stateContext -  the room state to be queried\n   * @param toStartOfTimeline -  if true the event's forwardLooking flag is set false\n   * @internal\n   */\n  setMetadata(stateContext, toStartOfTimeline) {\n    var _this$sender, _this$target;\n    // If an event is an m.room.member state event then we should set the sentinels again in case setEventMetadata\n    // was already called before the state was applied and thus the sentinel points at the member from before this event.\n    var affectsSelf = this.isState() && this.getType() === EventType.RoomMember && this.getSender() === this.getStateKey();\n    var changed = false;\n    // When we try to generate a sentinel member before we have that member\n    // in the members object, we still generate a sentinel but it doesn't\n    // have a membership event, so test to see if events.member is set. We\n    // check this to avoid overriding non-sentinel members by sentinel ones\n    // when adding the event to a filtered timeline\n    if (affectsSelf || !((_this$sender = this.sender) !== null && _this$sender !== void 0 && (_this$sender = _this$sender.events) !== null && _this$sender !== void 0 && _this$sender.member)) {\n      var newSender = stateContext.getSentinelMember(this.getSender());\n      if (newSender !== this.sender) changed = true;\n      this.sender = newSender;\n    }\n    if (affectsSelf || !((_this$target = this.target) !== null && _this$target !== void 0 && (_this$target = _this$target.events) !== null && _this$target !== void 0 && _this$target.member) && this.getType() === EventType.RoomMember) {\n      var newTarget = stateContext.getSentinelMember(this.getStateKey());\n      if (newTarget !== this.target) changed = true;\n      this.target = newTarget;\n    }\n    if (this.isState()) {\n      // room state has no concept of 'old' or 'current', but we want the\n      // room state to regress back to previous values if toStartOfTimeline\n      // is set, which means inspecting prev_content if it exists. This\n      // is done by toggling the forwardLooking flag.\n      if (toStartOfTimeline) {\n        this.forwardLooking = false;\n      }\n    }\n    if (changed) {\n      this.emit(MatrixEventEvent.SentinelUpdated);\n    }\n  }\n\n  /**\n   * The sending status of the event.\n   * @privateRemarks\n   * Should be read-only\n   */\n\n  /**\n   * Construct a Matrix Event object\n   *\n   * @param event - The raw (possibly encrypted) event. <b>Do not access\n   * this property</b> directly unless you absolutely have to. Prefer the getter\n   * methods defined on this class. Using the getter methods shields your app\n   * from changes to event JSON between Matrix versions.\n   */\n  constructor() {\n    var _this$getTs;\n    var event = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n    super();\n\n    // intern the values of matrix events to force share strings and reduce the\n    // amount of needless string duplication. This can save moderate amounts of\n    // memory (~10% on a 350MB heap).\n    // 'membership' at the event level (rather than the content level) is a legacy\n    // field that Element never otherwise looks at, but it will still take up a lot\n    // of space if we don't intern it.\n    this.event = event;\n    // applied push rule and action for this event\n    _defineProperty(this, \"pushDetails\", {});\n    _defineProperty(this, \"_replacingEvent\", null);\n    _defineProperty(this, \"_localRedactionEvent\", null);\n    _defineProperty(this, \"_isCancelled\", false);\n    _defineProperty(this, \"clearEvent\", void 0);\n    /* Message hiding, as specified by https://github.com/matrix-org/matrix-doc/pull/3531.\n     Note: We're returning this object, so any value stored here MUST be frozen.\n    */\n    _defineProperty(this, \"visibility\", MESSAGE_VISIBLE);\n    // Not all events will be extensible-event compatible, so cache a flag in\n    // addition to a falsy cached event value. We check the flag later on in\n    // a public getter to decide if the cache is valid.\n    _defineProperty(this, \"_hasCachedExtEv\", false);\n    _defineProperty(this, \"_cachedExtEv\", undefined);\n    /** If we failed to decrypt this event, the reason for the failure. Otherwise, `null`. */\n    _defineProperty(this, \"_decryptionFailureReason\", null);\n    /* curve25519 key which we believe belongs to the sender of the event. See\n     * getSenderKey()\n     */\n    _defineProperty(this, \"senderCurve25519Key\", null);\n    /* ed25519 key which the sender of this event (for olm) or the creator of\n     * the megolm session (for megolm) claims to own. See getClaimedEd25519Key()\n     */\n    _defineProperty(this, \"claimedEd25519Key\", null);\n    /**\n     * If another user forwarded the key to this message\n     * (eg via [MSC4268](https://github.com/matrix-org/matrix-spec-proposals/pull/4268)),\n     * the ID of that user.\n     */\n    _defineProperty(this, \"keyForwardedBy\", void 0);\n    /* if we have a process decrypting this event, a Promise which resolves\n     * when it is finished. Normally null.\n     */\n    _defineProperty(this, \"decryptionPromise\", null);\n    /* flag to indicate if we should retry decrypting this event after the\n     * first attempt (eg, we have received new data which means that a second\n     * attempt may succeed)\n     */\n    _defineProperty(this, \"retryDecryption\", false);\n    /* The txnId with which this event was sent if it was during this session,\n     * allows for a unique ID which does not change when the event comes back down sync.\n     */\n    _defineProperty(this, \"txnId\", void 0);\n    /**\n     * A reference to the thread this event belongs to\n     */\n    _defineProperty(this, \"thread\", void 0);\n    _defineProperty(this, \"threadId\", void 0);\n    /* Set an approximate timestamp for the event relative the local clock.\n     * This will inherently be approximate because it doesn't take into account\n     * the time between the server putting the 'age' field on the event as it sent\n     * it to us and the time we're now constructing this event, but that's better\n     * than assuming the local clock is in sync with the origin HS's clock.\n     */\n    _defineProperty(this, \"localTimestamp\", void 0);\n    /**\n     * The room member who sent this event, or null e.g.\n     * this is a presence event. This is only guaranteed to be set for events that\n     * appear in a timeline, ie. do not guarantee that it will be set on state\n     * events.\n     * @privateRemarks\n     * Should be read-only\n     */\n    _defineProperty(this, \"sender\", null);\n    /**\n     * The room member who is the target of this event, e.g.\n     * the invitee, the person being banned, etc.\n     * @privateRemarks\n     * Should be read-only\n     */\n    _defineProperty(this, \"target\", null);\n    _defineProperty(this, \"status\", null);\n    /**\n     * most recent error associated with sending the event, if any\n     * @privateRemarks\n     * Should be read-only. May not be a MatrixError.\n     */\n    _defineProperty(this, \"error\", null);\n    /**\n     * True if this event is 'forward looking', meaning\n     * that getDirectionalContent() will return event.content and not event.prev_content.\n     * Only state events may be backwards looking\n     * Default: true. <strong>This property is experimental and may change.</strong>\n     * @privateRemarks\n     * Should be read-only\n     */\n    _defineProperty(this, \"forwardLooking\", true);\n    _defineProperty(this, \"reEmitter\", void 0);\n    /**\n     * The timestamp for when this event should expire, in milliseconds.\n     * Prefers using the server-provided value, but will fall back to local calculation.\n     *\n     * This value is **safe** to use, as malicious start time and duration are appropriately capped.\n     *\n     * If the event is not a sticky event (or not supported by the server),\n     * then this returns `undefined`.\n     */\n    _defineProperty(this, \"unstableStickyExpiresAt\", void 0);\n    [\"state_key\", \"type\", \"sender\", \"room_id\", \"membership\"].forEach(prop => {\n      if (typeof event[prop] !== \"string\") return;\n      event[prop] = internaliseString(event[prop]);\n    });\n    [\"membership\", \"avatar_url\", \"displayname\"].forEach(prop => {\n      var _event$content;\n      if (typeof ((_event$content = event.content) === null || _event$content === void 0 ? void 0 : _event$content[prop]) !== \"string\") return;\n      event.content[prop] = internaliseString(event.content[prop]);\n    });\n    [\"rel_type\"].forEach(prop => {\n      var _event$content2;\n      if (typeof ((_event$content2 = event.content) === null || _event$content2 === void 0 || (_event$content2 = _event$content2[\"m.relates_to\"]) === null || _event$content2 === void 0 ? void 0 : _event$content2[prop]) !== \"string\") return;\n      event.content[\"m.relates_to\"][prop] = internaliseString(event.content[\"m.relates_to\"][prop]);\n    });\n    this.txnId = event.txn_id;\n    // The localTimestamp is calculated using the age.\n    // Some events lack an `age` property, either because they are EDUs such as typing events,\n    // or due to server-side bugs such as https://github.com/matrix-org/synapse/issues/8429.\n    // The fallback in these cases will be to use the origin_server_ts.\n    // For EDUs, the origin_server_ts also is not defined so we use Date.now().\n    var age = this.getAge();\n    var now = Date.now();\n    this.localTimestamp = age !== undefined ? now - age : (_this$getTs = this.getTs()) !== null && _this$getTs !== void 0 ? _this$getTs : now;\n    this.reEmitter = new TypedReEmitter(this);\n    if (this.unstableStickyInfo) {\n      if (this.unstableStickyInfo.duration_ttl_ms) {\n        this.unstableStickyExpiresAt = now + this.unstableStickyInfo.duration_ttl_ms;\n      } else {\n        // Bound the timestamp so it doesn't come from the future.\n        this.unstableStickyExpiresAt = Math.min(now, this.getTs()) + this.unstableStickyInfo.duration_ms;\n      }\n    }\n  }\n\n  /**\n   * Unstable getter to try and get an extensible event. Note that this might\n   * return a falsy value if the event could not be parsed as an extensible\n   * event.\n   *\n   * @deprecated Use stable functions where possible.\n   */\n  get unstableExtensibleEvent() {\n    if (!this._hasCachedExtEv) {\n      var _ExtensibleEvents$par;\n      this._cachedExtEv = (_ExtensibleEvents$par = ExtensibleEvents.parse(this.getEffectiveEvent())) !== null && _ExtensibleEvents$par !== void 0 ? _ExtensibleEvents$par : undefined;\n    }\n    return this._cachedExtEv;\n  }\n  invalidateExtensibleEvent() {\n    // just reset the flag - that'll trick the getter into parsing a new event\n    this._hasCachedExtEv = false;\n  }\n\n  /**\n   * Gets the event as it would appear if it had been sent unencrypted.\n   *\n   * If the event is encrypted, we attempt to mock up an event as it would have looked had the sender not encrypted it.\n   * If the event is not encrypted, a copy of it is simply returned as-is.\n   *\n   * @returns A shallow copy of the event, in wire format, as it would have been had it not been encrypted.\n   */\n  getEffectiveEvent() {\n    var content = Object.assign({}, this.getContent()); // clone for mutation\n\n    if (this.getWireType() === EventType.RoomMessageEncrypted) {\n      // Encrypted events sometimes aren't symmetrical on the `content` so we'll copy\n      // that over too, but only for missing properties. We don't copy over mismatches\n      // between the plain and decrypted copies of `content` because we assume that the\n      // app is relying on the decrypted version, so we want to expose that as a source\n      // of truth here too.\n      for (var [_key, value] of Object.entries(this.getWireContent())) {\n        // Skip fields from the encrypted event schema though - we don't want to leak\n        // these.\n        if ([\"algorithm\", \"ciphertext\", \"device_id\", \"sender_key\", \"session_id\"].includes(_key)) {\n          continue;\n        }\n        if (content[_key] === undefined) content[_key] = value;\n      }\n    }\n\n    // clearEvent doesn't have all the fields, so we'll copy what we can from this.event.\n    // We also copy over our \"fixed\" content key.\n    return Object.assign({}, this.event, this.clearEvent, {\n      content\n    });\n  }\n\n  /**\n   * Get the event_id for this event.\n   * @returns The event ID, e.g. <code>$143350589368169JsLZx:localhost\n   * </code>\n   */\n  getId() {\n    return this.event.event_id;\n  }\n\n  /**\n   * Get the user_id for this event.\n   * @returns The user ID, e.g. `@alice:matrix.org`\n   */\n  getSender() {\n    return this.event.sender; // v2 / v1\n  }\n\n  /**\n   * Get the (decrypted, if necessary) type of event.\n   *\n   * @returns The event type, e.g. `m.room.message`\n   */\n  getType() {\n    if (this.clearEvent) {\n      return this.clearEvent.type;\n    }\n    return this.event.type;\n  }\n\n  /**\n   * Get the (possibly encrypted) type of the event that will be sent to the\n   * homeserver.\n   *\n   * @returns The event type.\n   */\n  getWireType() {\n    return this.event.type;\n  }\n\n  /**\n   * Get the room_id for this event. This will return `undefined`\n   * for `m.presence` events.\n   * @returns The room ID, e.g. <code>!cURbafjkfsMDVwdRDQ:matrix.org\n   * </code>\n   */\n  getRoomId() {\n    return this.event.room_id;\n  }\n\n  /**\n   * Get the timestamp of this event.\n   * @returns The event timestamp, e.g. `1433502692297`\n   */\n  getTs() {\n    return this.event.origin_server_ts;\n  }\n\n  /**\n   * Get the timestamp of this event, as a Date object.\n   * @returns The event date, e.g. `new Date(1433502692297)`\n   */\n  getDate() {\n    return this.event.origin_server_ts ? new Date(this.event.origin_server_ts) : null;\n  }\n\n  /**\n   * Get a string containing details of this event\n   *\n   * This is intended for logging, to help trace errors. Example output:\n   *\n   * @example\n   * ```\n   * id=$HjnOHV646n0SjLDAqFrgIjim7RCpB7cdMXFrekWYAn type=m.room.encrypted\n   * sender=@user:example.com room=!room:example.com ts=2022-10-25T17:30:28.404Z\n   * ```\n   */\n  getDetails() {\n    var room = this.getRoomId();\n    if (room) {\n      var _this$getDate;\n      // in-room event\n      return \"id=\".concat(this.getId(), \" type=\").concat(this.getWireType(), \" sender=\").concat(this.getSender(), \" room=\").concat(room, \" ts=\").concat((_this$getDate = this.getDate()) === null || _this$getDate === void 0 ? void 0 : _this$getDate.toISOString());\n    } else {\n      // to-device event\n      var msgid = this.getContent()[ToDeviceMessageId];\n      return \"msgid=\".concat(msgid, \" type=\").concat(this.getWireType(), \" sender=\").concat(this.getSender());\n    }\n  }\n\n  /**\n   * Get the (decrypted, if necessary) event content JSON, even if the event\n   * was replaced by another event.\n   *\n   * @returns The event content JSON, or an empty object.\n   */\n  getOriginalContent() {\n    var _this$event$content;\n    if (this._localRedactionEvent) {\n      return {};\n    }\n    if (this.clearEvent) {\n      var _this$clearEvent$cont;\n      return (_this$clearEvent$cont = this.clearEvent.content) !== null && _this$clearEvent$cont !== void 0 ? _this$clearEvent$cont : {};\n    }\n    return (_this$event$content = this.event.content) !== null && _this$event$content !== void 0 ? _this$event$content : {};\n  }\n\n  /**\n   * Get the (decrypted, if necessary) event content JSON,\n   * or the content from the replacing event, if any.\n   * See `makeReplaced`.\n   *\n   * @returns The event content JSON, or an empty object.\n   */\n  getContent() {\n    if (this._localRedactionEvent) {\n      return {};\n    } else if (this._replacingEvent) {\n      var _this$_replacingEvent;\n      return (_this$_replacingEvent = this._replacingEvent.getContent()[\"m.new_content\"]) !== null && _this$_replacingEvent !== void 0 ? _this$_replacingEvent : {};\n    } else {\n      return this.getOriginalContent();\n    }\n  }\n\n  /**\n   * Get the (possibly encrypted) event content JSON that will be sent to the\n   * homeserver.\n   *\n   * @returns The event content JSON, or an empty object.\n   */\n  getWireContent() {\n    return this.event.content || {};\n  }\n\n  /**\n   * Get the event ID of the thread head\n   */\n  get threadRootId() {\n    var _this$getWireContent;\n    // don't allow state events to be threaded as per the spec\n    if (this.isState()) {\n      return undefined;\n    }\n    var relatesTo = (_this$getWireContent = this.getWireContent()) === null || _this$getWireContent === void 0 ? void 0 : _this$getWireContent[\"m.relates_to\"];\n    if ((relatesTo === null || relatesTo === void 0 ? void 0 : relatesTo.rel_type) === THREAD_RELATION_TYPE.name) {\n      return relatesTo.event_id;\n    }\n    if (this.thread) {\n      return this.thread.id;\n    }\n    if (this.threadId !== undefined) {\n      return this.threadId;\n    }\n    var unsigned = this.getUnsigned();\n    if (typeof unsigned[UNSIGNED_THREAD_ID_FIELD.name] === \"string\") {\n      return unsigned[UNSIGNED_THREAD_ID_FIELD.name];\n    }\n    return undefined;\n  }\n\n  /**\n   * A helper to check if an event is a thread's head or not\n   */\n  get isThreadRoot() {\n    // don't allow state events to be threaded as per the spec\n    if (this.isState()) {\n      return false;\n    }\n    var threadDetails = this.getServerAggregatedRelation(THREAD_RELATION_TYPE.name);\n\n    // Bundled relationships only returned when the sync response is limited\n    // hence us having to check both bundled relation and inspect the thread\n    // model\n    return !!threadDetails || this.threadRootId === this.getId();\n  }\n  get replyEventId() {\n    var _this$getWireContent$;\n    return (_this$getWireContent$ = this.getWireContent()[\"m.relates_to\"]) === null || _this$getWireContent$ === void 0 || (_this$getWireContent$ = _this$getWireContent$[\"m.in_reply_to\"]) === null || _this$getWireContent$ === void 0 ? void 0 : _this$getWireContent$.event_id;\n  }\n  get relationEventId() {\n    var _this$getWireContent2;\n    return (_this$getWireContent2 = this.getWireContent()) === null || _this$getWireContent2 === void 0 || (_this$getWireContent2 = _this$getWireContent2[\"m.relates_to\"]) === null || _this$getWireContent2 === void 0 ? void 0 : _this$getWireContent2.event_id;\n  }\n\n  /**\n   * Get the previous event content JSON. This will only return something for\n   * state events which exist in the timeline.\n   * @returns The previous event content JSON, or an empty object.\n   */\n  getPrevContent() {\n    // v2 then v1 then default\n    return this.getUnsigned().prev_content || {};\n  }\n\n  /**\n   * Get either 'content' or 'prev_content' depending on if this event is\n   * 'forward-looking' or not. This can be modified via event.forwardLooking.\n   * In practice, this means we get the chronologically earlier content value\n   * for this event (this method should surely be called getEarlierContent)\n   * <strong>This method is experimental and may change.</strong>\n   * @returns event.content if this event is forward-looking, else\n   * event.prev_content.\n   */\n  getDirectionalContent() {\n    return this.forwardLooking ? this.getContent() : this.getPrevContent();\n  }\n\n  /**\n   * Get the age of this event. This represents the age of the event when the\n   * event arrived at the device, and not the age of the event when this\n   * function was called.\n   * Can only be returned once the server has echo'ed back\n   * @returns The age of this event in milliseconds.\n   */\n  getAge() {\n    return this.getUnsigned().age;\n  }\n\n  /**\n   * Get the age of the event when this function was called.\n   * This is the 'age' field adjusted according to how long this client has\n   * had the event.\n   * @returns The age of this event in milliseconds.\n   */\n  getLocalAge() {\n    return Date.now() - this.localTimestamp;\n  }\n\n  /**\n   * Get the event state_key if it has one. If necessary, this will perform\n   * string-unpacking on the state key, as per MSC4362. This will return\n   * <code>undefined</code> for message events.\n   * @returns The event's `state_key`.\n   */\n  getStateKey() {\n    if (this.clearEvent) {\n      return this.clearEvent.state_key;\n    }\n    return this.event.state_key;\n  }\n\n  /**\n   * Get the raw event state_key if it has one. This may be string-packed as per\n   * MSC4362 if the state event is encrypted. This will return <code>undefined\n   * </code> for message events.\n   * @returns The event's `state_key`.\n   */\n  getWireStateKey() {\n    return this.event.state_key;\n  }\n\n  /**\n   * Check if this event is a state event.\n   * @returns True if this is a state event.\n   */\n  isState() {\n    return this.event.state_key !== undefined;\n  }\n\n  /**\n   * Get the user's room membership at the time the event was sent, as reported\n   * by the server.  This uses MSC4115.\n   *\n   * @returns The user's room membership, or `undefined` if the server does\n   *   not report it.\n   */\n  getMembershipAtEvent() {\n    var unsigned = this.getUnsigned();\n    return UNSIGNED_MEMBERSHIP_FIELD.findIn(unsigned);\n  }\n\n  /**\n   * Replace the content of this event with encrypted versions.\n   * (This is used when sending an event; it should not be used by applications).\n   *\n   * @internal\n   *\n   * @param cryptoType - type of the encrypted event - typically\n   * <tt>\"m.room.encrypted\"</tt>\n   *\n   * @param cryptoContent - raw 'content' for the encrypted event.\n   *\n   * @param senderCurve25519Key - curve25519 key to record for the\n   *   sender of this event.\n   *   See {@link MatrixEvent#getSenderKey}.\n   *\n   * @param claimedEd25519Key - claimed ed25519 key to record for the\n   *   sender if this event.\n   *   See {@link MatrixEvent#getClaimedEd25519Key}\n   */\n  makeEncrypted(cryptoType, cryptoContent, senderCurve25519Key, claimedEd25519Key) {\n    // keep the plain-text data for 'view source'\n    this.clearEvent = {\n      type: this.event.type,\n      content: this.event.content,\n      state_key: this.event.state_key\n    };\n    this.event.type = cryptoType;\n    this.event.content = cryptoContent;\n    this.senderCurve25519Key = senderCurve25519Key;\n    this.claimedEd25519Key = claimedEd25519Key;\n\n    // if this is a state event, pack cleartext type and statekey\n    if (this.isState()) {\n      this.event.state_key = \"\".concat(this.clearEvent.type, \":\").concat(this.clearEvent.state_key);\n    }\n  }\n\n  /**\n   * Check if this event is currently being decrypted.\n   *\n   * @returns True if this event is currently being decrypted, else false.\n   */\n  isBeingDecrypted() {\n    return this.decryptionPromise != null;\n  }\n  getDecryptionPromise() {\n    return this.decryptionPromise;\n  }\n\n  /**\n   * Check if this event is an encrypted event which we failed to decrypt\n   *\n   * (This implies that we might retry decryption at some point in the future)\n   *\n   * @returns True if this event is an encrypted event which we\n   *     couldn't decrypt.\n   */\n  isDecryptionFailure() {\n    return this._decryptionFailureReason !== null;\n  }\n\n  /** If we failed to decrypt this event, the reason for the failure. Otherwise, `null`. */\n  get decryptionFailureReason() {\n    return this._decryptionFailureReason;\n  }\n  shouldAttemptDecryption() {\n    if (this.isRedacted()) return false;\n    if (this.isBeingDecrypted()) return false;\n    if (this.clearEvent) return false;\n    if (!this.isEncrypted()) return false;\n    return true;\n  }\n\n  /**\n   * Start the process of trying to decrypt this event.\n   *\n   * (This is used within the SDK: it isn't intended for use by applications)\n   *\n   * @internal\n   *\n   * @param crypto - crypto module\n   *\n   * @returns promise which resolves (to undefined) when the decryption\n   * attempt is completed.\n   */\n  attemptDecryption(crypto) {\n    var _arguments = arguments,\n      _this = this;\n    return _asyncToGenerator(function* () {\n      var options = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : {};\n      // start with a couple of sanity checks.\n      if (!_this.isEncrypted()) {\n        throw new Error(\"Attempt to decrypt event which isn't encrypted\");\n      }\n      var alreadyDecrypted = _this.clearEvent && !_this.isDecryptionFailure();\n      if (alreadyDecrypted) {\n        // we may want to just ignore this? let's start with rejecting it.\n        throw new Error(\"Attempt to decrypt event which has already been decrypted\");\n      }\n\n      // if we already have a decryption attempt in progress, then it may\n      // fail because it was using outdated info. We now have reason to\n      // succeed where it failed before, but we don't want to have multiple\n      // attempts going at the same time, so just set a flag that says we have\n      // new info.\n      //\n      if (_this.decryptionPromise) {\n        logger.log(\"Event \".concat(_this.getId(), \" already being decrypted; queueing a retry\"));\n        _this.retryDecryption = true;\n        return _this.decryptionPromise;\n      }\n      _this.decryptionPromise = _this.decryptionLoop(crypto, options);\n      return _this.decryptionPromise;\n    })();\n  }\n\n  /**\n   * Calculate the recipients for keyshare requests.\n   *\n   * @param userId - the user who received this event.\n   *\n   * @returns array of recipients\n   */\n  getKeyRequestRecipients(userId) {\n    // send the request to all of our own devices\n    var recipients = [{\n      userId,\n      deviceId: \"*\"\n    }];\n    return recipients;\n  }\n  decryptionLoop(crypto) {\n    var _arguments2 = arguments,\n      _this2 = this;\n    return _asyncToGenerator(function* () {\n      var options = _arguments2.length > 1 && _arguments2[1] !== undefined ? _arguments2[1] : {};\n      // make sure that this method never runs completely synchronously.\n      // (doing so would mean that we would clear decryptionPromise *before*\n      // it is set in attemptDecryption - and hence end up with a stuck\n      // `decryptionPromise`).\n      yield Promise.resolve();\n\n      // eslint-disable-next-line no-constant-condition\n      while (true) {\n        _this2.retryDecryption = false;\n        var err = undefined;\n        try {\n          var res = yield crypto.decryptEvent(_this2);\n          if (options.isRetry === true) {\n            logger.info(\"Decrypted event on retry (\".concat(_this2.getDetails(), \")\"));\n          }\n          _this2.setClearData(res);\n          _this2._decryptionFailureReason = null;\n        } catch (e) {\n          var detailedError = e instanceof DecryptionError ? e.detailedString : String(e);\n          err = e;\n\n          // see if we have a retry queued.\n          //\n          // NB: make sure to keep this check in the same tick of the\n          //   event loop as `decryptionPromise = null` below - otherwise we\n          //   risk a race:\n          //\n          //   * A: we check retryDecryption here and see that it is\n          //        false\n          //   * B: we get a second call to attemptDecryption, which sees\n          //        that decryptionPromise is set so sets\n          //        retryDecryption\n          //   * A: we continue below, clear decryptionPromise, and\n          //        never do the retry.\n          //\n          if (_this2.retryDecryption) {\n            // decryption error, but we have a retry queued.\n            logger.log(\"Error decrypting event (\".concat(_this2.getDetails(), \"), but retrying: \").concat(detailedError));\n            continue;\n          }\n\n          // decryption error, no retries queued. Warn about the error and\n          // set it to m.bad.encrypted.\n          //\n          // the detailedString already includes the name and message of the error, and the stack isn't much use,\n          // so we don't bother to log `e` separately.\n          logger.warn(\"Error decrypting event (\".concat(_this2.getDetails(), \"): \").concat(detailedError));\n          _this2.setClearDataForDecryptionFailure(String(e));\n          _this2._decryptionFailureReason = e instanceof DecryptionError ? e.code : DecryptionFailureCode.UNKNOWN_ERROR;\n        }\n\n        // Make sure we clear 'decryptionPromise' before sending the 'Event.decrypted' event,\n        // otherwise the app will be confused to see `isBeingDecrypted` still set when\n        // there isn't an `Event.decrypted` on the way.\n        //\n        // see also notes on retryDecryption above.\n        //\n        _this2.decryptionPromise = null;\n        _this2.retryDecryption = false;\n\n        // Before we emit the event, clear the push actions so that they can be recalculated\n        // by relevant code. We do this because the clear event has now changed, making it\n        // so that existing rules can be re-run over the applicable properties. Stuff like\n        // highlighting when the user's name is mentioned rely on this happening. We also want\n        // to set the push actions before emitting so that any notification listeners don't\n        // pick up the wrong contents.\n        _this2.setPushDetails();\n        if (options.emit !== false) {\n          _this2.emit(MatrixEventEvent.Decrypted, _this2, err);\n        }\n        return;\n      }\n    })();\n  }\n\n  /**\n   * Update the cleartext data on this event.\n   *\n   * (This is used after decrypting an event; it should not be used by applications).\n   *\n   * @internal\n   *\n   * @param decryptionResult - the decryption result, including the plaintext and some key info\n   */\n  setClearData(decryptionResult) {\n    var _decryptionResult$sen, _decryptionResult$cla;\n    this.clearEvent = decryptionResult.clearEvent;\n    this.senderCurve25519Key = (_decryptionResult$sen = decryptionResult.senderCurve25519Key) !== null && _decryptionResult$sen !== void 0 ? _decryptionResult$sen : null;\n    this.claimedEd25519Key = (_decryptionResult$cla = decryptionResult.claimedEd25519Key) !== null && _decryptionResult$cla !== void 0 ? _decryptionResult$cla : null;\n    this.keyForwardedBy = decryptionResult.keyForwardedBy;\n    this.invalidateExtensibleEvent();\n  }\n\n  /**\n   * Update the cleartext data on this event after a decryption failure.\n   *\n   * @param reason - the textual reason for the failure\n   */\n  setClearDataForDecryptionFailure(reason) {\n    this.clearEvent = {\n      type: EventType.RoomMessage,\n      content: {\n        msgtype: \"m.bad.encrypted\",\n        body: \"** Unable to decrypt: \".concat(reason, \" **\")\n      }\n    };\n    this.senderCurve25519Key = null;\n    this.claimedEd25519Key = null;\n    this.invalidateExtensibleEvent();\n  }\n\n  /**\n   * Gets the cleartext content for this event. If the event is not encrypted,\n   * or encryption has not been completed, this will return null.\n   *\n   * @returns The cleartext (decrypted) content for the event\n   */\n  getClearContent() {\n    return this.clearEvent ? this.clearEvent.content : null;\n  }\n\n  /**\n   * Check if the event is encrypted.\n   * @returns True if this event is encrypted.\n   */\n  isEncrypted() {\n    return this.event.type === EventType.RoomMessageEncrypted;\n  }\n\n  /**\n   * The curve25519 key for the device that we think sent this event\n   *\n   * For an Olm-encrypted event, this is inferred directly from the DH\n   * exchange at the start of the session: the curve25519 key is involved in\n   * the DH exchange, so only a device which holds the private part of that\n   * key can establish such a session.\n   *\n   * For a megolm-encrypted event, it is inferred from the Olm message which\n   * established the megolm session\n   */\n  getSenderKey() {\n    return this.senderCurve25519Key;\n  }\n\n  /**\n   * The additional keys the sender of this encrypted event claims to possess.\n   *\n   * Just a wrapper for #getClaimedEd25519Key (q.v.)\n   */\n  getKeysClaimed() {\n    if (!this.claimedEd25519Key) return {};\n    return {\n      ed25519: this.claimedEd25519Key\n    };\n  }\n\n  /**\n   * Get the ed25519 the sender of this event claims to own.\n   *\n   * For Olm messages, this claim is encoded directly in the plaintext of the\n   * event itself. For megolm messages, it is implied by the m.room_key event\n   * which established the megolm session.\n   *\n   * Until we download the device list of the sender, it's just a claim: the\n   * device list gives a proof that the owner of the curve25519 key used for\n   * this event (and returned by #getSenderKey) also owns the ed25519 key by\n   * signing the public curve25519 key with the ed25519 key.\n   *\n   * In general, applications should not use this method directly, but should\n   * instead use {@link crypto-api!CryptoApi#getEncryptionInfoForEvent}.\n   */\n  getClaimedEd25519Key() {\n    return this.claimedEd25519Key;\n  }\n\n  /**\n   *  Returns an empty array.\n   *\n   * Previously, this returned the chain of Curve25519 keys through which\n   * this session was forwarded, via `m.forwarded_room_key` events.\n   * However, that is not cryptographically reliable, and clients should not\n   * be using it.\n   *\n   * @see https://github.com/matrix-org/matrix-spec/issues/1089\n   * @deprecated\n   */\n  getForwardingCurve25519KeyChain() {\n    return [];\n  }\n\n  /**\n   * @deprecated always returns false\n   */\n  isKeySourceUntrusted() {\n    return false;\n  }\n\n  /**\n   * If another user forwarded the key to this message\n   * (eg via [MSC4268](https://github.com/matrix-org/matrix-spec-proposals/pull/4268)),\n   * get the ID of that user.\n   */\n  getKeyForwardingUser() {\n    return this.keyForwardedBy;\n  }\n  getUnsigned() {\n    return this.event.unsigned || {};\n  }\n  setUnsigned(unsigned) {\n    this.event.unsigned = unsigned;\n  }\n  unmarkLocallyRedacted() {\n    var value = this._localRedactionEvent;\n    this._localRedactionEvent = null;\n    if (this.event.unsigned) {\n      this.event.unsigned.redacted_because = undefined;\n    }\n    return !!value;\n  }\n  markLocallyRedacted(redactionEvent) {\n    if (this._localRedactionEvent) return;\n    this.emit(MatrixEventEvent.BeforeRedaction, this, redactionEvent);\n    this._localRedactionEvent = redactionEvent;\n    if (!this.event.unsigned) {\n      this.event.unsigned = {};\n    }\n    this.event.unsigned.redacted_because = redactionEvent.event;\n  }\n\n  /**\n   * Change the visibility of an event, as per https://github.com/matrix-org/matrix-doc/pull/3531 .\n   *\n   * @param visibilityChange - event holding a hide/unhide payload, or nothing\n   *   if the event is being reset to its original visibility (presumably\n   *   by a visibility event being redacted).\n   *\n   * @remarks\n   * Fires {@link MatrixEventEvent.VisibilityChange} if `visibilityEvent`\n   *   caused a change in the actual visibility of this event, either by making it\n   *   visible (if it was hidden), by making it hidden (if it was visible) or by\n   *   changing the reason (if it was hidden).\n   */\n  applyVisibilityEvent(visibilityChange) {\n    var _visibilityChange$vis, _visibilityChange$rea;\n    var visible = (_visibilityChange$vis = visibilityChange === null || visibilityChange === void 0 ? void 0 : visibilityChange.visible) !== null && _visibilityChange$vis !== void 0 ? _visibilityChange$vis : true;\n    var reason = (_visibilityChange$rea = visibilityChange === null || visibilityChange === void 0 ? void 0 : visibilityChange.reason) !== null && _visibilityChange$rea !== void 0 ? _visibilityChange$rea : null;\n    var change = false;\n    if (this.visibility.visible !== visible) {\n      change = true;\n    } else if (!this.visibility.visible && this.visibility[\"reason\"] !== reason) {\n      change = true;\n    }\n    if (change) {\n      if (visible) {\n        this.visibility = MESSAGE_VISIBLE;\n      } else {\n        this.visibility = Object.freeze({\n          visible: false,\n          reason\n        });\n      }\n      this.emit(MatrixEventEvent.VisibilityChange, this, visible);\n    }\n  }\n\n  /**\n   * Return instructions to display or hide the message.\n   *\n   * @returns Instructions determining whether the message\n   * should be displayed.\n   */\n  messageVisibility() {\n    // Note: We may return `this.visibility` without fear, as\n    // this is a shallow frozen object.\n    return this.visibility;\n  }\n\n  /**\n   * Update the content of an event in the same way it would be by the server\n   * if it were redacted before it was sent to us\n   *\n   * @param redactionEvent - event causing the redaction\n   * @param room - the room in which the event exists\n   */\n  makeRedacted(redactionEvent, room) {\n    // quick sanity-check\n    if (!redactionEvent.event) {\n      throw new Error(\"invalid redactionEvent in makeRedacted\");\n    }\n    this._localRedactionEvent = null;\n    this.emit(MatrixEventEvent.BeforeRedaction, this, redactionEvent);\n    this._replacingEvent = null;\n    // we attempt to replicate what we would see from the server if\n    // the event had been redacted before we saw it.\n    //\n    // The server removes (most of) the content of the event, and adds a\n    // \"redacted_because\" key to the unsigned section containing the\n    // redacted event.\n    if (!this.event.unsigned) {\n      this.event.unsigned = {};\n    }\n    this.event.unsigned.redacted_because = redactionEvent.event;\n    for (var _key2 in this.event) {\n      if (this.event.hasOwnProperty(_key2) && !REDACT_KEEP_KEYS.has(_key2)) {\n        delete this.event[_key2];\n      }\n    }\n\n    // If the event is encrypted prune the decrypted bits\n    if (this.isEncrypted()) {\n      this.clearEvent = undefined;\n    }\n    var keeps = this.getType() in REDACT_KEEP_CONTENT_MAP ? REDACT_KEEP_CONTENT_MAP[this.getType()] : {};\n    var content = this.getContent();\n    for (var _key3 in content) {\n      if (content.hasOwnProperty(_key3) && !keeps[_key3]) {\n        delete content[_key3];\n      }\n    }\n\n    // If the redacted event was in a thread (but not thread root), move it\n    // to the main timeline. This will change if MSC3389 is merged.\n    if (!this.isThreadRoot && this.threadRootId && this.threadRootId !== this.getId()) {\n      this.moveAllRelatedToMainTimeline(room);\n      redactionEvent.moveToMainTimeline(room);\n    }\n    this.invalidateExtensibleEvent();\n  }\n  moveAllRelatedToMainTimeline(room) {\n    var thread = this.thread;\n    this.moveToMainTimeline(room);\n\n    // If we dont have access to the thread, we can only move this\n    // event, not things related to it.\n    if (thread) {\n      for (var _event of thread.events) {\n        var _event$getRelation;\n        if (((_event$getRelation = _event.getRelation()) === null || _event$getRelation === void 0 ? void 0 : _event$getRelation.event_id) === this.getId()) {\n          _event.moveAllRelatedToMainTimeline(room);\n        }\n      }\n    }\n  }\n  moveToMainTimeline(room) {\n    var _this$thread;\n    // Remove it from its thread\n    (_this$thread = this.thread) === null || _this$thread === void 0 || _this$thread.timelineSet.removeEvent(this.getId());\n    this.setThread(undefined);\n\n    // And insert it into the main timeline\n    var timeline = room.getLiveTimeline();\n    // We use insertEventIntoTimeline to insert it in timestamp order,\n    // because we don't know where it should go (until we have MSC4033).\n    timeline.getTimelineSet().insertEventIntoTimeline(this, timeline, timeline.getState(EventTimeline.FORWARDS), false);\n  }\n\n  /**\n   * Check if this event has been redacted\n   *\n   * @returns True if this event has been redacted\n   */\n  isRedacted() {\n    return Boolean(this.getUnsigned().redacted_because);\n  }\n\n  /**\n   * Check if this event is a redaction of another event\n   *\n   * @returns True if this event is a redaction\n   */\n  isRedaction() {\n    return this.getType() === EventType.RoomRedaction;\n  }\n\n  /**\n   * Return the visibility change caused by this event,\n   * as per https://github.com/matrix-org/matrix-doc/pull/3531.\n   *\n   * @returns If the event is a well-formed visibility change event,\n   * an instance of `IVisibilityChange`, otherwise `null`.\n   */\n  asVisibilityChange() {\n    if (!EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType())) {\n      // Not a visibility change event.\n      return null;\n    }\n    var relation = this.getRelation();\n    if (!relation || relation.rel_type != \"m.reference\") {\n      // Ill-formed, ignore this event.\n      return null;\n    }\n    var eventId = relation.event_id;\n    if (!eventId) {\n      // Ill-formed, ignore this event.\n      return null;\n    }\n    var content = this.getWireContent();\n    var visible = !!content.visible;\n    var reason = content.reason;\n    if (reason && typeof reason != \"string\") {\n      // Ill-formed, ignore this event.\n      return null;\n    }\n    // Well-formed visibility change event.\n    return {\n      visible,\n      reason,\n      eventId\n    };\n  }\n\n  /**\n   * Check if this event alters the visibility of another event,\n   * as per https://github.com/matrix-org/matrix-doc/pull/3531.\n   *\n   * @returns True if this event alters the visibility\n   * of another event.\n   */\n  isVisibilityEvent() {\n    return EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType());\n  }\n\n  /**\n   * Get the (decrypted, if necessary) redaction event JSON\n   * if event was redacted\n   *\n   * @returns The redaction event JSON, or an empty object\n   */\n  getRedactionEvent() {\n    var _this$clearEvent, _this$event$unsigned;\n    if (!this.isRedacted()) return null;\n    if ((_this$clearEvent = this.clearEvent) !== null && _this$clearEvent !== void 0 && _this$clearEvent.unsigned) {\n      var _this$clearEvent$unsi, _this$clearEvent2;\n      return (_this$clearEvent$unsi = (_this$clearEvent2 = this.clearEvent) === null || _this$clearEvent2 === void 0 ? void 0 : _this$clearEvent2.unsigned.redacted_because) !== null && _this$clearEvent$unsi !== void 0 ? _this$clearEvent$unsi : null;\n    } else if ((_this$event$unsigned = this.event.unsigned) !== null && _this$event$unsigned !== void 0 && _this$event$unsigned.redacted_because) {\n      return this.event.unsigned.redacted_because;\n    } else {\n      return {};\n    }\n  }\n\n  /**\n   * Get the push actions, if known, for this event\n   *\n   * @returns push actions\n   */\n  getPushActions() {\n    return this.pushDetails.actions || null;\n  }\n\n  /**\n   * Get the push details, if known, for this event\n   *\n   * @returns push actions\n   */\n  getPushDetails() {\n    return this.pushDetails;\n  }\n\n  /**\n   * Set the push details for this event.\n   *\n   * @param pushActions - push actions\n   * @param rule - the executed push rule\n   */\n  setPushDetails(pushActions, rule) {\n    this.pushDetails = {\n      actions: pushActions,\n      rule\n    };\n  }\n\n  /**\n   * Replace the `event` property and recalculate any properties based on it.\n   * @param event - the object to assign to the `event` property\n   */\n  handleRemoteEcho(event) {\n    var _this$getAge;\n    var oldUnsigned = this.getUnsigned();\n    var oldId = this.getId();\n    this.event = event;\n    // if this event was redacted before it was sent, it's locally marked as redacted.\n    // At this point, we've received the remote echo for the event, but not yet for\n    // the redaction that we are sending ourselves. Preserve the locally redacted\n    // state by copying over redacted_because so we don't get a flash of\n    // redacted, not-redacted, redacted as remote echos come in\n    if (oldUnsigned.redacted_because) {\n      if (!this.event.unsigned) {\n        this.event.unsigned = {};\n      }\n      this.event.unsigned.redacted_because = oldUnsigned.redacted_because;\n    }\n    // successfully sent.\n    this.setStatus(null);\n    if (this.getId() !== oldId) {\n      // emit the event if it changed\n      this.emit(MatrixEventEvent.LocalEventIdReplaced, this);\n    }\n    this.localTimestamp = Date.now() - ((_this$getAge = this.getAge()) !== null && _this$getAge !== void 0 ? _this$getAge : 0);\n  }\n\n  /**\n   * Whether the event is in any phase of sending, send failure, waiting for\n   * remote echo, etc.\n   */\n  isSending() {\n    return !!this.status;\n  }\n\n  /**\n   * Update the event's sending status and emit an event as well.\n   *\n   * @param status - The new status\n   */\n  setStatus(status) {\n    this.status = status;\n    this.emit(MatrixEventEvent.Status, this, status);\n  }\n  replaceLocalEventId(eventId) {\n    this.event.event_id = eventId;\n    this.emit(MatrixEventEvent.LocalEventIdReplaced, this);\n  }\n\n  /**\n   * Get whether the event is a relation event, and of a given type if\n   * `relType` is passed in. State events cannot be relation events\n   *\n   * @param relType - if given, checks that the relation is of the\n   * given type\n   */\n  isRelation(relType) {\n    var _this$getWireContent3;\n    // Relation info is lifted out of the encrypted content when sent to\n    // encrypted rooms, so we have to check `getWireContent` for this.\n    var relation = (_this$getWireContent3 = this.getWireContent()) === null || _this$getWireContent3 === void 0 ? void 0 : _this$getWireContent3[\"m.relates_to\"];\n    if (this.isState() && !!(relation !== null && relation !== void 0 && relation.rel_type) && [RelationType.Replace, RelationType.Thread].includes(relation.rel_type)) {\n      // State events cannot be m.replace or m.thread relations\n      return false;\n    }\n    return !!(relation !== null && relation !== void 0 && relation.rel_type && relation.event_id && (relType ? relation.rel_type === relType : true));\n  }\n\n  /**\n   * Get relation info for the event, if any.\n   */\n  getRelation() {\n    var _this$getWireContent$2;\n    if (!this.isRelation()) {\n      return null;\n    }\n    return (_this$getWireContent$2 = this.getWireContent()[\"m.relates_to\"]) !== null && _this$getWireContent$2 !== void 0 ? _this$getWireContent$2 : null;\n  }\n\n  /**\n   * Set an event that replaces the content of this event, through an m.replace relation.\n   *\n   * @param newEvent - the event with the replacing content, if any.\n   *\n   * @remarks\n   * Fires {@link MatrixEventEvent.Replaced}\n   */\n  makeReplaced(newEvent) {\n    // don't allow redacted events to be replaced.\n    // if newEvent is null we allow to go through though,\n    // as with local redaction, the replacing event might get\n    // cancelled, which should be reflected on the target event.\n    if (this.isRedacted() && newEvent) {\n      return;\n    }\n    // don't allow state events to be replaced using this mechanism as per MSC2676\n    if (this.isState()) {\n      return;\n    }\n    if (this._replacingEvent !== newEvent) {\n      this._replacingEvent = newEvent !== null && newEvent !== void 0 ? newEvent : null;\n      this.emit(MatrixEventEvent.Replaced, this);\n      this.invalidateExtensibleEvent();\n    }\n  }\n\n  /**\n   * Returns the status of any associated edit or redaction\n   * (not for reactions/annotations as their local echo doesn't affect the original event),\n   * or else the status of the event.\n   */\n  getAssociatedStatus() {\n    if (this._replacingEvent) {\n      return this._replacingEvent.status;\n    } else if (this._localRedactionEvent) {\n      return this._localRedactionEvent.status;\n    }\n    return this.status;\n  }\n  getServerAggregatedRelation(relType) {\n    var _this$getUnsigned$mR;\n    return (_this$getUnsigned$mR = this.getUnsigned()[\"m.relations\"]) === null || _this$getUnsigned$mR === void 0 ? void 0 : _this$getUnsigned$mR[relType];\n  }\n\n  /**\n   * Returns the event ID of the event replacing the content of this event, if any.\n   */\n  replacingEventId() {\n    var replaceRelation = this.getServerAggregatedRelation(RelationType.Replace);\n    if (replaceRelation) {\n      return replaceRelation.event_id;\n    } else if (this._replacingEvent) {\n      return this._replacingEvent.getId();\n    }\n  }\n\n  /**\n   * Returns the event replacing the content of this event, if any.\n   * Replacements are aggregated on the server, so this would only\n   * return an event in case it came down the sync, or for local echo of edits.\n   */\n  replacingEvent() {\n    return this._replacingEvent;\n  }\n\n  /**\n   * Returns the origin_server_ts of the event replacing the content of this event, if any.\n   */\n  replacingEventDate() {\n    var replaceRelation = this.getServerAggregatedRelation(RelationType.Replace);\n    if (replaceRelation) {\n      var ts = replaceRelation.origin_server_ts;\n      if (Number.isFinite(ts)) {\n        return new Date(ts);\n      }\n    } else if (this._replacingEvent) {\n      var _this$_replacingEvent2;\n      return (_this$_replacingEvent2 = this._replacingEvent.getDate()) !== null && _this$_replacingEvent2 !== void 0 ? _this$_replacingEvent2 : undefined;\n    }\n  }\n\n  /**\n   * Returns the event that wants to redact this event, but hasn't been sent yet.\n   * @returns the event\n   */\n  localRedactionEvent() {\n    return this._localRedactionEvent;\n  }\n\n  /**\n   * For relations and redactions, returns the event_id this event is referring to.\n   */\n  getAssociatedId() {\n    var relation = this.getRelation();\n    if (this.replyEventId) {\n      return this.replyEventId;\n    } else if (relation) {\n      return relation.event_id;\n    } else if (this.isRedaction()) {\n      return this.event.redacts;\n    }\n  }\n\n  /**\n   * Checks if this event is associated with another event. See `getAssociatedId`.\n   */\n  hasAssociation() {\n    return !!this.getAssociatedId();\n  }\n\n  /**\n   * Update the related id with a new one.\n   *\n   * Used to replace a local id with remote one before sending\n   * an event with a related id.\n   *\n   * @param eventId - the new event id\n   */\n  updateAssociatedId(eventId) {\n    var relation = this.getRelation();\n    if (relation) {\n      relation.event_id = eventId;\n    } else if (this.isRedaction()) {\n      this.event.redacts = eventId;\n    }\n  }\n\n  /**\n   * Flags an event as cancelled due to future conditions. For example, a verification\n   * request event in the same sync transaction may be flagged as cancelled to warn\n   * listeners that a cancellation event is coming down the same pipe shortly.\n   * @param cancelled - Whether the event is to be cancelled or not.\n   */\n  flagCancelled() {\n    var cancelled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;\n    this._isCancelled = cancelled;\n  }\n\n  /**\n   * Gets whether or not the event is flagged as cancelled. See flagCancelled() for\n   * more information.\n   * @returns True if the event is cancelled, false otherwise.\n   */\n  isCancelled() {\n    return this._isCancelled;\n  }\n\n  /**\n   * Get a copy/snapshot of this event. The returned copy will be loosely linked\n   * back to this instance, though will have \"frozen\" event information. Other\n   * properties of this MatrixEvent instance will be copied verbatim, which can\n   * mean they are in reference to this instance despite being on the copy too.\n   * The reference the snapshot uses does not change, however members aside from\n   * the underlying event will not be deeply cloned, thus may be mutated internally.\n   * For example, the sender profile will be copied over at snapshot time, and\n   * the sender profile internally may mutate without notice to the consumer.\n   *\n   * This is meant to be used to snapshot the event details themselves, not the\n   * features (such as sender) surrounding the event.\n   * @returns A snapshot of this event.\n   */\n  toSnapshot() {\n    var ev = new MatrixEvent(JSON.parse(JSON.stringify(this.event)));\n    for (var [p, v] of Object.entries(this)) {\n      if (p !== \"event\") {\n        // exclude the thing we just cloned\n        // @ts-ignore - XXX: this is just nasty\n        ev[p] = v;\n      }\n    }\n    return ev;\n  }\n\n  /**\n   * Determines if this event is equivalent to the given event. This only checks\n   * the event object itself, not the other properties of the event. Intended for\n   * use with toSnapshot() to identify events changing.\n   * @param otherEvent - The other event to check against.\n   * @returns True if the events are the same, false otherwise.\n   */\n  isEquivalentTo(otherEvent) {\n    if (!otherEvent) return false;\n    if (otherEvent === this) return true;\n    var myProps = deepSortedObjectEntries(this.event);\n    var theirProps = deepSortedObjectEntries(otherEvent.event);\n    return JSON.stringify(myProps) === JSON.stringify(theirProps);\n  }\n\n  /**\n   * Summarise the event as JSON.\n   *\n   * If encrypted, include both the decrypted and encrypted view of the event.\n   *\n   * This is named `toJSON` for use with `JSON.stringify` which checks objects\n   * for functions named `toJSON` and will call them to customise the output\n   * if they are defined.\n   *\n   * **WARNING** Do not log the result of this method; otherwise, it will end up\n   * in rageshakes, leading to a privacy violation.\n   *\n   * @deprecated Prefer to use {@link MatrixEvent#getEffectiveEvent} or similar.\n   * This method will be removed soon; it is too easy to use it accidentally\n   * and cause a privacy violation (cf https://github.com/vector-im/element-web/issues/26380).\n   * In any case, the value it returns is not a faithful serialization of the object.\n   */\n  toJSON() {\n    var event = this.getEffectiveEvent();\n    if (!this.isEncrypted()) {\n      return event;\n    }\n    return {\n      decrypted: event,\n      encrypted: this.event\n    };\n  }\n  setTxnId(txnId) {\n    this.txnId = txnId;\n  }\n  getTxnId() {\n    return this.txnId;\n  }\n\n  /**\n   * Set the instance of a thread associated with the current event\n   * @param thread - the thread\n   */\n  setThread(thread) {\n    // don't allow state events to be threaded as per the spec\n    if (this.isState()) {\n      return;\n    }\n    if (this.thread) {\n      this.reEmitter.stopReEmitting(this.thread, [ThreadEvent.Update]);\n    }\n    this.thread = thread;\n    this.setThreadId(thread === null || thread === void 0 ? void 0 : thread.id);\n    if (thread) {\n      this.reEmitter.reEmit(thread, [ThreadEvent.Update]);\n    }\n  }\n\n  /**\n   * Get the instance of the thread associated with the current event\n   */\n  getThread() {\n    return this.thread;\n  }\n  setThreadId(threadId) {\n    this.threadId = threadId;\n  }\n\n  /**\n   * Unstable getter to try and get the sticky information for the event.\n   * If the event is not a sticky event (or not supported by the server),\n   * then this returns `undefined`.\n   *\n   * `duration_ms` is safely bounded to a hour.\n   */\n  get unstableStickyInfo() {\n    var _this$event$msc4354_s, _this$event$unsigned2;\n    if (!((_this$event$msc4354_s = this.event.msc4354_sticky) !== null && _this$event$msc4354_s !== void 0 && _this$event$msc4354_s.duration_ms)) {\n      return undefined;\n    }\n    return {\n      duration_ms: Math.min(MAX_STICKY_DURATION_MS, this.event.msc4354_sticky.duration_ms),\n      // This is assumed to be bounded server-side.\n      duration_ttl_ms: (_this$event$unsigned2 = this.event.unsigned) === null || _this$event$unsigned2 === void 0 ? void 0 : _this$event$unsigned2.msc4354_sticky_duration_ttl_ms\n    };\n  }\n}\n\n/* REDACT_KEEP_KEYS gives the keys we keep when an event is redacted\n *\n * This is specified here:\n *  http://matrix.org/speculator/spec/HEAD/client_server/latest.html#redactions\n *\n * Also:\n *  - We keep 'unsigned' since that is created by the local server\n *  - We keep user_id for backwards-compat with v1\n */\nvar REDACT_KEEP_KEYS = new Set([\"event_id\", \"type\", \"room_id\", \"user_id\", \"sender\", \"state_key\", \"prev_state\", \"content\", \"unsigned\", \"origin_server_ts\"]);\n\n// a map from state event type to the .content keys we keep when an event is redacted\nvar REDACT_KEEP_CONTENT_MAP = {\n  [EventType.RoomMember]: {\n    membership: 1\n  },\n  [EventType.RoomJoinRules]: {\n    join_rule: 1\n  },\n  [EventType.RoomPowerLevels]: {\n    ban: 1,\n    events: 1,\n    events_default: 1,\n    kick: 1,\n    redact: 1,\n    state_default: 1,\n    users: 1,\n    users_default: 1\n  }\n};\n//# sourceMappingURL=event.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventType } from \"./@types/event.js\";\nimport { isSupportedReceiptType, MapWithDefault, recursiveMapToObject } from \"./utils.js\";\n/**\n * Summarises the read receipts within a room. Used by the sync accumulator.\n *\n * Given receipts for users, picks the most recently-received one and provides\n * the results in a new fake receipt event returned from\n * buildAccumulatedReceiptEvent().\n *\n * Handles unthreaded receipts and receipts in each thread separately, so the\n * returned event contains the most recently received unthreaded receipt, and\n * the most recently received receipt in each thread.\n */\nexport class ReceiptAccumulator {\n  constructor() {\n    /** user_id -\\> most-recently-received unthreaded receipt */\n    _defineProperty(this, \"unthreadedReadReceipts\", new Map());\n    /** thread_id -\\> user_id -\\> most-recently-received receipt for this thread */\n    _defineProperty(this, \"threadedReadReceipts\", new MapWithDefault(() => new Map()));\n  }\n  /**\n   * Provide an unthreaded receipt for this user. Overwrites any other\n   * unthreaded receipt we have for this user.\n   */\n  setUnthreaded(userId, receipt) {\n    this.unthreadedReadReceipts.set(userId, receipt);\n  }\n\n  /**\n   * Provide a receipt for this user in this thread. Overwrites any other\n   * receipt we have for this user in this thread.\n   */\n  setThreaded(threadId, userId, receipt) {\n    this.threadedReadReceipts.getOrCreate(threadId).set(userId, receipt);\n  }\n\n  /**\n   * @returns an iterator of pairs of [userId, AccumulatedReceipt] - all the\n   *          most recently-received unthreaded receipts for each user.\n   */\n  allUnthreaded() {\n    return this.unthreadedReadReceipts.entries();\n  }\n\n  /**\n   * @returns an iterator of pairs of [userId, AccumulatedReceipt] - all the\n   *          most recently-received threaded receipts for each user, in all\n   *          threads.\n   */\n  *allThreaded() {\n    for (var receiptsForThread of this.threadedReadReceipts.values()) {\n      for (var e of receiptsForThread.entries()) {\n        yield e;\n      }\n    }\n  }\n\n  /**\n   * Given a list of ephemeral events, find the receipts and store the\n   * relevant ones to be returned later from buildAccumulatedReceiptEvent().\n   */\n  consumeEphemeralEvents(events) {\n    events === null || events === void 0 || events.forEach(e => {\n      if (e.type !== EventType.Receipt || !e.content) {\n        // This means we'll drop unknown ephemeral events but that\n        // seems okay.\n        return;\n      }\n\n      // Handle m.receipt events. They clobber based on:\n      //   (user_id, receipt_type)\n      // but they are keyed in the event as:\n      //   content:{ $event_id: { $receipt_type: { $user_id: {json} }}}\n      // so store them in the former so we can accumulate receipt deltas\n      // quickly and efficiently (we expect a lot of them). Fold the\n      // receipt type into the key name since we only have 1 at the\n      // moment (m.read) and nested JSON objects are slower and more\n      // of a hassle to work with. We'll inflate this back out when\n      // getJSON() is called.\n      Object.keys(e.content).forEach(eventId => {\n        Object.entries(e.content[eventId]).forEach(_ref => {\n          var [key, value] = _ref;\n          if (!isSupportedReceiptType(key)) return;\n          for (var userId of Object.keys(value)) {\n            var data = e.content[eventId][key][userId];\n            var receipt = {\n              data: e.content[eventId][key][userId],\n              type: key,\n              eventId\n            };\n\n            // In a world that supports threads, read receipts normally have\n            // a `thread_id` which is either the thread they belong in or\n            // `MAIN_ROOM_TIMELINE`, so we normally use `setThreaded(...)`\n            // here. The `MAIN_ROOM_TIMELINE` is just treated as another\n            // thread.\n            //\n            // We still encounter read receipts that are \"unthreaded\"\n            // (missing the `thread_id` property). These come from clients\n            // that don't support threads, and from threaded clients that\n            // are doing a \"Mark room as read\" operation. Unthreaded\n            // receipts mark everything \"before\" them as read, in all\n            // threads, where \"before\" means in Sync Order i.e. the order\n            // the events were received from the homeserver in a sync.\n            // [Note: we have some bugs where we use timestamp order instead\n            // of Sync Order, because we don't correctly remember the Sync\n            // Order. See #3325.]\n            //\n            // Calling the wrong method will cause incorrect behavior like\n            // messages re-appearing as \"new\" when you already read them\n            // previously.\n            if (!data.thread_id) {\n              this.setUnthreaded(userId, receipt);\n            } else {\n              this.setThreaded(data.thread_id, userId, receipt);\n            }\n          }\n        });\n      });\n    });\n  }\n\n  /**\n   * Build a receipt event that contains all relevant information for this\n   * room, taking the most recently received receipt for each user in an\n   * unthreaded context, and in each thread.\n   */\n  buildAccumulatedReceiptEvent(roomId) {\n    var receiptEvent = {\n      type: EventType.Receipt,\n      room_id: roomId,\n      content: {\n        // $event_id: { \"m.read\": { $user_id: $json } }\n      }\n    };\n    var receiptEventContent = new MapWithDefault(() => new MapWithDefault(() => new Map()));\n    for (var [userId, receiptData] of this.allUnthreaded()) {\n      receiptEventContent.getOrCreate(receiptData.eventId).getOrCreate(receiptData.type).set(userId, receiptData.data);\n    }\n    for (var [_userId, _receiptData] of this.allThreaded()) {\n      receiptEventContent.getOrCreate(_receiptData.eventId).getOrCreate(_receiptData.type).set(_userId, _receiptData.data);\n    }\n    receiptEvent.content = recursiveMapToObject(receiptEventContent);\n    return receiptEventContent.size > 0 ? receiptEvent : null;\n  }\n}\n//# sourceMappingURL=receipt-accumulator.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2017 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link SyncAccumulator} for the public class.\n */\n\nimport { logger } from \"./logger.js\";\nimport { deepCopy } from \"./utils.js\";\nimport { MAX_STICKY_DURATION_MS } from \"./models/event.js\";\nimport { UNREAD_THREAD_NOTIFICATIONS } from \"./@types/sync.js\";\nimport { ReceiptAccumulator } from \"./receipt-accumulator.js\";\n\n/* eslint-disable camelcase */\n\n/** A to-device message as received from the sync. */\n\n/**\n * A (possibly decrypted) to-device message after it has been successfully processed by the sdk.\n *\n * If the message was encrypted, the `encryptionInfo` field will contain the encryption information.\n * If the message was sent in clear, this field will be null.\n *\n * The `message` field contains the message `type`, `content`, and `sender` as if the message was sent in clear.\n */\n\n/* eslint-enable camelcase */\n\nexport var Category = /*#__PURE__*/function (Category) {\n  Category[\"Invite\"] = \"invite\";\n  Category[\"Leave\"] = \"leave\";\n  Category[\"Join\"] = \"join\";\n  Category[\"Knock\"] = \"knock\";\n  return Category;\n}({});\nfunction isTaggedEvent(event) {\n  return \"_localTs\" in event && event[\"_localTs\"] !== undefined;\n}\n\n/**\n * The purpose of this class is to accumulate /sync responses such that a\n * complete \"initial\" JSON response can be returned which accurately represents\n * the sum total of the /sync responses accumulated to date. It only handles\n * room data: that is, everything under the \"rooms\" top-level key.\n *\n * This class is used when persisting room data so a complete /sync response can\n * be loaded from disk and incremental syncs can be performed on the server,\n * rather than asking the server to do an initial sync on startup.\n */\nexport class SyncAccumulator {\n  constructor() {\n    var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n    this.opts = opts;\n    _defineProperty(this, \"accountData\", {});\n    // $event_type: Object\n    _defineProperty(this, \"inviteRooms\", {});\n    // $roomId: { ... sync 'invite' json data ... }\n    _defineProperty(this, \"knockRooms\", {});\n    // $roomId: { ... sync 'knock' json data ... }\n    _defineProperty(this, \"joinRooms\", {});\n    // the /sync token which corresponds to the last time rooms were\n    // accumulated. We remember this so that any caller can obtain a\n    // coherent /sync response and know at what point they should be\n    // streaming from without losing events.\n    _defineProperty(this, \"nextBatch\", null);\n    this.opts.maxTimelineEntries = this.opts.maxTimelineEntries || 50;\n  }\n  accumulate(syncResponse) {\n    var fromDatabase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n    this.accumulateRooms(syncResponse, fromDatabase);\n    this.accumulateAccountData(syncResponse);\n    this.nextBatch = syncResponse.next_batch;\n  }\n  accumulateAccountData(syncResponse) {\n    if (!syncResponse.account_data || !syncResponse.account_data.events) {\n      return;\n    }\n    // Clobbers based on event type.\n    syncResponse.account_data.events.forEach(e => {\n      this.accountData[e.type] = e;\n    });\n  }\n\n  /**\n   * Accumulate incremental /sync room data.\n   * @param syncResponse - the complete /sync JSON\n   * @param fromDatabase - True if the sync response is one saved to the database\n   */\n  accumulateRooms(syncResponse) {\n    var fromDatabase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n    if (!syncResponse.rooms) {\n      return;\n    }\n    if (syncResponse.rooms.invite) {\n      Object.keys(syncResponse.rooms.invite).forEach(roomId => {\n        this.accumulateRoom(roomId, Category.Invite, syncResponse.rooms.invite[roomId], fromDatabase);\n      });\n    }\n    if (syncResponse.rooms.join) {\n      Object.keys(syncResponse.rooms.join).forEach(roomId => {\n        this.accumulateRoom(roomId, Category.Join, syncResponse.rooms.join[roomId], fromDatabase);\n      });\n    }\n    if (syncResponse.rooms.leave) {\n      Object.keys(syncResponse.rooms.leave).forEach(roomId => {\n        this.accumulateRoom(roomId, Category.Leave, syncResponse.rooms.leave[roomId], fromDatabase);\n      });\n    }\n    if (syncResponse.rooms.knock) {\n      Object.keys(syncResponse.rooms.knock).forEach(roomId => {\n        this.accumulateRoom(roomId, Category.Knock, syncResponse.rooms.knock[roomId], fromDatabase);\n      });\n    }\n  }\n  accumulateRoom(roomId, category, data) {\n    var fromDatabase = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n    // Valid /sync state transitions\n    //       +--------+ <======+            1: Accept an invite\n    //   +== | INVITE |        | (5)        2: Leave a room\n    //   |   +--------+ =====+ |            3: Join a public room previously\n    //   |(1)            (4) | |               left (handle as if new room)\n    //   V         (2)       V |            4: Reject an invite\n    // +------+ ========> +--------+         5: Invite to a room previously\n    // | JOIN |    (3)    | LEAVE* |            left (handle as if new room)\n    // +------+ <======== +--------+\n    //\n    // * equivalent to \"no state\"\n    switch (category) {\n      case Category.Invite:\n        // (5)\n        if (this.knockRooms[roomId]) {\n          // was previously knock, now invite, need to delete knock state\n          delete this.knockRooms[roomId];\n        }\n        this.accumulateInviteState(roomId, data);\n        break;\n      case Category.Knock:\n        this.accumulateKnockState(roomId, data);\n        break;\n      case Category.Join:\n        if (this.knockRooms[roomId]) {\n          // delete knock state on join\n          delete this.knockRooms[roomId];\n        } else if (this.inviteRooms[roomId]) {\n          // (1)\n          // was previously invite, now join. We expect /sync to give\n          // the entire state and timeline on 'join', so delete previous\n          // invite state\n          delete this.inviteRooms[roomId];\n        }\n        // (3)\n        this.accumulateJoinState(roomId, data, fromDatabase);\n        break;\n      case Category.Leave:\n        if (this.knockRooms[roomId]) {\n          // delete knock state on leave\n          delete this.knockRooms[roomId];\n        } else if (this.inviteRooms[roomId]) {\n          // (4)\n          delete this.inviteRooms[roomId];\n        } else {\n          // (2)\n          delete this.joinRooms[roomId];\n        }\n        break;\n      default:\n        logger.error(\"Unknown cateogory: \", category);\n    }\n  }\n  accumulateInviteState(roomId, data) {\n    if (!data.invite_state || !data.invite_state.events) {\n      // no new data\n      return;\n    }\n    if (!this.inviteRooms[roomId]) {\n      this.inviteRooms[roomId] = {\n        invite_state: data.invite_state\n      };\n      return;\n    }\n    // accumulate extra keys for invite->invite transitions\n    // clobber based on event type / state key\n    // We expect invite_state to be small, so just loop over the events\n    var currentData = this.inviteRooms[roomId];\n    data.invite_state.events.forEach(e => {\n      var hasAdded = false;\n      for (var i = 0; i < currentData.invite_state.events.length; i++) {\n        var current = currentData.invite_state.events[i];\n        if (current.type === e.type && current.state_key == e.state_key) {\n          currentData.invite_state.events[i] = e; // update\n          hasAdded = true;\n        }\n      }\n      if (!hasAdded) {\n        currentData.invite_state.events.push(e);\n      }\n    });\n  }\n  accumulateKnockState(roomId, data) {\n    if (!data.knock_state || !data.knock_state.events) {\n      // no new data\n      return;\n    }\n    if (!this.knockRooms[roomId]) {\n      this.knockRooms[roomId] = {\n        knock_state: data.knock_state\n      };\n      return;\n    }\n    // accumulate extra keys\n    // clobber based on event type / state key\n    // We expect knock_state to be small, so just loop over the events\n    var currentData = this.knockRooms[roomId];\n    data.knock_state.events.forEach(e => {\n      var hasAdded = false;\n      for (var i = 0; i < currentData.knock_state.events.length; i++) {\n        var current = currentData.knock_state.events[i];\n        if (current.type === e.type && current.state_key == e.state_key) {\n          currentData.knock_state.events[i] = e; // update\n          hasAdded = true;\n        }\n      }\n      if (!hasAdded) {\n        currentData.knock_state.events.push(e);\n      }\n    });\n  }\n\n  // Accumulate timeline and state events in a room.\n  accumulateJoinState(roomId, data) {\n    var _ref, _data, _data$ephemeral, _data$state, _data$orgMatrixMsc, _data$timeline, _data$msc4354_sticky;\n    var fromDatabase = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n    var now = Date.now();\n    // We expect this function to be called a lot (every /sync) so we want\n    // this to be fast. /sync stores events in an array but we often want\n    // to clobber based on type/state_key. Rather than convert arrays to\n    // maps all the time, just keep private maps which contain\n    // the actual current accumulated sync state, and array-ify it when\n    // getJSON() is called.\n\n    // State resolution:\n    // The 'state' key is the delta from the previous sync (or start of time\n    // if no token was supplied), to the START of the timeline. To obtain\n    // the current state, we need to \"roll forward\" state by reading the\n    // timeline. We want to store the current state so we can drop events\n    // out the end of the timeline based on opts.maxTimelineEntries.\n    //\n    //      'state'     'timeline'     current state\n    // |-------x<======================>x\n    //          T   I   M   E\n    //\n    // When getJSON() is called, we 'roll back' the current state by the\n    // number of entries in the timeline to work out what 'state' should be.\n\n    // Back-pagination:\n    // On an initial /sync, the server provides a back-pagination token for\n    // the start of the timeline. When /sync deltas come down, they also\n    // include back-pagination tokens for the start of the timeline. This\n    // means not all events in the timeline have back-pagination tokens, as\n    // it is only the ones at the START of the timeline which have them.\n    // In order for us to have a valid timeline (and back-pagination token\n    // to match), we need to make sure that when we remove old timeline\n    // events, that we roll forward to an event which has a back-pagination\n    // token. This means we can't keep a strict sliding-window based on\n    // opts.maxTimelineEntries, and we may have a few less. We should never\n    // have more though, provided that the /sync limit is less than or equal\n    // to opts.maxTimelineEntries.\n\n    if (!this.joinRooms[roomId]) {\n      // Create truly empty objects so event types of 'hasOwnProperty' and co\n      // don't cause this code to break.\n      this.joinRooms[roomId] = {\n        _currentState: Object.create(null),\n        _timeline: [],\n        _accountData: Object.create(null),\n        _unreadNotifications: {},\n        _unreadThreadNotifications: {},\n        _summary: {},\n        _receipts: new ReceiptAccumulator(),\n        _stickyEvents: []\n      };\n    }\n    var currentData = this.joinRooms[roomId];\n    if (data.account_data && data.account_data.events) {\n      // clobber based on type\n      data.account_data.events.forEach(e => {\n        currentData._accountData[e.type] = e;\n      });\n    }\n\n    // these probably clobber, spec is unclear.\n    if (data.unread_notifications) {\n      currentData._unreadNotifications = data.unread_notifications;\n    }\n    currentData._unreadThreadNotifications = (_ref = (_data = data[UNREAD_THREAD_NOTIFICATIONS.stable]) !== null && _data !== void 0 ? _data : data[UNREAD_THREAD_NOTIFICATIONS.unstable]) !== null && _ref !== void 0 ? _ref : undefined;\n    if (data.summary) {\n      var _sum$HEROES_KEY, _sum$JOINED_COUNT_KEY, _sum$INVITED_COUNT_KE;\n      var HEROES_KEY = \"m.heroes\";\n      var INVITED_COUNT_KEY = \"m.invited_member_count\";\n      var JOINED_COUNT_KEY = \"m.joined_member_count\";\n      var acc = currentData._summary;\n      var sum = data.summary;\n      acc[HEROES_KEY] = (_sum$HEROES_KEY = sum[HEROES_KEY]) !== null && _sum$HEROES_KEY !== void 0 ? _sum$HEROES_KEY : acc[HEROES_KEY];\n      acc[JOINED_COUNT_KEY] = (_sum$JOINED_COUNT_KEY = sum[JOINED_COUNT_KEY]) !== null && _sum$JOINED_COUNT_KEY !== void 0 ? _sum$JOINED_COUNT_KEY : acc[JOINED_COUNT_KEY];\n      acc[INVITED_COUNT_KEY] = (_sum$INVITED_COUNT_KE = sum[INVITED_COUNT_KEY]) !== null && _sum$INVITED_COUNT_KE !== void 0 ? _sum$INVITED_COUNT_KE : acc[INVITED_COUNT_KEY];\n    }\n\n    // We purposefully do not persist m.typing events.\n    // Technically you could refresh a browser before the timer on a\n    // typing event is up, so it'll look like you aren't typing when\n    // you really still are. However, the alternative is worse. If\n    // we do persist typing events, it will look like people are\n    // typing forever until someone really does start typing (which\n    // will prompt Synapse to send down an actual m.typing event to\n    // clobber the one we persisted).\n\n    // Persist the receipts\n    currentData._receipts.consumeEphemeralEvents((_data$ephemeral = data.ephemeral) === null || _data$ephemeral === void 0 ? void 0 : _data$ephemeral.events);\n\n    // if we got a limited sync, we need to remove all timeline entries or else\n    // we will have gaps in the timeline.\n    if (data.timeline && data.timeline.limited) {\n      currentData._timeline = [];\n    }\n\n    // Work out the current state. The deltas need to be applied in the order:\n    // - existing state which didn't come down /sync.\n    // - State events under the 'state' key.\n    // - State events under the 'state_after' key OR state events in the 'timeline' if 'state_after' is not present.\n    (_data$state = data.state) === null || _data$state === void 0 || (_data$state = _data$state.events) === null || _data$state === void 0 || _data$state.forEach(e => {\n      setState(currentData._currentState, e);\n    });\n    (_data$orgMatrixMsc = data[\"org.matrix.msc4222.state_after\"]) === null || _data$orgMatrixMsc === void 0 || (_data$orgMatrixMsc = _data$orgMatrixMsc.events) === null || _data$orgMatrixMsc === void 0 || _data$orgMatrixMsc.forEach(e => {\n      setState(currentData._currentState, e);\n    });\n    (_data$timeline = data.timeline) === null || _data$timeline === void 0 || (_data$timeline = _data$timeline.events) === null || _data$timeline === void 0 || _data$timeline.forEach((e, index) => {\n      var _data$timeline$prev_b;\n      if (!data[\"org.matrix.msc4222.state_after\"]) {\n        // this nops if 'e' isn't a state event\n        setState(currentData._currentState, e);\n      }\n      // append the event to the timeline. The back-pagination token\n      // corresponds to the first event in the timeline\n      var transformedEvent;\n      if (!fromDatabase) {\n        var _e$unsigned;\n        transformedEvent = Object.assign({}, e);\n        if (transformedEvent.unsigned !== undefined) {\n          transformedEvent.unsigned = Object.assign({}, transformedEvent.unsigned);\n        }\n        var age = (_e$unsigned = e.unsigned) === null || _e$unsigned === void 0 ? void 0 : _e$unsigned.age;\n        if (age !== undefined) transformedEvent._localTs = Date.now() - age;\n      } else {\n        transformedEvent = e;\n      }\n      currentData._timeline.push({\n        event: transformedEvent,\n        token: index === 0 ? (_data$timeline$prev_b = data.timeline.prev_batch) !== null && _data$timeline$prev_b !== void 0 ? _data$timeline$prev_b : null : null\n      });\n    });\n\n    // Prune out any events in our stores that have since expired, do this before we\n    // insert new events.\n    currentData._stickyEvents = currentData._stickyEvents.filter(_ref2 => {\n      var {\n        expiresTs\n      } = _ref2;\n      return expiresTs > now;\n    });\n\n    // We want this to be fast, so don't worry about duplicate events here. The RoomStickyEventsStore will\n    // process these events into the correct mapped order.\n    if ((_data$msc4354_sticky = data.msc4354_sticky) !== null && _data$msc4354_sticky !== void 0 && _data$msc4354_sticky.events) {\n      currentData._stickyEvents = currentData._stickyEvents.concat(data.msc4354_sticky.events.map(event => {\n        // If `duration_ms` exceeds the spec limit of a hour, we cap it.\n        var cappedDuration = Math.min(event.msc4354_sticky.duration_ms, MAX_STICKY_DURATION_MS);\n        // If `origin_server_ts` claims to have been from the future, we still bound it to now.\n        var createdTs = Math.min(event.origin_server_ts, now);\n        return {\n          event,\n          expiresTs: cappedDuration + createdTs\n        };\n      }));\n    }\n\n    // attempt to prune the timeline by jumping between events which have\n    // pagination tokens.\n    if (currentData._timeline.length > this.opts.maxTimelineEntries) {\n      var startIndex = currentData._timeline.length - this.opts.maxTimelineEntries;\n      for (var i = startIndex; i < currentData._timeline.length; i++) {\n        if (currentData._timeline[i].token) {\n          // keep all events after this, including this one\n          currentData._timeline = currentData._timeline.slice(i, currentData._timeline.length);\n          break;\n        }\n      }\n    }\n  }\n\n  /**\n   * Return everything under the 'rooms' key from a /sync response which\n   * represents all room data that should be stored. This should be paired\n   * with the sync token which represents the most recent /sync response\n   * provided to accumulate().\n   * @param forDatabase - True to generate a sync to be saved to storage\n   * @returns An object with a \"nextBatch\", \"roomsData\" and \"accountData\"\n   * keys.\n   * The \"nextBatch\" key is a string which represents at what point in the\n   * /sync stream the accumulator reached. This token should be used when\n   * restarting a /sync stream at startup. Failure to do so can lead to missing\n   * events. The \"roomsData\" key is an Object which represents the entire\n   * /sync response from the 'rooms' key onwards. The \"accountData\" key is\n   * a list of raw events which represent global account data.\n   */\n  getJSON() {\n    var forDatabase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n    var data = {\n      join: {},\n      invite: {},\n      knock: {},\n      // always empty. This is set by /sync when a room was previously\n      // in 'invite' or 'join'. On fresh startup, the client won't know\n      // about any previous room being in 'invite' or 'join' so we can\n      // just omit mentioning it at all, even if it has previously come\n      // down /sync.\n      // The notable exception is when a client is kicked or banned:\n      // we may want to hold onto that room so the client can clearly see\n      // why their room has disappeared. We don't persist it though because\n      // it is unclear *when* we can safely remove the room from the DB.\n      // Instead, we assume that if you're loading from the DB, you've\n      // refreshed the page, which means you've seen the kick/ban already.\n      leave: {}\n    };\n    Object.keys(this.inviteRooms).forEach(roomId => {\n      data.invite[roomId] = this.inviteRooms[roomId];\n    });\n    Object.keys(this.knockRooms).forEach(roomId => {\n      data.knock[roomId] = this.knockRooms[roomId];\n    });\n    Object.keys(this.joinRooms).forEach(roomId => {\n      var _roomData$_stickyEven;\n      var roomData = this.joinRooms[roomId];\n      var roomJson = {\n        \"ephemeral\": {\n          events: []\n        },\n        \"account_data\": {\n          events: []\n        },\n        \"state\": {\n          events: []\n        },\n        \"org.matrix.msc4222.state_after\": {\n          events: []\n        },\n        \"timeline\": {\n          events: [],\n          prev_batch: null\n        },\n        \"unread_notifications\": roomData._unreadNotifications,\n        \"unread_thread_notifications\": roomData._unreadThreadNotifications,\n        \"summary\": roomData._summary,\n        \"msc4354_sticky\": (_roomData$_stickyEven = roomData._stickyEvents) !== null && _roomData$_stickyEven !== void 0 && _roomData$_stickyEven.length ? {\n          events: roomData._stickyEvents.map(e => e.event)\n        } : undefined\n      };\n      // Add account data\n      Object.keys(roomData._accountData).forEach(evType => {\n        roomJson.account_data.events.push(roomData._accountData[evType]);\n      });\n      var receiptEvent = roomData._receipts.buildAccumulatedReceiptEvent(roomId);\n\n      // add only if we have some receipt data\n      if (receiptEvent) {\n        roomJson.ephemeral.events.push(receiptEvent);\n      }\n\n      // Add timeline data\n      roomData._timeline.forEach(msgData => {\n        if (!roomJson.timeline.prev_batch) {\n          // the first event we add to the timeline MUST match up to\n          // the prev_batch token.\n          if (!msgData.token) {\n            return; // this shouldn't happen as we prune constantly.\n          }\n          roomJson.timeline.prev_batch = msgData.token;\n        }\n        var transformedEvent;\n        if (!forDatabase && isTaggedEvent(msgData.event)) {\n          // This means we have to copy each event, so we can fix it up to\n          // set a correct 'age' parameter whilst keeping the local timestamp\n          // on our stored event. If this turns out to be a bottleneck, it could\n          // be optimised either by doing this in the main process after the data\n          // has been structured-cloned to go between the worker & main process,\n          // or special-casing data from saved syncs to read the local timestamp\n          // directly rather than turning it into age to then immediately be\n          // transformed back again into a local timestamp.\n          transformedEvent = Object.assign({}, msgData.event);\n          if (transformedEvent.unsigned !== undefined) {\n            transformedEvent.unsigned = Object.assign({}, transformedEvent.unsigned);\n          }\n          delete transformedEvent._localTs;\n          transformedEvent.unsigned = transformedEvent.unsigned || {};\n          transformedEvent.unsigned.age = Date.now() - msgData.event._localTs;\n        } else {\n          transformedEvent = msgData.event;\n        }\n        roomJson.timeline.events.push(transformedEvent);\n      });\n\n      // Add state data: roll back current state to the start of timeline,\n      // by \"reverse clobbering\" from the end of the timeline to the start.\n      // Convert maps back into arrays.\n      var rollBackState = Object.create(null);\n      for (var i = roomJson.timeline.events.length - 1; i >= 0; i--) {\n        var timelineEvent = roomJson.timeline.events[i];\n        if (timelineEvent.state_key === null || timelineEvent.state_key === undefined) {\n          continue; // not a state event\n        }\n        // since we're going back in time, we need to use the previous\n        // state value else we'll break causality. We don't have the\n        // complete previous state event, so we need to create one.\n        var prevStateEvent = deepCopy(timelineEvent);\n        if (prevStateEvent.unsigned) {\n          if (prevStateEvent.unsigned.prev_content) {\n            prevStateEvent.content = prevStateEvent.unsigned.prev_content;\n          }\n          if (prevStateEvent.unsigned.prev_sender) {\n            prevStateEvent.sender = prevStateEvent.unsigned.prev_sender;\n          }\n        }\n        setState(rollBackState, prevStateEvent);\n      }\n      Object.keys(roomData._currentState).forEach(evType => {\n        Object.keys(roomData._currentState[evType]).forEach(stateKey => {\n          var ev = roomData._currentState[evType][stateKey];\n          // Push to both fields to provide downgrade compatibility in the sync accumulator db\n          // the code will prefer `state_after` if it is present\n          roomJson[\"org.matrix.msc4222.state_after\"].events.push(ev);\n          // Roll the state back to the value at the start of the timeline if it was changed\n          if (rollBackState[evType] && rollBackState[evType][stateKey]) {\n            ev = rollBackState[evType][stateKey];\n          }\n          roomJson.state.events.push(ev);\n        });\n      });\n      data.join[roomId] = roomJson;\n    });\n\n    // Add account data\n    var accData = [];\n    Object.keys(this.accountData).forEach(evType => {\n      accData.push(this.accountData[evType]);\n    });\n    return {\n      nextBatch: this.nextBatch,\n      roomsData: data,\n      accountData: accData\n    };\n  }\n  getNextBatchToken() {\n    return this.nextBatch;\n  }\n}\nfunction setState(eventMap, event) {\n  if (event.state_key === null || event.state_key === undefined || !event.type) {\n    return;\n  }\n  if (!eventMap[event.type]) {\n    eventMap[event.type] = Object.create(null);\n  }\n  eventMap[event.type][event.state_key] = event;\n}\n//# sourceMappingURL=sync-accumulator.js.map","/*\nCopyright 2019 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Check if an IndexedDB database exists. The only way to do so is to try opening it, so\n * we do that and then delete it did not exist before.\n *\n * @param indexedDB - The `indexedDB` interface\n * @param dbName - The database name to test for\n * @returns Whether the database exists\n */\nexport function exists(indexedDB, dbName) {\n  return new Promise((resolve, reject) => {\n    var exists = true;\n    var req = indexedDB.open(dbName);\n    req.onupgradeneeded = () => {\n      // Since we did not provide an explicit version when opening, this event\n      // should only fire if the DB did not exist before at any version.\n      exists = false;\n    };\n    req.onblocked = () => reject(req.error);\n    req.onsuccess = () => {\n      var db = req.result;\n      db.close();\n      if (!exists) {\n        // The DB did not exist before, but has been created as part of this\n        // existence check. Delete it now to restore previous state. Delete can\n        // actually take a while to complete in some browsers, so don't wait for\n        // it. This won't block future open calls that a store might issue next to\n        // properly set up the DB.\n        indexedDB.deleteDatabase(dbName);\n      }\n      resolve(exists);\n    };\n    req.onerror = () => reject(req.error);\n  });\n}\n//# sourceMappingURL=indexeddb-helpers.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { SyncAccumulator } from \"../sync-accumulator.js\";\nimport { deepCopy, promiseTry } from \"../utils.js\";\nimport { exists as idbExists } from \"../indexeddb-helpers.js\";\nimport { logger } from \"../logger.js\";\nvar DB_MIGRATIONS = [db => {\n  // Make user store, clobber based on user ID. (userId property of User objects)\n  db.createObjectStore(\"users\", {\n    keyPath: [\"userId\"]\n  });\n\n  // Make account data store, clobber based on event type.\n  // (event.type property of MatrixEvent objects)\n  db.createObjectStore(\"accountData\", {\n    keyPath: [\"type\"]\n  });\n\n  // Make /sync store (sync tokens, room data, etc), always clobber (const key).\n  db.createObjectStore(\"sync\", {\n    keyPath: [\"clobber\"]\n  });\n}, db => {\n  var oobMembersStore = db.createObjectStore(\"oob_membership_events\", {\n    keyPath: [\"room_id\", \"state_key\"]\n  });\n  oobMembersStore.createIndex(\"room\", \"room_id\");\n}, db => {\n  db.createObjectStore(\"client_options\", {\n    keyPath: [\"clobber\"]\n  });\n}, db => {\n  db.createObjectStore(\"to_device_queue\", {\n    autoIncrement: true\n  });\n}\n// Expand as needed.\n];\nvar VERSION = DB_MIGRATIONS.length;\n\n/**\n * Helper method to collect results from a Cursor and promiseify it.\n * @param store - The store to perform openCursor on.\n * @param keyRange - Optional key range to apply on the cursor.\n * @param resultMapper - A function which is repeatedly called with a\n * Cursor.\n * Return the data you want to keep.\n * @returns Promise which resolves to an array of whatever you returned from\n * resultMapper.\n */\nfunction selectQuery(store, keyRange, resultMapper) {\n  var query = store.openCursor(keyRange);\n  return new Promise((resolve, reject) => {\n    var results = [];\n    query.onerror = () => {\n      var _query$error;\n      reject(new Error(\"Query failed: \" + ((_query$error = query.error) === null || _query$error === void 0 ? void 0 : _query$error.name)));\n    };\n    // collect results\n    query.onsuccess = () => {\n      var cursor = query.result;\n      if (!cursor) {\n        resolve(results);\n        return; // end of results\n      }\n      results.push(resultMapper(cursor));\n      cursor.continue();\n    };\n  });\n}\nfunction txnAsPromise(txn) {\n  return new Promise((resolve, reject) => {\n    txn.oncomplete = function (event) {\n      resolve(event);\n    };\n    txn.onerror = function () {\n      reject(txn.error);\n    };\n  });\n}\nfunction reqAsEventPromise(req) {\n  return new Promise((resolve, reject) => {\n    req.onsuccess = function (event) {\n      resolve(event);\n    };\n    req.onerror = function () {\n      reject(req.error);\n    };\n  });\n}\nfunction reqAsPromise(req) {\n  return new Promise((resolve, reject) => {\n    req.onsuccess = () => resolve(req);\n    req.onerror = err => reject(err);\n  });\n}\nfunction reqAsCursorPromise(req) {\n  return reqAsEventPromise(req).then(event => req.result);\n}\nexport class LocalIndexedDBStoreBackend {\n  static exists(indexedDB, dbName) {\n    dbName = \"matrix-js-sdk:\" + (dbName || \"default\");\n    return idbExists(indexedDB, dbName);\n  }\n  /**\n   * Does the actual reading from and writing to the indexeddb\n   *\n   * Construct a new Indexed Database store backend. This requires a call to\n   * `connect()` before this store can be used.\n   * @param indexedDB - The Indexed DB interface e.g\n   * `window.indexedDB`\n   * @param dbName - Optional database name. The same name must be used\n   * to open the same database.\n   */\n  constructor(indexedDB) {\n    var dbName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : \"default\";\n    this.indexedDB = indexedDB;\n    _defineProperty(this, \"dbName\", void 0);\n    _defineProperty(this, \"syncAccumulator\", void 0);\n    _defineProperty(this, \"db\", void 0);\n    _defineProperty(this, \"disconnected\", true);\n    _defineProperty(this, \"_isNewlyCreated\", false);\n    _defineProperty(this, \"syncToDatabasePromise\", void 0);\n    _defineProperty(this, \"pendingUserPresenceData\", []);\n    this.dbName = \"matrix-js-sdk:\" + dbName;\n    this.syncAccumulator = new SyncAccumulator();\n  }\n\n  /**\n   * Attempt to connect to the database. This can fail if the user does not\n   * grant permission.\n   * @returns Promise which resolves if successfully connected.\n   */\n  connect(onClose) {\n    var _this = this;\n    if (!this.disconnected) {\n      logger.log(\"LocalIndexedDBStoreBackend.connect: already connected or connecting\");\n      return Promise.resolve();\n    }\n    this.disconnected = false;\n    logger.log(\"LocalIndexedDBStoreBackend.connect: connecting...\");\n    var req = this.indexedDB.open(this.dbName, VERSION);\n    req.onupgradeneeded = ev => {\n      var db = req.result;\n      var oldVersion = ev.oldVersion;\n      logger.log(\"LocalIndexedDBStoreBackend.connect: upgrading from \".concat(oldVersion));\n      if (oldVersion < 1) {\n        // The database did not previously exist\n        this._isNewlyCreated = true;\n      }\n      DB_MIGRATIONS.forEach((migration, index) => {\n        if (oldVersion <= index) migration(db);\n      });\n    };\n    req.onblocked = () => {\n      logger.log(\"can't yet open LocalIndexedDBStoreBackend because it is open elsewhere\");\n    };\n    logger.log(\"LocalIndexedDBStoreBackend.connect: awaiting connection...\");\n    return reqAsEventPromise(req).then(/*#__PURE__*/_asyncToGenerator(function* () {\n      logger.log(\"LocalIndexedDBStoreBackend.connect: connected\");\n      _this.db = req.result;\n\n      // add a poorly-named listener for when deleteDatabase is called\n      // so we can close our db connections.\n      _this.db.onversionchange = () => {\n        var _this$db;\n        (_this$db = _this.db) === null || _this$db === void 0 || _this$db.close(); // this does not call onclose\n        _this.disconnected = true;\n        _this.db = undefined;\n      };\n      _this.db.onclose = () => {\n        _this.disconnected = true;\n        _this.db = undefined;\n        onClose === null || onClose === void 0 || onClose();\n      };\n      yield _this.init();\n    }));\n  }\n\n  /** @returns whether or not the database was newly created in this session. */\n  isNewlyCreated() {\n    return Promise.resolve(this._isNewlyCreated);\n  }\n\n  /**\n   * Having connected, load initial data from the database and prepare for use\n   * @returns Promise which resolves on success\n   */\n  init() {\n    return Promise.all([this.loadAccountData(), this.loadSyncData()]).then(_ref2 => {\n      var [accountData, syncData] = _ref2;\n      logger.log(\"LocalIndexedDBStoreBackend: loaded initial data\");\n      this.syncAccumulator.accumulate({\n        next_batch: syncData.nextBatch,\n        rooms: syncData.roomsData,\n        account_data: {\n          events: accountData\n        }\n      }, true);\n    });\n  }\n\n  /**\n   * Returns the out-of-band membership events for this room that\n   * were previously loaded.\n   * @returns the events, potentially an empty array if OOB loading didn't yield any new members\n   * @returns in case the members for this room haven't been stored yet\n   */\n  getOutOfBandMembers(roomId) {\n    return new Promise((resolve, reject) => {\n      var tx = this.db.transaction([\"oob_membership_events\"], \"readonly\");\n      var store = tx.objectStore(\"oob_membership_events\");\n      var roomIndex = store.index(\"room\");\n      var range = IDBKeyRange.only(roomId);\n      var request = roomIndex.openCursor(range);\n      var membershipEvents = [];\n      // did we encounter the oob_written marker object\n      // amongst the results? That means OOB member\n      // loading already happened for this room\n      // but there were no members to persist as they\n      // were all known already\n      var oobWritten = false;\n      request.onsuccess = () => {\n        var cursor = request.result;\n        if (!cursor) {\n          // Unknown room\n          if (!membershipEvents.length && !oobWritten) {\n            return resolve(null);\n          }\n          return resolve(membershipEvents);\n        }\n        var record = cursor.value;\n        if (record.oob_written) {\n          oobWritten = true;\n        } else {\n          membershipEvents.push(record);\n        }\n        cursor.continue();\n      };\n      request.onerror = err => {\n        reject(err);\n      };\n    }).then(events => {\n      logger.log(\"LL: got \".concat(events === null || events === void 0 ? void 0 : events.length, \" membershipEvents from storage for room \").concat(roomId, \" ...\"));\n      return events;\n    });\n  }\n\n  /**\n   * Stores the out-of-band membership events for this room. Note that\n   * it still makes sense to store an empty array as the OOB status for the room is\n   * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n   * @param membershipEvents - the membership events to store\n   */\n  setOutOfBandMembers(roomId, membershipEvents) {\n    var _this2 = this;\n    return _asyncToGenerator(function* () {\n      logger.log(\"LL: backend about to store \".concat(membershipEvents.length) + \" members for \".concat(roomId));\n      var tx = _this2.db.transaction([\"oob_membership_events\"], \"readwrite\");\n      var store = tx.objectStore(\"oob_membership_events\");\n      membershipEvents.forEach(e => {\n        store.put(e);\n      });\n      // aside from all the events, we also write a marker object to the store\n      // to mark the fact that OOB members have been written for this room.\n      // It's possible that 0 members need to be written as all where previously know\n      // but we still need to know whether to return null or [] from getOutOfBandMembers\n      // where null means out of band members haven't been stored yet for this room\n      var markerObject = {\n        room_id: roomId,\n        oob_written: true,\n        state_key: 0\n      };\n      store.put(markerObject);\n      yield txnAsPromise(tx);\n      logger.log(\"LL: backend done storing for \".concat(roomId, \"!\"));\n    })();\n  }\n  clearOutOfBandMembers(roomId) {\n    var _this3 = this;\n    return _asyncToGenerator(function* () {\n      // the approach to delete all members for a room\n      // is to get the min and max state key from the index\n      // for that room, and then delete between those\n      // keys in the store.\n      // this should be way faster than deleting every member\n      // individually for a large room.\n      var readTx = _this3.db.transaction([\"oob_membership_events\"], \"readonly\");\n      var store = readTx.objectStore(\"oob_membership_events\");\n      var roomIndex = store.index(\"room\");\n      var roomRange = IDBKeyRange.only(roomId);\n      var minStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, \"next\")).then(cursor => (cursor === null || cursor === void 0 ? void 0 : cursor.primaryKey)[1]);\n      var maxStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, \"prev\")).then(cursor => (cursor === null || cursor === void 0 ? void 0 : cursor.primaryKey)[1]);\n      var [minStateKey, maxStateKey] = yield Promise.all([minStateKeyProm, maxStateKeyProm]);\n      var writeTx = _this3.db.transaction([\"oob_membership_events\"], \"readwrite\");\n      var writeStore = writeTx.objectStore(\"oob_membership_events\");\n      var membersKeyRange = IDBKeyRange.bound([roomId, minStateKey], [roomId, maxStateKey]);\n      logger.log(\"LL: Deleting all users + marker in storage for room \".concat(roomId, \", with key range:\"), [roomId, minStateKey], [roomId, maxStateKey]);\n      yield reqAsPromise(writeStore.delete(membersKeyRange));\n    })();\n  }\n\n  /**\n   * Clear the entire database. This should be used when logging out of a client\n   * to prevent mixing data between accounts. Closes the database.\n   * @returns Resolved when the database is cleared.\n   */\n  clearDatabase() {\n    return new Promise(resolve => {\n      var _this$db2;\n      logger.log(\"Removing indexeddb instance: \".concat(this.dbName));\n\n      // Close the database first to avoid firing unexpected close events\n      (_this$db2 = this.db) === null || _this$db2 === void 0 || _this$db2.close();\n      var req = this.indexedDB.deleteDatabase(this.dbName);\n      req.onblocked = () => {\n        logger.log(\"can't yet delete indexeddb \".concat(this.dbName, \" because it is open elsewhere\"));\n      };\n      req.onerror = () => {\n        var _req$error;\n        // in firefox, with indexedDB disabled, this fails with a\n        // DOMError. We treat this as non-fatal, so that we can still\n        // use the app.\n        logger.warn(\"unable to delete js-sdk store indexeddb: \".concat((_req$error = req.error) === null || _req$error === void 0 ? void 0 : _req$error.name));\n        resolve();\n      };\n      req.onsuccess = () => {\n        logger.log(\"Removed indexeddb instance: \".concat(this.dbName));\n        resolve();\n      };\n    });\n  }\n\n  /**\n   * @param copy - If false, the data returned is from internal\n   * buffers and must not be mutated. Otherwise, a copy is made before\n   * returning such that the data can be safely mutated. Default: true.\n   *\n   * @returns Promise which resolves with a sync response to restore the\n   * client state to where it was at the last save, or null if there\n   * is no saved sync data.\n   */\n  getSavedSync() {\n    var copy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;\n    var data = this.syncAccumulator.getJSON();\n    if (!data.nextBatch) return Promise.resolve(null);\n    if (copy) {\n      // We must deep copy the stored data so that the /sync processing code doesn't\n      // corrupt the internal state of the sync accumulator (it adds non-clonable keys)\n      return Promise.resolve(deepCopy(data));\n    } else {\n      return Promise.resolve(data);\n    }\n  }\n  getNextBatchToken() {\n    return Promise.resolve(this.syncAccumulator.getNextBatchToken());\n  }\n  setSyncData(syncData) {\n    return Promise.resolve().then(() => {\n      this.syncAccumulator.accumulate(syncData);\n    });\n  }\n\n  /**\n   * Sync users and all accumulated sync data to the database.\n   * If a previous sync is in flight, the new data will be added to the\n   * next sync and the current sync's promise will be returned.\n   * @param userTuples - The user tuples\n   * @returns Promise which resolves if the data was persisted.\n   */\n  syncToDatabase(userTuples) {\n    var _this4 = this;\n    return _asyncToGenerator(function* () {\n      if (_this4.syncToDatabasePromise) {\n        logger.warn(\"Skipping syncToDatabase() as persist already in flight\");\n        _this4.pendingUserPresenceData.push(...userTuples);\n        return _this4.syncToDatabasePromise;\n      }\n      userTuples.unshift(..._this4.pendingUserPresenceData);\n      _this4.syncToDatabasePromise = _this4.doSyncToDatabase(userTuples);\n      return _this4.syncToDatabasePromise;\n    })();\n  }\n  doSyncToDatabase(userTuples) {\n    var _this5 = this;\n    return _asyncToGenerator(function* () {\n      try {\n        var syncData = _this5.syncAccumulator.getJSON(true);\n        yield Promise.all([_this5.persistUserPresenceEvents(userTuples), _this5.persistAccountData(syncData.accountData), _this5.persistSyncData(syncData.nextBatch, syncData.roomsData)]);\n      } finally {\n        _this5.syncToDatabasePromise = undefined;\n      }\n    })();\n  }\n\n  /**\n   * Persist rooms /sync data along with the next batch token.\n   * @param nextBatch - The next_batch /sync value.\n   * @param roomsData - The 'rooms' /sync data from a SyncAccumulator\n   * @returns Promise which resolves if the data was persisted.\n   */\n  persistSyncData(nextBatch, roomsData) {\n    logger.log(\"Persisting sync data up to\", nextBatch);\n    return promiseTry(() => {\n      var txn = this.db.transaction([\"sync\"], \"readwrite\");\n      var store = txn.objectStore(\"sync\");\n      store.put({\n        clobber: \"-\",\n        // constant key so will always clobber\n        nextBatch,\n        roomsData\n      }); // put == UPSERT\n      return txnAsPromise(txn).then(() => {\n        logger.log(\"Persisted sync data up to\", nextBatch);\n      });\n    });\n  }\n\n  /**\n   * Persist a list of account data events. Events with the same 'type' will\n   * be replaced.\n   * @param accountData - An array of raw user-scoped account data events\n   * @returns Promise which resolves if the events were persisted.\n   */\n  persistAccountData(accountData) {\n    return promiseTry(() => {\n      var txn = this.db.transaction([\"accountData\"], \"readwrite\");\n      var store = txn.objectStore(\"accountData\");\n      for (var event of accountData) {\n        store.put(event); // put == UPSERT\n      }\n      return txnAsPromise(txn).then();\n    });\n  }\n\n  /**\n   * Persist a list of [user id, presence event] they are for.\n   * Users with the same 'userId' will be replaced.\n   * Presence events should be the event in its raw form (not the Event\n   * object)\n   * @param tuples - An array of [userid, event] tuples\n   * @returns Promise which resolves if the users were persisted.\n   */\n  persistUserPresenceEvents(tuples) {\n    return promiseTry(() => {\n      var txn = this.db.transaction([\"users\"], \"readwrite\");\n      var store = txn.objectStore(\"users\");\n      for (var tuple of tuples) {\n        store.put({\n          userId: tuple[0],\n          event: tuple[1]\n        }); // put == UPSERT\n      }\n      return txnAsPromise(txn).then();\n    });\n  }\n\n  /**\n   * Load all user presence events from the database. This is not cached.\n   * FIXME: It would probably be more sensible to store the events in the\n   * sync.\n   * @returns A list of presence events in their raw form.\n   */\n  getUserPresenceEvents() {\n    return promiseTry(() => {\n      var txn = this.db.transaction([\"users\"], \"readonly\");\n      var store = txn.objectStore(\"users\");\n      return selectQuery(store, undefined, cursor => {\n        return [cursor.value.userId, cursor.value.event];\n      });\n    });\n  }\n\n  /**\n   * Load all the account data events from the database. This is not cached.\n   * @returns A list of raw global account events.\n   */\n  loadAccountData() {\n    logger.log(\"LocalIndexedDBStoreBackend: loading account data...\");\n    return promiseTry(() => {\n      var txn = this.db.transaction([\"accountData\"], \"readonly\");\n      var store = txn.objectStore(\"accountData\");\n      return selectQuery(store, undefined, cursor => {\n        return cursor.value;\n      }).then(result => {\n        logger.log(\"LocalIndexedDBStoreBackend: loaded account data\");\n        return result;\n      });\n    });\n  }\n\n  /**\n   * Load the sync data from the database.\n   * @returns An object with \"roomsData\" and \"nextBatch\" keys.\n   */\n  loadSyncData() {\n    logger.log(\"LocalIndexedDBStoreBackend: loading sync data...\");\n    return promiseTry(() => {\n      var txn = this.db.transaction([\"sync\"], \"readonly\");\n      var store = txn.objectStore(\"sync\");\n      return selectQuery(store, undefined, cursor => {\n        return cursor.value;\n      }).then(results => {\n        logger.log(\"LocalIndexedDBStoreBackend: loaded sync data\");\n        if (results.length > 1) {\n          logger.warn(\"loadSyncData: More than 1 sync row found.\");\n        }\n        return results.length > 0 ? results[0] : {};\n      });\n    });\n  }\n  getClientOptions() {\n    return Promise.resolve().then(() => {\n      var txn = this.db.transaction([\"client_options\"], \"readonly\");\n      var store = txn.objectStore(\"client_options\");\n      return selectQuery(store, undefined, cursor => {\n        var _cursor$value;\n        return (_cursor$value = cursor.value) === null || _cursor$value === void 0 ? void 0 : _cursor$value.options;\n      }).then(results => results[0]);\n    });\n  }\n  storeClientOptions(options) {\n    var _this6 = this;\n    return _asyncToGenerator(function* () {\n      var txn = _this6.db.transaction([\"client_options\"], \"readwrite\");\n      var store = txn.objectStore(\"client_options\");\n      store.put({\n        clobber: \"-\",\n        // constant key so will always clobber\n        options: options\n      }); // put == UPSERT\n      yield txnAsPromise(txn);\n    })();\n  }\n  saveToDeviceBatches(batches) {\n    var _this7 = this;\n    return _asyncToGenerator(function* () {\n      var txn = _this7.db.transaction([\"to_device_queue\"], \"readwrite\");\n      var store = txn.objectStore(\"to_device_queue\");\n      for (var batch of batches) {\n        store.add(batch);\n      }\n      yield txnAsPromise(txn);\n    })();\n  }\n  getOldestToDeviceBatch() {\n    var _this8 = this;\n    return _asyncToGenerator(function* () {\n      var txn = _this8.db.transaction([\"to_device_queue\"], \"readonly\");\n      var store = txn.objectStore(\"to_device_queue\");\n      var cursor = yield reqAsCursorPromise(store.openCursor());\n      if (!cursor) return null;\n      var resultBatch = cursor.value;\n      return {\n        id: cursor.key,\n        txnId: resultBatch.txnId,\n        eventType: resultBatch.eventType,\n        batch: resultBatch.batch\n      };\n    })();\n  }\n  removeToDeviceBatch(id) {\n    var _this9 = this;\n    return _asyncToGenerator(function* () {\n      var txn = _this9.db.transaction([\"to_device_queue\"], \"readwrite\");\n      var store = txn.objectStore(\"to_device_queue\");\n      store.delete(id);\n      yield txnAsPromise(txn);\n    })();\n  }\n\n  /*\n   * Close the database\n   */\n  destroy() {\n    var _this0 = this;\n    return _asyncToGenerator(function* () {\n      var _this0$db;\n      (_this0$db = _this0.db) === null || _this0$db === void 0 || _this0$db.close();\n    })();\n  }\n}\n//# sourceMappingURL=indexeddb-local-backend.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { LocalIndexedDBStoreBackend } from \"./indexeddb-local-backend.js\";\nimport { logger } from \"../logger.js\";\n/**\n * This class lives in the webworker and drives a LocalIndexedDBStoreBackend\n * controlled by messages from the main process.\n *\n * @example\n * It should be instantiated by a web worker script provided by the application\n * in a script, for example:\n * ```\n * import {IndexedDBStoreWorker} from 'matrix-js-sdk/lib/indexeddb-worker.js';\n * const remoteWorker = new IndexedDBStoreWorker(postMessage);\n * onmessage = remoteWorker.onMessage;\n * ```\n *\n * Note that it is advisable to import this class by referencing the file directly to\n * avoid a dependency on the whole js-sdk.\n *\n */\nexport class IndexedDBStoreWorker {\n  /**\n   * @param postMessage - The web worker postMessage function that\n   * should be used to communicate back to the main script.\n   */\n  constructor(postMessage) {\n    this.postMessage = postMessage;\n    _defineProperty(this, \"backend\", void 0);\n    _defineProperty(this, \"onClose\", () => {\n      this.postMessage.call(null, {\n        command: \"closed\"\n      });\n    });\n    /**\n     * Passes a message event from the main script into the class. This method\n     * can be directly assigned to the web worker `onmessage` variable.\n     *\n     * @param ev - The message event\n     */\n    _defineProperty(this, \"onMessage\", ev => {\n      var _this$backend, _this$backend2, _this$backend3, _this$backend4, _this$backend5, _this$backend6, _this$backend7, _this$backend8, _this$backend9, _this$backend0, _this$backend1, _this$backend10, _this$backend11, _this$backend12, _this$backend13, _this$backend14;\n      var msg = ev.data;\n      var prom;\n      switch (msg.command) {\n        case \"setupWorker\":\n          // this is the 'indexedDB' global (where global != window\n          // because it's a web worker and there is no window).\n          this.backend = new LocalIndexedDBStoreBackend(indexedDB, msg.args[0]);\n          prom = Promise.resolve();\n          break;\n        case \"connect\":\n          prom = (_this$backend = this.backend) === null || _this$backend === void 0 ? void 0 : _this$backend.connect(this.onClose);\n          break;\n        case \"isNewlyCreated\":\n          prom = (_this$backend2 = this.backend) === null || _this$backend2 === void 0 ? void 0 : _this$backend2.isNewlyCreated();\n          break;\n        case \"clearDatabase\":\n          prom = (_this$backend3 = this.backend) === null || _this$backend3 === void 0 ? void 0 : _this$backend3.clearDatabase();\n          break;\n        case \"getSavedSync\":\n          prom = (_this$backend4 = this.backend) === null || _this$backend4 === void 0 ? void 0 : _this$backend4.getSavedSync(false);\n          break;\n        case \"setSyncData\":\n          prom = (_this$backend5 = this.backend) === null || _this$backend5 === void 0 ? void 0 : _this$backend5.setSyncData(msg.args[0]);\n          break;\n        case \"syncToDatabase\":\n          prom = (_this$backend6 = this.backend) === null || _this$backend6 === void 0 ? void 0 : _this$backend6.syncToDatabase(msg.args[0]);\n          break;\n        case \"getUserPresenceEvents\":\n          prom = (_this$backend7 = this.backend) === null || _this$backend7 === void 0 ? void 0 : _this$backend7.getUserPresenceEvents();\n          break;\n        case \"getNextBatchToken\":\n          prom = (_this$backend8 = this.backend) === null || _this$backend8 === void 0 ? void 0 : _this$backend8.getNextBatchToken();\n          break;\n        case \"getOutOfBandMembers\":\n          prom = (_this$backend9 = this.backend) === null || _this$backend9 === void 0 ? void 0 : _this$backend9.getOutOfBandMembers(msg.args[0]);\n          break;\n        case \"clearOutOfBandMembers\":\n          prom = (_this$backend0 = this.backend) === null || _this$backend0 === void 0 ? void 0 : _this$backend0.clearOutOfBandMembers(msg.args[0]);\n          break;\n        case \"setOutOfBandMembers\":\n          prom = (_this$backend1 = this.backend) === null || _this$backend1 === void 0 ? void 0 : _this$backend1.setOutOfBandMembers(msg.args[0], msg.args[1]);\n          break;\n        case \"getClientOptions\":\n          prom = (_this$backend10 = this.backend) === null || _this$backend10 === void 0 ? void 0 : _this$backend10.getClientOptions();\n          break;\n        case \"storeClientOptions\":\n          prom = (_this$backend11 = this.backend) === null || _this$backend11 === void 0 ? void 0 : _this$backend11.storeClientOptions(msg.args[0]);\n          break;\n        case \"saveToDeviceBatches\":\n          prom = (_this$backend12 = this.backend) === null || _this$backend12 === void 0 ? void 0 : _this$backend12.saveToDeviceBatches(msg.args[0]);\n          break;\n        case \"getOldestToDeviceBatch\":\n          prom = (_this$backend13 = this.backend) === null || _this$backend13 === void 0 ? void 0 : _this$backend13.getOldestToDeviceBatch();\n          break;\n        case \"removeToDeviceBatch\":\n          prom = (_this$backend14 = this.backend) === null || _this$backend14 === void 0 ? void 0 : _this$backend14.removeToDeviceBatch(msg.args[0]);\n          break;\n      }\n      if (prom === undefined) {\n        this.postMessage({\n          command: \"cmd_fail\",\n          seq: msg.seq,\n          // Can't be an Error because they're not structured cloneable\n          error: \"Unrecognised command\"\n        });\n        return;\n      }\n      prom.then(ret => {\n        this.postMessage.call(null, {\n          command: \"cmd_success\",\n          seq: msg.seq,\n          result: ret\n        });\n      }, err => {\n        logger.error(\"Error running command: \" + msg.command, err);\n        this.postMessage.call(null, {\n          command: \"cmd_fail\",\n          seq: msg.seq,\n          // Just send a string because Error objects aren't cloneable\n          error: {\n            message: err.message,\n            name: err.name\n          }\n        });\n      });\n    });\n  }\n}\n//# sourceMappingURL=indexeddb-store-worker.js.map","/*\nCopyright 2022-2024 New Vector Ltd.\n\nSPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial\nPlease see LICENSE in the repository root for full details.\n*/\n\nimport { IndexedDBStoreWorker } from \"matrix-js-sdk/lib/indexeddb-worker\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst remoteWorker = new IndexedDBStoreWorker((self as any).postMessage);\n\nself.onmessage = remoteWorker.onMessage;\n"],"names":["_typeof","o","toPrimitive","t","r","e","i","toPropertyKey","_defineProperty","asyncGeneratorStep","n","c","u","_asyncToGenerator","_next","_throw","root","definition","module","this","noop","undefinedType","isIE","logMethods","_loggersByName","defaultLogger","bindMethod","obj","methodName","method","traceForIE","realMethod","replaceLoggingMethods","level","enableLoggingWhenConsoleArrives","defaultMethodFactory","_level","_loggerName","Logger","name","factory","self","inheritedLevel","defaultLevel","userLevel","storageKey","persistLevelIfPossible","levelNum","levelName","getPersistedLevel","storedLevel","cookie","cookieName","location","clearPersistedLevel","normalizeLevel","input","persist","childName","initialLevel","logger","_log","DEFAULT_NAMESPACE","loglevel","logLevel","loggerName","_len","args","_key","supportedByConsole","getPrefixedLogger","prefix","prefixLogger","childPrefix","childLogger","LogSpan","parent","_len2","msg","_key2","_len3","_key3","_len4","_key4","_len5","_key5","_len6","_key6","data","require$$0","escapeRegexp","str","REPLACE_RE","replace_fn","match","unhomoglyph","getDefaultExportFromCjs","unhomoglyphExports","objectToString","isError","value","errorMessages","isNetworkError","error","message","stack","validateRetries","retries","validateNumberOption","min","allowInfinity","createRetryContext","options","retriesLeft","attemptNumber","random","timeout","normalizedError","AbortError","context","currentTime","startTime","maxRetryTime","delayTime","calculateDelay","timeLeft","finalDelay","resolve","reject","onAbort","timeoutToken","resolvedMaxRetryTime","result","onAttemptFailure","NamespacedValue$1","stable","unstable","names","altName","val","arr","included","ServerControlledNamespacedValue","preferUnstable","UnstableValue","M_ASSET","M_TIMESTAMP","M_LOCATION","ReceiptType","MAIN_ROOM_TIMELINE","ownKeys$i","interns","internaliseString","encodeParams","searchParams","urlSearchParams","_loop","key","v","params","replaceParam","dict","_objectSpread$i","encodeUri","pathTemplate","variables","array","fn","reverse","checkObjectHasKeys","keys","deepCopy","deepCompare","x","y","p","_p","pairs","k","a","b","lexicographicCompare","isNumber","removeHiddenCharsRegex","removeDirectionOverrideChars","normalize","removeHiddenChars","escapeRegExp","string","globToRegexp","glob","ensureNoTrailingSlash","url","ms","logDuration","_x","_x2","_x3","_logDuration","block","start","end","logDurationSync","isNullOrUndefined","promiseMapSeries","_x4","_x5","_promiseMapSeries","promises","promiseTry","simpleRetryOperation","promiseFn","shouldRetry","pRetry","attempt","_ref","DEFAULT_ALPHABET","alphabetPad","s","alphabet","baseToString","len","_alphabet","d","stringToBase","charIndex","j","averageBetweenStrings","padN","baseA","avg","baseB","nextString","prevString","recursivelyAssign","target","source","ignoreNullish","sourceKey","sourceValue","safeSet","getContentTimestampWithFallback","_M_TIMESTAMP$findIn","sortEventsByLatestContentTimestamp","left","right","isSupportedReceiptType","receiptType","mapsEqual","eq","v1","v2","processMapToObjectValue","recursiveMapToObject","map","targetMap","unsafeProp","prop","noUnsafeEventProps","event","createDefault","hasRequiredNamespacedMap","NamespacedMap_1","NamespacedMap","_createForOfIteratorHelper","it","_unsupportedIterableToArray","allowArrayLike","F","_e","normalCompletion","didErr","err","step","_e2","minLen","_arrayLikeToArray","arr2","_classCallCheck","instance","Constructor","_defineProperties","props","descriptor","_createClass","protoProps","staticProps","initial","_step","_iterator","hasRequiredInvalidEventError","InvalidEventError_1","InvalidEventError","_inherits","subClass","superClass","_setPrototypeOf","_createSuper","Derived","hasNativeReflectConstruct","_isNativeReflectConstruct","Super","_getPrototypeOf","NewTarget","_possibleConstructorReturn","call","_assertThisInitialized","_wrapNativeSuper","Class","_cache","_isNativeFunction","Wrapper","_construct","Parent","_super","hasRequiredExtensibleEvent","ExtensibleEvent_1","ExtensibleEvent","ExtensibleEvent$1","wireFormat","hasRequiredTypes","types","isProvided","isOptionalAString","hasRequiredNamespacedValue","NamespacedValue_1","NamespacedValue","_NamespacedValue","_this","hasRequiredMessage_types","message_types","requireNamespacedValue","M_MESSAGE","M_TEXT","M_HTML","M_EMOTE","M_NOTICE","hasRequiredEvents$1","events","events$1","isEventTypeSame","given","expected","givenNs","expectedNs","hasRequiredMessageEvent","MessageEvent_1","MessageEvent","_ExtensibleEvent2","require$$1","_types","requireTypes","require$$2","_InvalidEventError","require$$3","_message_types","require$$4","requireEvents$1","ownKeys","object","enumerableOnly","symbols","sym","_objectSpread","_ExtensibleEvent","mmessage","mtext","mhtml","text","html","primaryEventType","_events","mime","messageRendering","_this$html","_content","hasRequiredNoticeEvent","NoticeEvent_1","NoticeEvent","_MessageEvent2","_get","property","_superPropBase","base","desc","receiver","_MessageEvent","hasRequiredEmoteEvent","EmoteEvent_1","EmoteEvent","hasRequiredMRoomMessage","MRoomMessage","_NoticeEvent","_EmoteEvent","requireEmoteEvent","requireMessage_types","LEGACY_M_ROOM_MESSAGE","_wireEvent$content","_wireEvent$content2","_wireEvent$content3","wireEvent","msgtype","_objectSpread2","_objectSpread3","_objectSpread4","hasRequiredMMessage","MMessage","requireMessageEvent","requireNoticeEvent","hasRequiredPoll_types","poll_types","M_POLL_KIND_DISCLOSED","M_POLL_KIND_UNDISCLOSED","M_POLL_START","M_POLL_RESPONSE","M_POLL_END","hasRequiredPollStartEvent","PollStartEvent_1","PollStartEvent","_poll_types","requirePoll_types","require$$5","require$$6","requireExtensibleEvent","_toConsumableArray","_arrayWithoutHoles","_iterableToArray","_nonIterableSpread","iter","PollAnswerSubevent","id","_super2","_this2","poll","answers","_content2","_content3","question","kind","makeId","LETTERS","hasRequiredRelationship_types","relationship_types","REFERENCE_RELATION","hasRequiredPollResponseEvent","PollResponseEvent_1","PollResponseEvent","requireInvalidEventError","_relationship_types","rel","response","pa","pollEventId","hasRequiredPollEndEvent","PollEndEvent_1","PollEndEvent","hasRequiredMPoll","MPoll","_PollStartEvent","requirePollStartEvent","_PollResponseEvent","_PollEndEvent","requirePollEndEvent","hasRequiredExtensibleEvents","ExtensibleEvents_1","ExtensibleEvents","_NamespacedMap","requireNamespacedMap","_MRoomMessage","_MMessage","requireMMessage","_MPoll","requireMPoll","ExtensibleEvents$1","_this$_unknownInterpr","wireEventType","interpreter","tryType","hasRequiredIPartialEvent","IPartialEvent","hasRequiredMessageMatchers","MessageMatchers","LegacyMsgType","content","exports","_ExtensibleEvents","requireExtensibleEvents","_IPartialEvent","requireIPartialEvent","_MessageMatchers","requireMessageMatchers","requireMRoomMessage","requireRelationship_types","requirePollResponseEvent","libExports$1","requireLib$1","EventType","RelationType","MsgType","RoomCreateTypeField","RoomType","ToDeviceMessageId","UNSTABLE_MSC3088_PURPOSE","UNSTABLE_MSC3088_ENABLED","UNSTABLE_MSC3089_TREE_SUBTYPE","UNSTABLE_MSC3089_LEAF","UNSTABLE_MSC3089_BRANCH","UNSTABLE_MSC2716_MARKER","MSC3912_RELATION_BASED_REDACTIONS_PROP","UNSTABLE_ELEMENT_FUNCTIONAL_USERS","EVENT_VISIBILITY_CHANGE_TYPE","PUSHER_ENABLED","LOCAL_NOTIFICATION_SETTINGS_PREFIX","UNSIGNED_THREAD_ID_FIELD","UNSIGNED_MEMBERSHIP_FIELD","_objectWithoutPropertiesLoose","_objectWithoutProperties","hasRequiredEvents","R","ReflectApply","ReflectOwnKeys","ProcessEmitWarning","warning","NumberIsNaN","EventEmitter","eventsModule","once","defaultMaxListeners","checkListener","listener","arg","_getMaxListeners","that","type","doError","er","handler","listeners","arrayClone","_addListener","prepend","m","existing","w","onceWrapper","state","wrapped","_onceWrap","list","position","originalListener","unwrap","evlistener","emitter","listenerCount","copy","spliceOne","index","unwrapListeners","ret","errorListener","resolver","addErrorHandlerIfEventEmitter","flags","eventTargetAgnosticAddListener","wrapListener","eventsExports","requireEvents","EventEmitterEvents","TypedEventEmitter","_arguments","UserEvent","User","userId","client","user","firstFire","eventsToFire","eventToFire","oldName","oldUrl","serverNameRegex","validateServerName","matches","serverName","mediaIdRegex","validateMediaId","mediaId","getHttpUriForMxc","baseUrl","mxc","width","height","resizeMethod","allowDirectLinks","allowRedirects","rest","isThumbnailRequest","useAuthentication","verb","KnownMembership","RoomMemberEvent","RoomMember","roomId","_event$getDirectional","_event$getDirectional2","displayName","oldMembership","logger$2","calculateDisplayName","powerLevel","powerLevelEvent","oldPowerLevel","oldTyping","typingList","memberEvent","memberContent","inviteSender","allowDefault","rawUrl","httpUrl","MXID_PATTERN","LTR_RTL_PATTERN","shouldDisambiguate","selfUserId","roomState","strippedDisplayName","userIds","disambiguate","Preset","JoinRule","GuestAccess","HistoryVisibility","M_TOPIC","makeHtmlMessage","body","htmlBody","makeHtmlNotice","makeHtmlEmote","makeTextMessage","makeNotice","makeEmoteMessage","makeTopicContent","topic","htmlTopic","renderings","parseBeaconInfoContent","description","live","timestamp","asset","parseBeaconContent","_M_TIMESTAMP$findIn2","BeaconEvent","isTimestampInDuration","startTimestamp","durationMs","getBeaconInfoIdentifier","rootEvent","beaconInfoEvent","expiryInMs","beaconLocationEvents","_validLocationEvents$","parsed","latestLocationEvent","validLocationEvents","prevLiveness","ReEmitter","eventNames","reEmittersByEvent","eventName","forSource","TypedReEmitter","M_BEACON","PRE_HYDRA_ROOM_VERSIONS","shouldUseHydraForRoomVersion","roomVersion","OobStatus","RoomStateEvent","RoomState","oobMemberFlags","_createEvent$getConte","createEvent","count","excludedIds","sentinel","member","eventType","stateKey","_this$liveBeaconIds","status","eventsByStateKey","_copy$getMember","unknownStateEvents","stateEvents","M_BEACON_INFO","lastStateEvent","_event$getContent$dis","members","creators","getCreators","oldLastModified","pl","powerLevelForUserId","markerFoundOptions","matrixClient","beacon","processBeaconRelation","beaconInfoEventId","beaconByEventIdDict","_event$getRelation","relatedToEventId","MatrixEventEvent","_ret","beaconIdentifier","_event$getRedactionEv","_beacon","Beacon","_this$events$get$get","_this$events$get","pwrLvlEvent","stateEvent","existingMember","token","_this$displayNameToUs","mxEvent","canRedact","action","powerLevelsEvent","powerLevels","requiredLevel","stateEventType","cli","_roomMember$powerLeve","eventsLevels","stateDefault","eventsDefault","roomMember","userPowerLevel","notifLevelKey","notifLevel","_joinRuleEvent$getCon","joinRuleEvent","joinRuleContent","_historyVisibilityEve","historyVisibilityEvent","historyVisibilityContent","_guestAccessEvent$get","guestAccessEvent","guestAccessContent","msc3946ProcessDynamicPredecessor","predecessorEvent","_roomId","eventId","viaServers","predecessor","_eventId","_roomId2","threePidInvite","strippedOldName","existingUserIds","filteredUserIDs","strippedDisplayname","_this$displayNameToUs2","roomCreateEvent","roomCreateSender","additionalCreators","evContent","users","Direction","EventTimeline","stateContext","toStartOfTimeline","eventTimelineSet","_eventTimelineSet$roo2","_eventTimelineSet$roo","_this$startState","_this$endState","timelineWasEmpty","direction","timeline","forkState","neighbour","addToState","timelineSet","_roomState","insertIndex","ev","RelationsEvent","matchesEventType","targetEventType","altTargetEventTypes","Relations","relationType","altEventTypes","EventStatus","redactedEvent","lastReplacement","relation","_this3","eventsForKey","bEvents","sender","eventsFromSender","_event$getRelation2","aEvents","_this4","replaceRelation","minTs","last","_this5","replacement","RelationsContainer","room","_this$relations$get","parentEventId","_this$relations$get2","relationsForEvent","relationsRecord","relations","relationsWithRelType","relationsWithEventType","onEventDecrypted","relatesToEventId","_timelineSet$findEven","_room","_this$room","relatesToEvent","debuglog$2","DuplicateStrategy","EventTimelineSet","_this$room$relations","_room$client","opts","threadListType","filter","newEventId","oldEventId","existingTimeline","backPaginationToken","forwardPaginationToken","resetAllTimelines","oldTimeline","newTimeline","res","tl","inverseDirection","didUpdate","lastEventWasNew","debuglog","existingIsLive","timelineIsLive","backwardsIsLive","forwardsIsLive","paginationToken","duplicateStrategy","fromCache","tlEvents","_ref2","_this$thread","_this$thread2","eventDebugString","_this$thread3","_this$thread4","timelineEvents","parentIndex","parentEvent","nextEvent","localEvent","removed","RoomEvent","eventId1","eventId2","timeline1","timeline2","idx1","idx2","idx","evId","difference","threadId","shouldLiveInRoom","shouldLiveInThread","_this$room2","RoomSummary","info","UNREAD_THREAD_NOTIFICATIONS","matchesWildcard","actualValue","filterValue","typePrefix","FilterComponent","filterJson","_event$getUnsigned","_bundledRelationships","bundledRelationships","THREAD_RELATION_TYPE","FILTER_RELATED_BY_SENDERS","FILTER_RELATED_BY_REL_TYPES","containsUrl","relationTypes","relationSenders","literalKeys","matchFunc","notName","disallowedValues","allowedValues","containsUrlFilter","relationTypesFilter","relationSendersFilter","values","ownKeys$h","_objectSpread$h","setProp","keyNesting","currentObj","nestedKeys","Filter","jsonObj","filterId","roomFilterJson","roomFilterFields","limit","_this$definition","_this$definition2","enabled","includeLeave","_objectSpread$g","ownKeys$g","synthesizeReceipt","MatrixEvent","unthreaded","threadIdForReceipt","ReceiptPairRealIndex","ReadReceipt","MapWithDefault","_this$receipts$get$ge","_this$receipts$get","ignoreSynthesized","syntheticReceipt","realReceipt","_this$getUnfilteredTi","latestReceipt","_receipt$data","receipt","eventIsInMainTimeline","inMainTimelineForReceipt","privateReadReceipt","comparison","publicReadReceipt","synthetic","_pair$ReceiptPairSynt2","_pair$ReceiptPairSynt3","receiptTypesMap","pair","_pair$ReceiptPairSynt","existingReceipt","ReceiptPairSyntheticIndex","_ordering","wrappedReceipt","ordering","preferSynthetic","cachedReceipt","newCachedReceipt","previousEventId","lastEvent","NotificationCountType","PollEvent","filterResponseRelations","relationEvents","pollEndTimestamp","responseEvents","undecryptableEventIds","previousCount","_this$endEvent","_this$endEvent2","allRelations","responses","pollEndEvent","pollCloseTimestamp","_this2$endEvent","_allRelations$nextBat","_this$endEvent3","_this$responses","endEvent","roomCurrentState","endEventSender","isPollEvent","danglingReceipts","danglingReceipt","ThreadedReceipts","ReceiptsByUser","DanglingReceipts","receiptContent","eventReceipt","_receiptType","receiptsByUser","_userId","_receipt","referencedEvent","DanglingReceipt","threaded","_this$room$getThread","ReceiptInfo","ts","receiptInfo","isAfterOrSame","userReceipts","getOrCreate","isAfter","_this$data$get","_this$data$get2","createFn","found","created","leftEventId","rightEventId","leftEvent","rightEvent","isLeftEventInMainTimeline","isRightEventInMainTimeline","compareEventsInMainTimeline","compareEventsInThreads","compareSameTimeline","leftTimeline","rightTimeline","guessOrderBasedOnTimestamp","leftEventThreadId","rightEventThreadId","leftThread","leftTs","rightTs","Method","ownKeys$f","_objectSpread$f","HTTPError","httpStatus","httpHeaders","_this$httpHeaders","retryAfter","date","MatrixError","errorJson","headerValue","_this$httpStatus","_this$url","_this$errcode","_this$data$error","headers","defaultMs","_error$getRetryAfterM","cause","_cause$message","_cause$message2","MatrixSafetyErrorCode","MatrixSafetyError","HttpApiEvent","hasRequiredContentType","PARAM_REGEXP","TOKEN_REGEXP","QESC_REGEXP","QUOTE_REGEXP","TYPE_REGEXP","contentType","parse","format","parameters","param","qstring","header","ContentType","TEXT_REGEXP","contentTypeExports","requireContentType","timeoutSignal","controller","anySignal","signals","signal","cleanup","parseErrorResponse","_contentType","_contentType2","isXhr","colonIdx","getResponseContentType","errorBody","parseContentType","retryNetworkOperation","_retryNetworkOperation","maxAttempts","callback","attempts","lastConnectionError","sleep","ConnectionError","calculateRetryBackoff","retryConnectionError","TokenRefreshOutcome","REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS","REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS","TokenRefresher","expiresIn","snapshot","_this4$tokenRefreshPr","_this5$opts$logger","_this5$opts$logger2","_this5$opts$logger3","accessToken","refreshToken","expiry","_this5$opts$logger5","_this5$opts$logger4","_objectSpread$e","ownKeys$e","eventEmitter","_opts$useAuthorizatio","resource","queryParams","fullUri","path","paramOpts","requestSnapshot","outcome","TokenRefreshError","_arguments2","_this2$opts$logger","_opts$localTimeoutMs","_opts$keepAlive","_body$constructor","urlForLogs","jsonResponse","keepAlive","cacheMode","_this2$opts$logger2","_this2$opts$logger3","asUrl","sanitizedQsString","sanitizedQs","sanitizedQsUrlPiece","baseUrlWithFallback","baseUrlWithoutTrailingSlash","mergedParams","ClientPrefix","IdentityPrefix","MediaPrefix","TIMER_CHECK_PERIOD_MS","realCallbackKey","callbackList","debuglog$1","setTimeout$1","func","delayMs","runAt","binarySearch","el","scheduleRealCallback","clearTimeout$1","cb","first","runCallbacks","callbacksToRun","_cb","max","mid","MatrixHttpApi","FetchHttpApi","file","_opts$includeFilename","_opts$abortController","_opts$name","abortController","_opts$type","fileName","upload","xhr","timeoutFn","timeoutTimer","callbacks.clearTimeout","uploadResolvers","callbacks.setTimeout","_opts$progressHandler","includeFilename","removeElement","elem","promise","CAPABILITIES_CACHE_MS","CAPABILITIES_RETRY_MS","RoomVersionStability","ServerCapabilities","http","resp","howLong","logger$1","RoomStickyEventsEvent","assertIsUserId","RoomStickyEventsStore","removedEvents","innerEvents","_this$stickyEventsMap","innerMapKey","currentEvent","now","previousEvents","eventA","eventB","_eventB$getId","_eventA$getId","stickyKey","innerMap","_this$stickyEventsMap2","_this$stickyEventsMap3","_this$stickyEventsMap5","stickyEvent","currentEventSet","_this$stickyEventsMap4","added","updated","ex","_innerMap$get","_this$stickyEventsMap6","mapKey","redactEventId","newEvents","_innerMap","_currentEvent","_objectSpread$d","ownKeys$d","KNOWN_SAFE_ROOM_VERSION","SAFE_ROOM_VERSIONS","MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH","Room","myUserId","RoomReceipts","thread","recreateEvent","_this$threadsTimeline","_this$threadsTimeline2","Thread","redactId","membership","redactEvents","toRedact","PendingEventOrdering","mapper","serializedEvent","_this2$client","ThreadFilterType","timelineSets","readReceiptEventId","readReceiptTimelineIndex","matrixEvent","decryptionPromises","_createEvent$getSende","capabilities","versionCap","safeVer","currentVersion","stableVersions","_this$pendingEventLis","_this$pendingEventLis2","_this$pendingEventLis3","_this$pendingEventLis4","_lastRoomEvent$getTs","_lastThreadEvent$getT","roomEvents","lastRoomEvent","lastThread","lastThreadEvent","_threadEvent$getTs","_lastThreadEvent$getT2","threadEvent","_this$selfMembership","me","memberCount","_this$heroes","inviterId","anyMember","mFunctionalMembers","functionalMembers","nonFunctionalMemberCount","nonFunctionalHeroes","_this$heroes2","h","hasHeroes","hero","heroMember","availableMember","nonFunctionalMembers","_availableMember","availableUser","_member","prevMembership","_this6","lastSyncToken","_this7","fromServer","rawMembersEvents","memberEvents","inMemoryUpdate","oobMembers","_m$events$member","store","_this8","liveTimelineBefore","_this9","backwardPaginationToken","mostRecentEventInTimeline","liveTimeline","previousCurrentState","previousOldState","threadIds","hasUnthreadedReceipt","utils.isSupportedReceiptType","userReceipt","receiptGroup","singleReceipt","typedSingleReceipt","_this$getThread","maxHistory","_event","pushActions","highlightCount","threads","threadNotification","_threadNotification$t","isThreadEvent","_this$threadNotificat2","_notification$total","_notification$highlig","notification","_this$threadNotificat3","_this$threadNotificat4","_threadNotification$h","_threadNotification$t2","exceptThreadIds","isEncrypted","notifs","bumpStamp","summary","_summary$mHeroes","joinedCount","invitedCount","heroes","mainUrl","_this$currentState$ge","_this$currentState$ge2","canonicalAlias","_this$currentState$ge3","altAliases","alias","_this$threads$get","_this0","_ev$getContent","prepopulateTimeline","pendingEvents","unfilteredLiveTimeline","useSyncEvents","livePaginationToken","_this1","filterType","_this10","_ref3","currentUserParticipated","_this11","threadRoots","threadAMetadata","threadBMetadata","latestMyThreadsRootEvent","_this11$threadsTimeli","_opts","threadRelationship","_this11$threadsTimeli2","ThreadEvent","_this12","_this13","maybeDecryptedEvent","relationEventId","_poll","_this14","matrixEvents","_timeline$getEvents","roomEvent","_this$client","roots","isThreadRelation","threadRootId","_this$findEventById","_this$findEventById2","_eventsByThread","eventsByThread","threadEvents","_ref4","_this$cachedThreadRea","relatedEvents","redactionEvent","currentStateEvent","txnId","tid","unsigned","addLiveEventOptions","isEventEncrypted","isRoomEncrypted","remoteEvent","oldStatus","newStatus","remoteTxnId","ALLOWED_TRANSITIONS","allowed","removedEvent","_this15","_eventsByThread$threa","existingEvent","neighbouringEvents","_ref5","ROOM","THREAD","UNKNOWN_RELATION","memo","_receipt$thread_id","_this$unthreadedRecei","_this$unthreadedRecei2","receiptForMainTimeline","receiptDestination","_this$cachedThreadRea2","eventIds","removedAny","membershipEvent","strippedStateEvents","strippedEvent","canInvite","currentState","RoomNameType","memberNamesToRoomName","ignoreRoomNameEvent","_this$currentState$ge4","joinedMemberCount","invitedMemberCount","inviteJoinCount","excludedUserIds","otherNames","otherMembers","_ref6","collator","myMembership","thirdPartyInvites","thirdPartyNames","leftNames","visibilityChange","isPowerSufficient","visibilityEventsOnOriginalEvent","originalEvent","originalEventId","change","newEvent","newVisibility","visibilityEvents","visibilityEvent","unreadThreads","_this$getLiveTimeline","countWithoutMe","plural","ServerSupport","Feature","featureSupportResolver","buildFeatureSupportMap","_buildFeatureSupportMap","versions","feature","supportCondition","_versions$versions$in","_versions$versions","_supportCondition$uns","_supportCondition$uns2","supportUnstablePrefixes","unstablePrefix","_versions$unstable_fe","supportMatrixVersion","supportMap","_objectSpread$c","ownKeys$c","BUFFER_PERIOD_MS","FAILED_SYNC_ERROR_THRESHOLD$1","SyncState","MSC2716_ROOM_VERSIONS","getFilterName","suffix","SetPresence","defaultClientOpts","defaultSyncApiOpts","syncOpts","SyncApi","_createAndReEmitRoom","markerEvent","isValidMsc2716Event","localTimeoutMs","qps","leaveRooms","_data$rooms","rooms","leaveObj","ClientEvent","_this$_peekRoom","_this$_peekRoom2","oldStateEvents","messages","presenceEvent","peekRoom","_this$abortController","_this$syncStateData","savedSyncPromise","keepaliveProm","_globalThis$window$ad","_globalThis$window","tok","savedSync","firstSyncFilter","savedSyncToken","savedSyncTokenPromise","initialFilter","_globalThis$window2","_globalThis$window2$r","_this$abortController2","nextSyncToken","syncEventData","syncOptions","syncToken","abort","_this$abortController3","presence","keepAlivePromise","connDidFail","_data$presence","_data$account_data","accountDataEvent","rules","prevEventsMap","prevEvent","toDeviceMessages","receivedToDeviceMessages","rawEvent","processToDeviceMessages","inviteRooms","joinRooms","knockRooms","_ref7","inviteObj","_ref8","joinObj","_joinObj$UNREAD_THREA","stateAfterEvents","ephemeralEvents","stickyEvents","eventsFormingFinalState","encrypted","_joinObj$unread_notif","_joinObj$unread_notif2","unreadThreadNotifications","unreadNotification","_unreadNotification$n","hasNoNotifications","_unreadNotification$h","limited","_syncEventData$oldSyn","accountDataEvents","stickyEventsAndStickyEventsFromTheTimeline","emitEvent","timelineEvent","_ref9","_ref0","knockObj","_x6","_client$getNotifTimel","_this9$syncOpts$crypt","_data$device_unused_f","delay","_this$abortController4","success","isBrandNewRoom","decrypt","inviteEvent","wrappedRoom","stateEventList","stateAfterEventList","timelineEventList","eitherStateEventList","_pushActions$tweaks","newState","old","timelineSupport","_client$getUser","cancelledKeyVerificationTxns","processedMessage","processedEvent","toDeviceEvent","deprecatedCompatibilityEvent","StubStore","creator","toStart","filterName","syncData","membershipEvents","batch","byteToHex","unsafeStringify","offset","getRandomValues","rnds8","rng","native","randomUUID","_v4","buf","rnds","v4","grammar","grammar$1","objs","hasRequiredParser","toIntIfInt","attachProperties","rawName","parseReg","needsBlank","keyLocation","sdp","session","validLine","l","media","acc","expr","candidates","parts","item","paramReducer","stream","scid","paused","hasRequiredWriter","writer","requireGrammar","formatRegExp","formatStr","makeLine","mLine","outerOrder","defaultOuterOrder","innerOrder","hasRequiredLib","lib","parser","requireParser","libExports","requireLib","toBase64","uint8Array","base64","current","encodeBase64","encodeUnpaddedBase64","encodeUnpaddedBase64Url","fromBase64","decodeBase64","LOWERCASE","UPPERCASE","secureRandomString","secureRandomStringFrom","chars","randomValueCutoff","entropyBuffer","entropyBufferPos","randomByte","SDPStreamMetadataKey","SDPStreamMetadataPurpose","refCount","audioContext","releaseContext","_audioContext","POLLING_INTERVAL","SPEAKING_SAMPLE_COUNT","CallFeedEvent","SPEAKING_THRESHOLD","CallState","maxVolume","volume","_volume","newSpeaking","CallEvent","connected","oldStream","newStream","wasMeasuringVolumeActivity","acquireContext","mediaStreamAudioSourceNode","_callRoom$getMember","callRoom","audioMuted","videoMuted","threshold","mediaHandler","CallFeed","_this$call","_this$stream","localVolume","RING_GRACE_PERIOD","CallEventHandlerEvent","CallEventHandler","currentEventBuffer","nextSeq","buffer","callId","_buffer","eventBuffer","callEvents","ignoreCallIds","_eventType","_getGroupCallById","callRoomId","groupCallId","senderId","opponentDeviceId","groupCall","GroupCallEvent","GroupCallUnknownDeviceError","weSentTheEvent","_this2$client$getTurn","_createNewMatrixCall","_groupCall","timeUntilTurnCresExpire","createNewMatrixCall","stats","CallError","GroupCallErrorCode","_groupCall2","_call$getOpponentMemb","isCalling","thisCall","CallDirection","existingCall","CallErrorCode","_createNewMatrixCall2","GroupCallEventHandlerEvent","GroupCallEventHandler","currentGroupCall","onSync","deferred","resolveFunc","callEvent","sortedCallEvents","GroupCallType","callType","GroupCallIntent","callIntent","isPtt","dataChannelOptions","ordered","maxPacketLifeTime","maxRetransmits","protocol","GroupCall","ConnectionStatsBuilder","availableIncomingBitrate","availableOutgoingBitrate","TransportStatsBuilder","conferenceStatsTransport","isFocus","remoteUsedCandidate","report","localUsedCandidate","remoteIpAddress","remotePort","ip","localIpAddress","localPort","localIp","MediaSsrcHandler","ssrc","ssrcs","_m$ssrcs","ssrcToMid","MediaTrackHandler","pc","isNotNullAndKind","track","trackId","transceiver","_transceiver$sender","_transceiver$receiver","MediaTrackStats","loss","resolution","framerate","bitrate","codecShortType","isAlive","isMuted","isEnabled","jitter","concealedAudioDuration","totalAudioDuration","MediaTrackStatsHandler","mediaSsrcHandler","mediaTrackHandler","trackID","trackStats","localVideoTracks","ValueFormatter","imput","TrackStatsBuilder","frameRate","before","layer","timeMs","numberOfFramesSinceBefore","codec","packetsNow","packetsBefore","packetsDiff","packetsLostNow","packetsLostBefore","packetsLostDiff","bytesNowAny","bytesBeforeAny","nowTimestamp","bytesNow","bytesBefore","bytesProcessed","beforeTimestamp","bitrateKbps","trackStatsList","videoTrackSummary","audioTrackSummary","remoteTrackList","audioTrackList","trackSummary","_stats$getAudioConcea","_stats$getAudioConcea2","statsReport","jitterStr","msPerSample","ConnectionStatsReportBuilder","bitrateDownload","bitrateUpload","resolutions","framerates","codecs","audioConcealment","audioBitrateDownload","audioBitrateUpload","videoBitrateDownload","videoBitrateUpload","totalConcealedAudio","lostPackets","audioConcealmentForTrack","totalPackets","opponentMemberId","rtpTransceivers","_t$sender","CallFeedStatsReporter","callFeeds","_track$getSettings","label","settingDeviceId","constrainDeviceId","_track$getConstraints","feed","audioTracks","videoTracks","audio","feedStats","video","_objectSpread$b","ownKeys$b","CallStatsReportGatherer","ConnectionStats","localUserId","statsPromise","_this$connectionStats","_this$connectionStats2","byteSentStatsReport","_this$currentStatsRep","_trackStats","isActive","StatsReport","StatsReportEmitter","byteSentStats","SummaryStatsReportGatherer","allSummary","summaryTotalCount","peerConnectionsCount","summaryCounter","maxJitter","maxPacketLoss","decimalPlaces","callParticipants","devices","userEntry","device","counter","hasReceivedAudio","hasReceivedVideo","GroupCallStats","interval","peerConnection","opponentMember","_this$getStatsReportG","ownKeys$a","_objectSpread$a","GroupCallTerminationReason","GroupCallStatsReportEvent","GroupCallError","code","GroupCallState","DEVICE_TIMEOUT","getCallUserId","intent","dataChannelsEnabled","isCallWithoutVideoAndAudio","_room$currentState$ge","_room$currentState$ge2","livekitServiceURL","useLivekit","f","newCall","_newCall$getOpponentM","_this$calls$get","opponentUserId","deviceMap","prevCall","feeds","setTracksEnabled","participantMap","callMap","retriesMap","deviceId","participant","_retriesMap$get","_retriesMap","needsRetry","currentUserMediaFeed","remoteUsermediaFeed","remoteFeedChanged","currentCallForUserDevice","currentScreenshareFeed","remoteScreensharingFeed","remoteScreenshareFeedChanged","_oldState","_call$getOpponentMemb2","_call$getOpponentMemb3","nextActiveSpeaker","callFeed","total","topAvg","oldState","genCallID","groupCallState","newURL","prevValue","deviceMapsEqual","participantStateEqual","_this$participants$ge","_this$participants$ge2","_this$participants$ge3","vidShouldBeMuted","micShouldBeMuted","_this$stats","emitStateEvent","existingStateEvent","muted","sendUpdatesBefore","_call$localUsermediaF","sendUpdates","updates","hasPermission","onTrackEnded","localDeviceId","_loop2","_userId2","_this10$calls$get","_loop3","callsChanged","onCallFeedsChanged","onCallStateChanged","onCallHangup","onCallReplaced","hangupReason","usermediaFeed","screenshareFeed","existingFeed","replacementFeed","feedIndex","localMember","participants","entered","nextExpiration","calls","validDevices","_deviceMap","_arguments3","_event$getContent","otherCalls","newDevices","newCalls","newContent","myDevices","userID","ownKeys$9","r2","_objectSpread$9","CallState2","CallType","CallType2","CallDirection2","CallParty","CallParty2","CallEvent2","CallErrorCode2","VOIP_PROTO_VERSION","FALLBACK_ICE_SERVER","CALL_TIMEOUT_MS","CALL_LENGTH_INTERVAL","ICE_DISCONNECTED_TIMEOUT","getCodecParamMods","mods","getTransceiverKey","purpose","MatrixCall","_opts$forceTURN","_this$peerConn","_this$peerConn2","_this$peerConn3","_this$peerConn$iceCon","_this$peerConn4","_this$peerConn5","_this$peerConn8","_this$peerConn6","_this$peerConn7","_this$peerConn9","_this$peerConn1","_this$peerConn0","_this$peerConn10","onRemoveTrack","shouldTerminate","server","dataChannel","_this$localUsermediaS","_feed$stream","_this$localUsermediaS2","_feed$stream2","_this$transceivers$ge","_this$transceivers$ge2","_this$localUsermediaF","_this$localScreenshar","_this$remoteUsermedia","_this$remoteScreensha","streamId","_this4$getOpponentMem","updateStreamIds","metadata","localFeed","_this$feeds$find","oldRemoteStream","addToPeerConnection","tKey","newSender","newTransceiver","audioTransceiverKey","videoTransceiverKey","transceiverKey","invite","haveTurnCreds","sdpStreamMetadata","_this8$feeds$find","remoteStream","ringingTimer","_this8$stats","onState","wantedValue","valueOfTheOtherSide","prevState","answerWithVideo","_this9$client$getDevi","answerWithAudio","suppressEvent","reason","getAudio","getVideo","audioTransceiver","videoTransceiver","_this10$transceivers$","track2","_this10$localUsermedi","_track","_sender","_this10$transceivers$2","forceAudio","forceVideo","videoEnabled","audioEnabled","_track2","_track3","oldSender","_this12$localUsermedi2","_this12$localUsermedi","_this$localUsermediaF2","_this$localUsermediaF3","_this13$localUsermedi","_this$localUsermediaF4","_this$localUsermediaF5","onHold","callOnHold","trackOnHold","digit","_sender$track","requestScreenshareFeed","answerContent","discardCount","codecToPayloadTypeMap","rtp","payloadTypeToCodecMap","mod","extraConfig","fmtp","_this16","offer","_this17","answer","_this18","_this19","fromPartyId","bufferedCandidates","_this20","_this21","selectedPartyId","_this22","polite","offerCollision","readyForOffer","prevLocalOnHold","_localDescription","newLocalOnHold","_streamId","_metadata","_this23","_this24","_this25","_localDescription2","_localDescription3","screenshareVideoTransceiver","recvCodecs","sendCodecs","_this26","realContent","_this26$getOpponentMe","toDeviceSeq","_this26$getOpponentMe2","newQueue","candidate","targetUserId","_this27","profileInfo","replacementId","transferTargetCall","_this28","_transferTargetCall$g","_this28$getOpponentMe","targetProfileInfo","transfereeProfileInfo","newCallId","bodyToTransferTarget","bodyToTransferee","hangupParty","shouldEmit","_this29$stats","_this29","_this30","_this31","_this31$client$getDev","_this32","msgPartyId","_getMember","_this$stats2","_this33","_this34","tracks","_window$RTCPeerConnec","supported","optionsForceTURN","PushRuleActionName","TweakName","ConditionKind","PushRuleKind","RuleId","ownKeys$8","RULEKINDS_IN_ORDER","DEFAULT_OVERRIDE_RULES","UserDefinedRules","DEFAULT_UNDERRIDE_RULES","EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS","mergeRulesWithDefaults","incomingRules","defaultRules","orderedRuleIds","incomingDefaultRules","rule","incomingCustomRules","insertDefaultPushRule","ruleId","newRules","nextExpectedRuleIdIndex","ruleIndex","defaultRuleId","PushProcessor","actionList","actionObj","EXPECTED_DEFAULT_OVERRIDE_RULE_IDS","pattern","alignToWordBoundary","cacheKey","toRemoveKeys","ruleset","condition","kindset","rawrule","_objectSpread$8","tprule","cond","ineq","rhs","_room$currentState","pat","regex","_cond","escaped","part","firstPart","currentIndex","thisPart","rulesets","_rule$conditions","actions","_result$rule","scope","_this$client$pushRule","SUPPORTED_MATRIX_VERSIONS","AutoDiscoveryAction","AutoDiscoveryError","AutoDiscovery","wellknown","clientConfig","hsUrl","hsVersions","_hsVersions$raw","hsVersionSet","version","supportedVersionFound","isUrl","failingClientConfig","isResponse","notProps","domain","domainWithProtocol","_response$raw","_parsed","port","saferUrl","fetchFn","_error","SERVICE_TYPES","EventContext","ourEvent","backwards","atStart","SearchResult","eventMapper","jsonContext","eventsBefore","eventsAfter","rank","isSendDelayedEventRequestOpts","UpdateDelayedEventAction","ownKeys$7","eventMapperFor","preventReEmit","plainOldJsObject","_objectSpread$7","bundledEdit","ownKeys$6","_objectSpread$6","MSC3089Branch","indexEvent","directory","_this$indexEvent$getC","nextVersion","locked","encryptedContents","additionalContent","fileEventResponse","fileHistory","childEvent","branch","ownKeys$5","_objectSpread$5","DEFAULT_TREE_POWER_LEVELS_TEMPLATE","TreePermissions","MSC3089TreeSpace","parentEvents","_e$getContent","andSubspaces","role","_pls$events","currentPls","pls","viewLevel","editLevel","adminLevel","_pls$events2","_pls$users","trees","children","child","tree","subdirectories","dir","kickMemberships","isNotUs","_roomA$currentState$g","_roomA$currentState$g2","_roomB$currentState$g","_roomB$currentState$g2","roomA","roomB","createTsA","createTsB","parents","parentRoom","_currentChild$getCont2","movingUp","prev","next","newOrder","ensureBeforeIsSane","startOrder","endOrder","lastOrder","_currentChild$getCont","_currentChild","currentChild","fileContent","fileEventId","branches","_this$room$currentSta","SearchOrderBy","MediaHandlerEvent","audioInput","videoInput","callMediaStreamParams","_call","_stream","_stream2","reusable","shouldRequestAudio","shouldRequestVideo","canReuseStream","_this7$localUserMedia","_this7$localUserMedia2","_this7$localUserMedia3","constraints","settings","mediaStream","_this$localUserMediaS","screenshareConstraints","matchingStream","_stream3","_track4","exactDeviceId","isWebkit","deviceIdKey","audioConstraints","videoConstraints","desktopCapturerSourceId","SlidingSyncState","ExtensionState","SlidingSyncEvent","FAILED_SYNC_ERROR_THRESHOLD","ExtensionE2EE","crypto","isInitial","ExtensionToDevice","cryptoCallbacks","ExtensionAccountData","mapEvents","globalAccountData","ExtensionTyping","processEphemeralEvents","ExtensionReceipts","slidingSync","extensions","ext","roomData","_this$client$getUser","ensureNameEvent","knownEvents","oldEvents","recvEvent","seenKnownEvent","inviteStateEvents","_roomData$prev_batch","processRoomEvent","numLive","liveTimelineEvents","_err","_this$client$getNotif","ephEvents","MatrixScheduler","retryAlgorithm","queueAlgorithm","queueName","waitTimeMs","element","eventResolvers","queue","MAX_BATCH_SIZE","ToDeviceMessageQueue","headBatch","retryDelay","batches","batchWithTxnId","msgmap","contentMap","POLICIES_ACCOUNT_EVENT_TYPE","IGNORE_INVITES_ACCOUNT_EVENT_KEY","PolicyRecommendation","PolicyScope","scopeToEventTypeMap","IgnoredInvites","entity","sources","ignoreInvitesPolicies","policyRooms","senderServer","entities","roomServer","regexp","hasChanges","sourceRooms","policies","_this$client$getAccou","hasIgnoreInvitesPolicies","_value","RUST_SDK_STORE_PREFIX","ALPHABET","BASE_MAP","xc","BASE","LEADER","FACTOR","iFACTOR","encode","zeroes","length","pbegin","pend","size","b58","carry","it1","it2","decodeUnsafe","psz","charCode","it3","b256","it4","vch","decode","bs58","CryptoEvent","DecryptionFailureCode","DeviceIsolationModeKind","AllDevicesIsolationMode","errorOnVerifiedUserProblems","UserVerificationStatus","crossSigningVerified","crossSigningVerifiedBefore","tofu","needsUserApproval","DeviceVerificationStatus","_opts$signedByOwner","_opts$crossSigningVer","_opts$tofu","_opts$localVerified","_opts$trustCrossSigne","ImportRoomKeyStage","CrossSigningKey","EventShieldColour","EventShieldReason","zeroSalt","deriveKeys","_deriveKeys","hkdfkey","keybits","aesKey","hmacKey","aesProm","hmacProm","encryptAESSecretStorageItem","_encryptAESSecretStorageItem","ivStr","iv","encodedData","ciphertext","hmac","decryptAESSecretStorageItem","_decryptAESSecretStorageItem","SECRET_STORAGE_ALGORITHM_V1_AES","ServerSideSecretStorageImpl","accountDataAdapter","callbacks","_defaultKey$key","defaultKey","keyId","isSameKey","newValue","algorithm","keyInfo","mac","calculateKeyCheck","trimTrailingEquals","secret","defaultKeyId","_keyId","_keyInfo","_keys","encryption","secretInfo","_keyId2","_keyInfo2","_encInfo","decryption","encInfo","_keyId3","_keyInfo3","returned","privateKey","ZERO_STR","sha256","_sha","utf8","plaintext","digest","checkRtcMembershipData","errors","referenceUserId","_data$sticky_key","checkSessionsMembershipData","_data$focus_active","CallMembership","membershipData","rtcBackendIdentity","memberId","sessionErrors","rtcErrors","details","json","_this$logger2","application","_this$logger","compatibilityAdaptedId","slotDescriptionToId","_application","_id","_this$logger3","_data$membershipID","_data$created_ts","_data$expires","DEFAULT_EXPIRE_DURATION","oldestMembership","Status","isMyMembership","ActionScheduler","membershipLoopHandler","update","parentLogger","MembershipActionType","wakeupUpdate","wakeupPromise","nextAction","handlerResult","actionUpdate","_this$wakeup","_this$wakeup2","InvalidCryptoStoreState","InvalidCryptoStoreError","ClientStoppedError","UnsupportedDelayedEventsEndpointError","clientEndpoint","UnsupportedStickyEventsEndpointError","MembershipManagerEvent","isLivekitTransportConfig","_objectSpread$4","ownKeys$4","MEMBERSHIP_STICKY_DURATION_MS","createInsertActionUpdate","createReplaceActionUpdate","MembershipManager","multiSfuFocus","fociPreferred","onError","_this$leavePromiseRes","_this$leavePromiseRes2","memberships","sendingMembershipActions","joinConfig","slotDescription","rootLogger","_this$joinConfig$netw","_this$joinConfig","_this$joinConfig$memb","_this$joinConfig2","_this$joinConfig$memb2","_this$joinConfig3","iteration","_this$delayedLeaveEve","_this$joinConfig4","_this$joinConfig$dela","_this$joinConfig5","_this$joinConfig$maxi","_this$joinConfig6","_this$joinConfig$maxi2","_this$joinConfig7","_this$joinConfig$dela2","_this$joinConfig8","repeatActionType","delayId","probablyLeft","durationUntilServerDelayedLeave","abortPromise","_","actionsWithoutUpdateExpiry","nextExpireUpdateIteration","needsEmptyStringRoomFix","slotId","expires","_this$fociPreferred","_this$fociPreferred2","ownMembership","focusObjects","maxDelayAllowed","updateLimit","updateNetwork","_this$state$rateLimit","rateLimitRetries","resendDelay","_this$state$networkEr","retryCounterString","retryDuration","retryDurationString","StickyEventMembershipManager","clientWithSticky","sessionDescription","_StickyEventMembershi","relationObject","livekitTransport","KeyTransportEvents","getEncryptionKeyMapKey","EncryptionManager","_this$joinConfig$upda","_this$joinConfig$make","_this$joinConfig$useK","getMemberships","transport","statistics","onEncryptionKeysChanged","myKeys","indexToSend","keyIndexToSend","keyToSend","targets","safeGetRetryAfterMs","keyBase64Encoded","newKeyIndex","keysMap","userKeyEntry","entry","_this$joinConfig$mana","oldMemberships","newMembershipIds","anyLeft","oldMembershipIds","anyJoined","oldFingerprints","newFingerprints","candidateUpdates","delayBeforeUse","encryptionKey","secureRandomBase64Url","encryptionKeyIndex","_this$encryptionKeys$","encryptionKeyString","keyBin","participantKeys","existingKeyAtIndex","keysEqual","useKeyTimeout","OutdatedKeyFilter","_this$tsBuffer$get","latestTimestamp","RTCEncryptionManager","rtcBackendIdProvider","candidateInboundSession","outdated","_this$logger4","keyInfoTemp","keyIndex","knownRtcMembership","fullMembership","_this$logger5","_joinConfig$manageMed","_joinConfig$unstableS","_joinConfig$useKeyDel","_joinConfig$keyRotati","_this$logger6","_this$logger7","_this$logger8","_this$logger9","_this$logger0","_this$logger1","_this2$outboundSessio","_this2$outboundSessio2","isFirstKey","firstKey","toShareWith","alreadySharedWith","toDistributeTo","outboundKey","hasKeyChanged","newOutboundKey","keyAge","_this2$logger","_this2$logger2","_newOutboundKey","_this2$logger3","_this2$logger4","_this2$logger5","_this2$logger6","_this2$logger7","_this$logger10","NotSupportedError","ToDeviceKeyTransport","fromUser","age","hardcodedMemberIdAlternative","_content$member$id","RoomKeyTransport","isRetry","matrixError","_objectSpread$3","ownKeys$3","MatrixRTCSessionEvent","slotIdToDescription","_this$membershipManag","_this$membershipManag2","_this$membershipManag3","_this$slotDescription","DEFAULT_SESSION_MEMBERSHIPS_FOR_SLOT_OPTS","collectMembersEvents","callMemberships","computeBackendIdentityAndVerifyMemberEvents","callMemberEvents","roomSubset","calculateMembershipsOpts","_this$encryptionManag","MatrixRTCSession","changed","_this$membershipManag4","_this$membershipManag5","_this$membershipManag6","_this$membershipManag7","_this2$membershipMana","ownMembershipIdentity","_client","_transport","leavePromise","_this$getOldestMember","_this$memberships$fin","getFirstCallIntent","_this4$membershipMana","_this4$membershipMana2","_this$encryptionManag2","keyRing","thisExpiry","soonestExpiry","notificationType","sendNotificationEvent","newResult","errorLegacy","errorNew","_computeBackendIdentityAndVerifyMemberEvents","quickFilterNonRelevantContents","isValidMembership","eventKeysCount","_membership$userId","listenForMemberStateEvents","listenForStickyEvents","callMemberStateEvents","callMemberStateEvent","MatrixRTCSessionManagerEvents","MatrixRTCSessionManager","_this$client$getRooms","sess","isNewSession","wasActiveAndKnown","nowActive","getRelationsThreadFilter","_e$content","_e$content2","InvalidTokenError","nopLogger","Log","Log2","reset","setLevel","setLogger","_Logger","_name","methodLogger","staticMethod","staticLogger","ErrorResponse","form","_a","_b","_c","ErrorTimeout","InMemoryWebStorage","ErrorDPoPNonce","nonce","JsonService","additionalContentTypes","_jwtHandler","_extraHeaders","init","timeoutInSeconds","timeoutId","credentials","logger2","basicAuth","initCredentials","extraHeaders","responseText","customKeys","protectedHeaders","headerName","MetadataService","_settings","optional","jwks_uri","keySet","WebStorageStateStore","DefaultResponseType","DefaultScope","DefaultClientAuthentication","OidcClientSettingsStore","authority","metadataUrl","signingKeys","metadataSeed","client_id","client_secret","response_type","redirect_uri","post_logout_redirect_uri","client_authentication","prompt","display","max_age","ui_locales","acr_values","response_mode","filterProtocolClaims","loadUserInfo","requestTimeoutInSeconds","staleStateAgeInSeconds","DefaultStaleStateAgeInSeconds","mergeClaimsStrategy","disablePKCE","stateStore","revokeTokenAdditionalContentTypes","fetchRequestCredentials","refreshTokenAllowedScope","extraQueryParams","extraTokenParams","dpop","omitScopeWhenRequesting","OidcError","isRecord","wellKnown","optionalStringProperty","authMetadata","requiredStringProperty","optionalStringArrayProperty","requiredArrayValue","OAuthGrantType","isValid","isInvalid","ownKeys$2","_objectSpread$2","discoverAndValidateOIDCIssuerWellKnown","issuer","issuerOpenIdConfigUrl","issuerWellKnownResponse","issuerWellKnown","validateAuthMetadataAndKeys","validatedIssuerConfig","validateAuthMetadata","metadataService","_excluded","ownKeys$1","TURN_CHECK_INTERVAL","UNSTABLE_MSC2666_SHARED_ROOMS","UNSTABLE_MSC2666_MUTUAL_ROOMS","UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS","UNSTABLE_MSC4140_DELAYED_EVENTS","UNSTABLE_MSC4354_STICKY_EVENTS","UNSTABLE_MSC4133_EXTENDED_PROFILES","STABLE_MSC4133_EXTENDED_PROFILES","EVENT_ID_PREFIX","SSO_ACTION_PARAM","MatrixClient","_opts$logger","_opts$usingExternalCr","_opts$disableVoip","_opts$enableEncrypted","_opts$cryptoCallbacks","MediaHandler","supportsMatrixCall","_this$getRooms","unreadRooms","currentUserId","eventToSend","fixNotificationCountOnDecryption","newStore","fwdPagination","SlidingSyncSdk","_this$cryptoBackend","_this$syncApi","_this$peekSync","_this$callEventHandle","_this$groupCallEventH","deleteRustSdkStore","indexedDB","dbname","prom","req","_args$cryptoDatabaseP","_args$cryptoDatabaseP2","_this$credentials$use","_this$credentials","_this$credentials2","_this$credentials$use2","_this$credentials3","force","support","_this$syncApi$getSync","_this$syncApi2","guest","_this$syncApi$retryIm","set","caps","_args$cryptoDatabaseP3","_this6$legacyPickleKe","RustCrypto","rustCrypto","progress","sessionId","queryData","useAuthenticatedMedia","allRooms","visibleRooms","_room2","predecessors","existingData","updatedResolvers","accountDataListener","utils.encodeUri","_data","msc3391DeleteAccountDataServerSupport","roomIdOrAlias","_roomMember$events$me","preJoinMembership","inviter","_roomMember$events$me2","signPromise","_url","signedInviteObj","bundleDownloaded","resolvedRoom","syncApi","tagName","_this10$getRoom","beaconInfoContent","threadIdOrEventType","eventTypeOrContent","contentOrTxnId","txnIdOrVoid","_content$mRelates_to","isReply","_content$mRelates_to2","_objectSpread$1","_this$getRoom","_thread$lastReply$get","_thread$lastReply","eventObject","delayOpts","targetId","queryDict","delayOptsOrQuery","queryOpts","cancelled","_this15$cryptoBackend","_this$getRoom2","queryOrDelayOpts","pathParams","_pathTemplate","getUnstableDelayQueryOpts","_opts2","withRelTypesPropName","sendContent","_threadId","_threadId2","_threadId3","_threadId4","_threadId5","_threadId6","_threadId7","_threadId8","stickDuration","fromToken","_arguments4","requestOptions","_arguments5","_arguments6","_arguments7","_arguments8","_arguments9","_arguments0","shouldAddThreadId","fullBody","_arguments1","rmEventId","rrEvent","rpEvent","rrEventId","rpEventId","notificationEventId","isTyping","timeoutMs","verifyLinks","currentRoom","after","_room$findPredecessor","seenRoomIDs","predecessorRoomId","predecessorRoom","tombstone","_room$findPredecessor2","tombstoneEvent","successorRoom","_successorRoom$findPr","roomIds","ref","_arguments10","_this30$cryptoBackend","email","medium","address","identityServerUrl","_this31$identityServe","identityAccessToken","includeFuture","upgradeHistory","eligibleToLeave","_room3","populationResults","doLeave","_room4","_arguments11","deleteRoom","forceRecalculate","mxcUrl","_this35$syncApi","_this35","validStates","_this36","timeToWaitMs","timeWaitedMs","SCROLLBACK_DELAY_MS","numAdded","_res$end","_res$end2","threadedEvents","unknownRelations","_this37$clientOpts","_this37","_res$events_after","_res$events_before","_res$state","_this38","_timelineSet$getTimel","_timelineSet$room$fin","_yield$_this38$getThr","_res$end3","_this39","recurse","_resOlder$next_batch","resOlder","resNewer","_event2","_timelineSet$thread","_timelineSet$getTimel2","_resOlder$next_batch2","_thread","_resOlder","eventsNewer","nextBatch","_resNewer","_event3","_timelineSet$thread2","_timeline","_originalEvent","_this40","_res$chunk","_res$chunk2","_res","_this40$clientOpts","messagesPath","_params","_res2","_res2$chunk","_this$clientOpts","timelineFilter","_timelineFilter$getRo","_this$clientOpts2","_timelineFilter$getRo2","_res$chunk3","eventTimeline","_this41","isNotifTimeline","pendingRequest","_opts$limit","_event4","_eventTimeline$getRoo","_eventTimeline$getRoo2","_room5","_event5","newToken","_thread$rootEvent","_eventTimeline$getRoo3","atEnd","_this$peekSync2","readPromise","clientSecret","sendAttempt","nextLink","phoneCountry","phoneNumber","endpoint","_this42","postParams","_this$pushRules$scope","mute","hasDontNotifyRule","roomPushRule","doneResolvers","err2","searchResults","searchOpts","_roomEvents$results","highlights","hl","resultsLength","_roomEvents$results$l","sr","_room6","allowCached","_this43","existingId","utils.deepCompare","newDef","oldDef","createdFilter","_this44","credentialsGood","remainingTime","servers","allow","_this45$getDomain","_this45","primTypes","_this46","sharedRoomsSupport","mutualRoomsSupport","queryMutualRoomsSupport","query","tokenQuery","_this47","_this48","serverVersions","_this49","_this50","unstableFeatures","presetName","_this51","versionsPresetName","_this52","FeatureSupport","threadStable","listUnstable","listStable","fwdPaginationStable","threadUnstable","determineFeatureSupport","fwdPaginationUnstable","_this$clientOpts3","_arguments12","_this53","_result$next_batch","_result$prev_batch","fetchedEventType","eventResult","allEvents","serviceType","_this$idBaseUrl","_this$idBaseUrl2","stripProto","_this$http$opts$refre","username","password","auth","bindThreepids","guestAccessToken","inhibitLogin","performRefreshRequestWithPrefix","redirectUrl","loginType","idpId","_this54","_arguments13","_this55","stopClient","erase","_this56","authSessionId","_this57$identityServe","invitesNeedingToken","_this57","utils.encodeParams","queryString","templatedUrl","excludeMembership","atEventId","includeMembership","newVersion","_arguments14","_this58","_this59","_limit$toString","_this60","since","_queryParams","_body","visibility","term","_this61","_this62","_this63","_this64","profile","_this65","_this66","_this67","_this68","_this69","_this70","_this71","authDict","newPassword","logoutDevices","_this72","pusher","pushKey","appId","_ref1","abortSignal","keyAlgorithm","queries","_deviceId","oldToken","uri","sid","msisdnToken","addressPairs","_this73","hashes","localMapping","_ref10","addr","med","hashed","hashBuffer","unhashed","foundAddresses","mxid","plainAddress","_this74","mapping","_this75","originalQuery","v1results","deviceMessages","payload","_this76","termsUrls","score","maxDepth","suggestedOnly","_this77","_purposeEvent$getCont","purposeEvent","proxyBaseUrl","clientTimeout","_this$clientOpts4","via","_this78","_path","_this79","_this80","useStable","_this81","_ref11","_actions$tweaks","ourUserId","hasReadEvent","newHighlight","newCount","newNotify","_newCount","isRelatedToRoot","_opts$pendingEventOrd","redaction","_this$lastEvent","eventData","_this$client$canSuppo","recursionSupport","_this$getReadReceiptF","oldReceiptEventId","receiptEvent","emit","lastReply","isNewestReply","_this$client$canSuppo2","_this$replayEvents","_this$timelineSet$rel","receipts","bundledRelationship","unfilteredPendingEvents","_this$lastEvent2","oldLive","newLive","newBackward","oldForward","_this8$client$canSupp","isAnEncryptedThreadMessage","editEvent","_event$event","_this$lastPendingEven","isCurrentUser","beforeFirstThreadedReceipt","lastReplyId","readUpToId","unthreadedReceipt","_this$timeline","_ev$getId","_this$lastReply$getTs","_this$lastReply","_this$room$getLastUnt","_this$room$getLastUnt2","_this$lastReply$getTs2","_this$lastReply2","unthreadedReceiptTs","beforeLastUnthreadedReceipt","threadFilterTypeToFilter","DecryptionError","detailedStringForDecryptionError","MESSAGE_VISIBLE","MAX_STICKY_DURATION_MS","_this$sender","_this$target","affectsSelf","newTarget","_event$content","_event$content2","_this$getTs","_ExtensibleEvents$par","_this$getDate","msgid","_this$clearEvent$cont","_this$_replacingEvent","_this$getWireContent","relatesTo","threadDetails","_this$getWireContent$","_this$getWireContent2","cryptoType","cryptoContent","senderCurve25519Key","claimedEd25519Key","alreadyDecrypted","recipients","detailedError","decryptionResult","_decryptionResult$sen","_decryptionResult$cla","_visibilityChange$vis","_visibilityChange$rea","visible","REDACT_KEEP_KEYS","keeps","REDACT_KEEP_CONTENT_MAP","_this$clearEvent","_this$event$unsigned","_this$clearEvent$unsi","_this$clearEvent2","_this$getAge","oldUnsigned","oldId","relType","_this$getWireContent3","_this$getUnsigned$mR","_this$_replacingEvent2","otherEvent","myProps","deepSortedObjectEntries","theirProps","_this$event$unsigned2","_this$event$msc4354_s","ReceiptAccumulator","receiptsForThread","receiptEventContent","receiptData","_receiptData","Category","isTaggedEvent","SyncAccumulator","syncResponse","fromDatabase","category","currentData","hasAdded","_data$state","_data$orgMatrixMsc","_data$timeline","_data$msc4354_sticky","_sum$HEROES_KEY","_sum$JOINED_COUNT_KEY","_sum$INVITED_COUNT_KE","HEROES_KEY","INVITED_COUNT_KEY","JOINED_COUNT_KEY","sum","_data$ephemeral","setState","_data$timeline$prev_b","transformedEvent","_e$unsigned","expiresTs","cappedDuration","createdTs","startIndex","forDatabase","_roomData$_stickyEven","roomJson","evType","msgData","rollBackState","prevStateEvent","accData","eventMap","exists","dbName","db","DB_MIGRATIONS","oobMembersStore","VERSION","selectQuery","keyRange","resultMapper","_query$error","cursor","results","txnAsPromise","txn","reqAsEventPromise","reqAsPromise","reqAsCursorPromise","idbExists","onClose","oldVersion","migration","_this$db","accountData","tx","roomIndex","range","request","oobWritten","record","markerObject","readTx","roomRange","minStateKeyProm","maxStateKeyProm","maxStateKey","writeTx","membersKeyRange","minStateKey","writeStore","_this$db2","_req$error","userTuples","roomsData","tuples","tuple","_cursor$value","resultBatch","_this0$db","IndexedDBStoreWorker","postMessage","_this$backend","_this$backend2","_this$backend3","_this$backend4","_this$backend5","_this$backend6","_this$backend7","_this$backend8","_this$backend9","_this$backend0","_this$backend1","_this$backend10","_this$backend11","_this$backend12","_this$backend13","_this$backend14","LocalIndexedDBStoreBackend"],"mappings":"AAAA,SAASA,GAAQC,EAAG,CAClB,0BAEA,OAAOD,GAAwB,OAAO,QAArB,YAA2C,OAAO,OAAO,UAA1B,SAAqC,SAAUC,EAAG,CAChG,OAAO,OAAOA,CAChB,EAAI,SAAUA,EAAG,CACf,OAAOA,GAAmB,OAAO,QAArB,YAA+BA,EAAE,cAAgB,QAAUA,IAAM,OAAO,UAAY,SAAW,OAAOA,CACpH,EAAGD,GAAQC,CAAC,CACd,CCPA,SAASC,GAAYC,EAAGC,EAAG,CACzB,GAAgBJ,GAAQG,CAAC,GAArB,UAA0B,CAACA,EAAG,OAAOA,EACzC,IAAIE,EAAIF,EAAE,OAAO,WAAW,EAC5B,GAAeE,IAAX,OAAc,CAChB,IAAIC,EAAID,EAAE,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h5G,EAAA,KAAA,CAAA,EAAAA,EAAA,KAAA,CAAA,CAAA,EACrB,MACV,IAAU,sBACGi5G,EAAoB,KAAA,WAAA,MAAAA,IAAA,OAAA,OAAAA,EAAA,iBAAA,EACvB,MACV,IAAU,wBACGC,EAAqB,KAAA,WAAA,MAAAA,IAAA,OAAA,OAAAA,EAAA,mBAAAl5G,EAAA,KAAA,CAAA,CAAA,EACxB,MACV,IAAU,yBACGm5G,EAAA,KAAwB,WAAA,MAAAA,IAAA,OAAA,OAAAA,EAAA,oBAAAn5G,EAAA,KAAA,CAAA,CAAA,EAC3B,MACV,IAAU,4BACGo5G,EAAqB,KAAA,WAAA,MAAAA,IAAA,OAAA,OAAAA,EAAA,uBAAA,EACxB,MACV,IAAU,sBACVxlB,GAAAylB,EAAA,KAAA,WAAA,MAAAA,IAAA,OAAA,OAAAA,EAAA,oBAAAr5G,EAAA,KAAA,CAAA,CAAA,EACU,KACV,CACA,GAAU4zF,IAAS,OAAU,CAC7B,KAAa,YAAS,CACtB,QAAA,WACU,IAAK5zF,EAAE,IAET,MAAA,sBACF,CAAA,EACA,MACN,CACA4zF,EAAU,KAAA31E,GAAS,CACnB,KAAa,YAAS,KAAA,KAAA,CACZ,QAAQ,cACR,IAAAje,EAAA,IACD,OAAOie,CACRnf,CAAAA,CACR,KAAa,CACboiB,EAAiB,MAAE,0BAAUlhB,EAAA,QAAAkM,CAAA,EAC7B,KAAa,YAAS,KAAA,KAAA,CACtB,QAAA,WACU,IAAKlM,EAAE,IAEjB,MAAgB,CAChB,QAAAkM,EAAA,QACU,KAAAA,EAAA,IACF,CACF,CAAA,CACJ,CAAA,CACF,CAAA,ECtIA","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176]}